DEV Community

Discussion on: Sum of first "n" odd numbers with Python

Collapse
 
anatoliyaksenov profile image
Anatoliy A Aksenov

For thought:

# our input array
a = [1,10,6,7,8,9,11,12,2,3,4,5,13,18,14,15,16,17,19]
  • sums odd numbers by sorted input:
first_n = 4
sum([x for x in sorted(a) if x%2 != 0][:first_n])

or sums odd numbers by unsorted input

first_n = 4
sum([x for x in a if x%2 != 0][:first_n])
  • for even numbers
first_n = 4
sum([x for x in sorted(a) if x%2 == 0][:first_n])