Posts: 18
Threads: 7
Joined: Jan 2019
So this was the question description :
# Write a Python function to sum all the numbers in a list.
# Sample List : (8, 2, 3, 0, 7)
# Expected Output : 20
This is my code :
lst = []
i = 0
sum = 0
print ("Enter how many numbers:")
x = input()
while i < int(x):
print ("Enter number: ")
y = input()
lst.append(y)
i = i + 1
def sum():
for i in range(x-1):
sum = lst[i] + sum
i = i + 1
print ("sum") When I tried to run the code in my terminal, I got the prompt to enter how many numbers there were in the list and also the prompt to enter the individual numbers. However, the code ends there immediately ... it doesn't print out the sum of the numbers. What am I missing, please advise thanks alot !
Posts: 12,029
Threads: 485
Joined: Sep 2016
are you required to write the sum function? there is a bulit-in one
>>> xx = [1,2,3,4,5,6]
>>> sum(xx)
21
Posts: 18
Threads: 7
Joined: Jan 2019
(Jan-20-2019, 01:19 PM)Larz60+ Wrote: are you required to write the sum function? there is a bulit-in one
>>> xx = [1,2,3,4,5,6]
>>> sum(xx)
21
I wanted to do it without using the built-in function for practice
Posts: 1,950
Threads: 8
Joined: Jun 2018
Jan-20-2019, 02:01 PM
(This post was last modified: Jan-20-2019, 02:01 PM by perfringo.)
Some observations:
- sum() is Python built-in function. Never use it as name.
- I personally prefer take user input in following way (subjectively it's more readable): x = int(input("Enter how many numbers: ))
- otherwise your code a quite a mess; you set sum to zero then create function with same name. You use name sum inside of function sum; function is defined but never used etc.
Function should be quite simple: you have list, you define total with value zero, you iterate over list elements and add all elements to total, you return total.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 7,315
Threads: 123
Joined: Sep 2016
(Jan-20-2019, 01:40 PM)MrGoat Wrote: I wanted to do it without using the built-in function for practice Can do it like this.
>>> tup = (8, 2, 3, 0, 7)
>>> total = 0
>>> for n in tup:
... total += n
...
>>> total
20
Posts: 1,950
Threads: 8
Joined: Jun 2018
Jan-20-2019, 02:29 PM
(This post was last modified: Jan-20-2019, 02:29 PM by perfringo.)
If you want to practice even more then you could enter wonderful world of recursion.
One way of sum list elements:
>>> def sum_of_list_elements(lst):
... if not lst:
... return 0
... else:
... return lst[0] + sum_of_list_elements(lst[1:])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 18
Threads: 7
Joined: Jan 2019
(Jan-20-2019, 02:29 PM)perfringo Wrote: If you want to practice even more then you could enter wonderful world of recursion.
One way of sum list elements:
>>> def sum_of_list_elements(lst):
... if not lst:
... return 0
... else:
... return lst[0] + sum_of_list_elements(lst[1:])
How come the parameter of function can be a list? --> 1st line of your code
Posts: 1,950
Threads: 8
Joined: Jun 2018
Jan-20-2019, 02:50 PM
(This post was last modified: Jan-20-2019, 03:13 PM by perfringo.)
(Jan-20-2019, 02:37 PM)MrGoat Wrote: How come the parameter of function can be a list? --> 1st line of your code
Why can't function be defined with list as parameter and given argument as list if used?
This function can handle tuples as well, with converting also dictionaries:
>>> sum_of_list_elements((8, 2, 3, 0, 7))
20
>>> sum_of_list_elements([8, 2, 3, 0, 7])
20
>>> sum_of_list_elements(list({1: 10, 2: 20})) # sum of dict keys
3
>>> sum_of_list_elements(list({1: 10, 2: 20}.values())) # sum of dict values
30
In real-life scenarios always use built-in function sum() as Larz60+ suggested.
However, if you are in process of learning and expanding your knowledge it is useful to play with different code snippets. For example, if you are in process of learning recursion and algorithms at the same time you can combine them into function which sums list elements. Combining "divide and conquer" with recursion enables us to express list elements sum function as follows:
def sum_of_list_elements(lst):
if not lst:
return 0
elif len(lst) == 1:
return lst[0]
else:
middle = len(lst) // 2
return sum_of_list_elements(lst[:middle]) + sum_of_list_elements(lst[middle:])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 10
Threads: 0
Joined: Jan 2019
Jan-27-2019, 06:03 PM
(This post was last modified: Jan-27-2019, 06:05 PM by snippsat.)
#Working code
lst = []
i = 0
print("Enter how many numbers:")
x = input()
while i < int(x):
print("Enter number: ")
y = input()
lst.append(int(y))
i = i + 1
def sum1():
sum=0
for z in range(0,int(x)):
sum =lst[z] + sum
print(sum)
sum1()
|