Iterating through list and getting even and odd numbers

2024/9/22 5:37:56

yet one more exercise that I seem to have a problem with. I'd say I've got it right, but Python knows better.

The body of the task is:

Write a function that takes a list or tuple of numbers. Return a two-element list, containing (respectively) the sum of the even-indexed numbers and the sum of the odd-indexed numbers. So calling the function as even_odd_sums([10, 20, 30, 40, 50, 60]) , you’ll get back [90, 120] .

My code is:

def even_odd_sums(sequence):sum_list = []for i, v in enumerate(sequence):if i % 2 == 0:sum_list = sum_list.insert(0, sum(v))else:sum_list = sum_list.insert(1, sum(v))return sum_listprint(even_odd_sums([10,20,30,40,50,60]))

the result is:

TypeError                                 Traceback (most recent call last)
<ipython-input-60-14518295929c> in <module>
----> 1 print(even_odd_sums([10,20,30,40,50,60]))<ipython-input-59-51fcb6e9a115> in even_odd_sums(sequence)3     for i, v in enumerate(sequence):4         if i % 2 == 0:
----> 5            sum_list = sum_list.insert(0, sum(v))6         else:7            sum_list = sum_list.insert(1, sum(v))TypeError: 'int' object is not iterable

I tried to find the solution on Google, I tried other ways to solve this task ("for i in range(len(sequence)), but I just can't solve non-iterable object problem

Thank you in advance!

Answer

As has been pointed out, sum takes an iterable, not a number. So, with your loop-approach, you could just keep adding to the proper sum:

def even_odd_sums(sequence):sum_list = [0, 0]for i, v in enumerate(sequence):sum_list[i % 2] += vreturn sum_list

Or, you can do the much simpler summation of the appropriate slices:

def even_odd_sums(sequence):return [sum(sequence[::2]), sum(sequence[1::2])]
https://en.xdnf.cn/q/119618.html

Related Q&A

Cannot import tensorflow-gpu

I have tried to import tensorflow-gpu and Im getting the same error with different versions of CUDA and cuDNN. My GPU is compatible with CUDA and I have no problems installing but when I try to import …

comparing two Dataframe columns to check if they have same value in python

I have two dataframes,new1.Name city0 sri won chn1 pechi won pune2 Ram won mum0 pec won keralanew3req 0 pec 1 mutI tried, mask=new1.Name.str.contains("|".join(…

Input gravity forms entries in a database locally stores (created with python)

I hope you are all doing alright. Is it possible to connect a gform entry to a database created with Python and stored in my PC with a little variation of the following code? add_action("gform_af…

Cant get javascript generated html using python

Im trying to create a python script that automatically gets the content of a table on a webpage. I manage to have it to work on pure html page, but there is one website that gives me headache... The ht…

Python: Extract text from Word files in a url

Given the url containing a certain file, in this case a word document, read the contents of the document. I have seen several examples of how to extract text from local documents but not from a url. Wo…

Python3:Plot f(x,y), preferably using matplotlib

Is there a way, preferably using matplotlib, to plot a 2-variable function f(x,y) in python; Thank you, in advance.

Why does my cronjob not send the email from my script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to delete unsaved tkinker label?

I made this program where I am putting labels on a grid without saving them in a variable. I do this because then I can for loop through a list of classes and get the data from each class in and add th…

Adjust every other row of a data frame

I would like to change every second row of my data frame.I have a df like this:Node | Feature | Indicator | Value | Class | Direction -------------------------------------------------------- 1 | …

Why is the list index out of range?

Im new at programing and Im trying to check a piece of code that keeps giving me this error: t[i] = t[i - 1] + dt IndexError: list index out of rangeThe code is the following: dt = 0.001t = [0] for i i…