Question

The task is following: sum the list elements with even indexes and multiply the result by the last list's elemet. I have this oneliner solution code in Python.

array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41] 
print sum(i for i in array if array.index(i) % 2 == 0)*array[-1] if array != [] else 0

My result is -1476 ( The calculation is: 41*(-37-19+29+3-64+36+26+55+84-65) )

The right result is 1968.

I can't figure it out why this code is not working correctly in this particular case.

Was it helpful?

Solution 2

There is a repeated element 84 in the list, thus array.index does not work as you expected it to be. Also, your code has a quadratic complexity which is not required.

To fix your code with a minimum amount of edit, it would look something like this:

array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41] 
print sum(array[i] for i in range(len(array)) if i % 2 == 0)*array[-1] if array != [] else 0

OTHER TIPS

This is what you are looking for:

array[-1] * sum(array[::2])

array[::2] traverses the array from first index to last index in steps of two, i.e., every alternate number. sum(array[::2]) gets the sum of alternate numbers from the original list.

Using index will work as expected only when you are sure the list does not have duplicates, which is why your code fails to give the correct result.

>>> sum(x for i, x in enumerate(array) if not i % 2)*array[-1] 
1968

Use the built-in enumerate function, since there're duplicate elements in your list, and list.index(x) returns the index of the first element equal to x (as said in the documentation). Also take a look at the documentation on enumerate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top