Reputation: 27
def fillaray(size):
num = [0] * size
num = [random.randint(0,9) for i in range(size)]
print(num)
return num
def totalOdds(num, size):
for i in range (size):
if i % 2 ==0:
odd = num[i]
i+1
print(odd)
As you can see in def totalOdds()
I'm trying to separate the odd elements from the array "num." I plan on adding all the values in the odd elements up. Can someone point me in the right direction to what I'm doing wrong?
Thanks.
Upvotes: 1
Views: 10106
Reputation: 2618
to get all odd elements
odds = [n for n in nums if n%2]
to get only the sum of odd elements
sum_odds = sum(n for n in sums if n % 2)
Upvotes: 3
Reputation: 7944
nums = [1,2,3,4,5,6,7,8,9,10,11,12]
odds = [ n for n in nums if n%2 ]
print odds
Gives:
>>>
[1, 3, 5, 7, 9, 11]
This can be put into a function like so:
def getOdds(aList):
return [ n for n in aList if n%2 ]
Example usage:
myOdds = getOdds(nums)
print("{0} has {1} odd numbers which were {2}".format(nums,len(myOdds),myOdds))
print("The odd numbers sum to {0}".format(sum(myOdds)))
Produces:
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] has 6 odd numbers which were [1, 3, 5, 7, 9, 11]
The odd numbers sum to 36
As to what you're doing wrong, you're iterating over an iterable containing the elements 0
to size
this won't always be the value of num
(unless num
is indeed range(size)
). Once you make i
represent a value in num
which you're iterating over, if i%2 == 0
will mean it's even, if you want odds, the number musn't be divisible by two. Hence this should be changed to either if i%2 != 0
or if i%2
. You will also have to declare the odd
list before the for i ...
loop, so you can append the numbers in num
which meet the condition in the if i%2
selection control structure. You should appened the number in num
by doing odd.append(i)
, at the moment you're reassigning odd a new value. You also should not be incrementing i
. 'i' should represent a number in num
not the index of the number in num
.
Upvotes: 1
Reputation: 283133
Can be done in one line:
print sum(x for x in num if x & 1)
Also, see my comment under the question for where you went wrong.
Upvotes: 1
Reputation: 4114
If you are trying to find the sum of elements at odd places in the array :
def totalOdds(num, size):
for i in range(size):
if i % 2 ==0 :
odd += num[i]
print(odd)
If you are trying to sum the odd valued elements :
def totalOdds(num, size):
for i in range(size):
if num[i] % 2 !=0 :
odd += num[i]
print(odd)
Upvotes: 0