Question 1:
To sum a list of numbers, use sum:
xs = [1, 2, 3, 4, 5]
print(sum(xs))
This outputs:
15
Question 2:
So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.
We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use zip to take pairs from two lists.
I assume you want to see decimals in the result, even though your input values are integers. By default, Python does integer division: it discards the remainder. To divide things through all the way, we need to use floating-point numbers. Fortunately, dividing an int by a float will produce a float, so we just use 2.0 for our divisor instead of 2.
Thus:
averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]
Answer from Karl Knechtel on Stack OverflowQuestion 1:
To sum a list of numbers, use sum:
xs = [1, 2, 3, 4, 5]
print(sum(xs))
This outputs:
15
Question 2:
So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.
We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use zip to take pairs from two lists.
I assume you want to see decimals in the result, even though your input values are integers. By default, Python does integer division: it discards the remainder. To divide things through all the way, we need to use floating-point numbers. Fortunately, dividing an int by a float will produce a float, so we just use 2.0 for our divisor instead of 2.
Thus:
averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]
To sum a list of numbers:
sum(list_of_nums)
Generate a new list with adjacent elements averaged in xs using a list comprehension:
[(x + y) / 2 for x, y in zip(xs, xs[1:])]
Sum all those adjacent elements into a single value:
sum((x + y) / 2 for x, y in zip(xs, xs[1:]))
Can someone explain to me how to add up all the numbers in a list without using sum?
Sum of Lists (Python)
Hi there, so Iโm currently learning about lists and loops and my friend challenged me to add up a entire list without using sum
So far my code looks like this (just the list as a variable)
ls = [1 , 5, 4, 3, 7]
In this exercise your function will receive three parameters,
a list of integers, and two integers. It will add up all values
in the list that do not equal either of the two integers.
This is what I have:
def sumniout(nums, a, b):
for num in nums:
if num == a or num == b:
total = sum(nums) - a - b
else:
total = sum(nums)
return total
print(suminout([1,2,3,4], 1,2)) Example of it working:
suminout([1, 2, 3, 4], 1, 2) -> 7
My code gives me the right results sometimes. For example, if I run a test on print(suminout([1,2,3,4,5], 1,1)) I get 13 when I should get 14. Any ideas to get me on the right track?