Reputation: 13
The input (list) would be a list similar to [[1,2],[5,6],[4,6]]
. I am trying to add the whole row together to test if it is even or odd.
def evenrow(list):
for row in list:
for item in row:
newNums+=item
n=sum(newNums)
print(n)
Upvotes: 1
Views: 117
Reputation: 8837
Just an alternate method:
def evenrow(lst):
return sum(map(sum,lst))%2 == 0 #True if even, False otherwise.
This works this way:
The outer sum
adds up all items of the map
, which applies sum
to each item in lst
. In python2, map returns a list
object, while in python3, it returns a map
object. This is passed to the outer sum
function, which adds up all items in your map
.
def evenrow(lst):
return sum(itertools.chain(*a)) % 2 == 0
This expands all the items in a
(each of the sublists), and chains them together, as a chain
object. It then adds together all the items and determines if the sum is even.
Upvotes: 1
Reputation: 29416
You don't need the following line of code: n=sum(newNums)
. You already summed up all the items of row in the newNums += item
line. Second, you have to declare newNums
before using it in your code. So, the fixed version of code will look like this:
def evenrow(list):
for row in list:
newNums = 0
for item in row:
newNums += item
print(newNums)
BTW: You should consider accepting answers to some of your previous questions, otherwise nobody will spend their time to answer your new questions.
Upvotes: 0
Reputation: 29093
First of all do not use 'list' as variable name. Second you calling sum for int value not for a list and that's why you getting error. Check your code please.
Not sure but your code can looks like:
def evenrow(list):
for row in list:
value = sum(row)
if values is even: # put your condition here
# do something
else:
print "Value is odd"
Upvotes: 2