How to find the difference between the sum of all even and odd elements of an array in the python – style

Completely the task is as follows:

Generate an array of integers ranging from 0 to 100 of a dimension of 10 by 20 (10 lines, 20 columns). Find the difference of the sum of all even and odd elements.

The array generated something like this:

import numpy as np a = np.random.random_integers(0, 100, 200).reshape(10,20) 
  • diff = a[even].sum() - a[~even].sum() where even = (a & 1) == 0 . - jfs
  • Thanks, that is necessary! - Alexey

1 answer 1

like so

 a = [1,2,3,4,5,6] print sum([0 if x % 2 != 0 else x for x in a]) - sum([0 if x % 2 == 0 else x for x in a]) 

it is possible and shorter

 print sum([x if x %2 == 0 else -x for x in a]) 

And if the teacher does not understand the generators, then so

 a = [1,2,3,4,5,6] s = 0 for x in a: if x % 2 == 0: s+=x else: s-=x print s 

UPD

in the comments, it is suggested that an even element should be understood as an element whose index is even. But it is worth clarifying. In any case, the code is even simpler (if you apply a slice).

 a = [1,2,3,4,5,6] print sum(a[0::2]) - sum(a[1::2]) 

and no enumerate .

  • if x% 2 == 0 is how? x is not an index, but a value, and you did not do it in enumerate (a) - vitidev
  • conditionally, you need to check the parity of the element, not the index. - KoVadim
  • one
    why do you think so?!. it does not say "even values". And "even element" is an element in place with an even sequence number. But I understand why you do not have in enumerate - vitidev
  • one
    @jfs, if you want to write an answer - write your answer. - KoVadim
  • one
    Oh, great, also decided to put -1. Super. - KoVadim