TAGS :Viewed: 15 - Published at: a few seconds ago

[ Object of type int is not iterable ]

Here is my code:

NUM = 3                
A = [1,5,6,2,8,4,3,2,5]
B = []
m = []
check = False
summ=0
n = len(A) / NUM
while check == False: 
    for i in A:
        if A.index(i) >= n:
            B.append(m)
            m = []
            n *= 2
        m.append(i)
    B.append(m)
    for j in B:
        s1=(sum(B[0]))
        s2=(sum(B[1]))
        s3=(sum(B[2]))
    print(B)
    if s1==s2==s3:
        summ=s1
        check = True
    else:
        B = [0] * len(A)
        ilg = len(A)
        B[0]=A[ilg-1]
        for i in range(len(A)-1):
            B[i+1] = A[i]
        for i in range(len(A)):
            A[i]=B[i]

What I am trying to do is to split my list into 3 lists and if sum of numbers in those lists are equal print sum out, if not print 'FALSE'. For example: [1,2,3,4,5,6,7,8,9], after split: [1,2,3],[4,5,6],[7,8,9] but I am getting an error: s1=[sum(B[0])] TypeError: 'int' object is not iterable What I am doing wrong?

EDIT: Here what I have more, the part after else should change list from [1,5,6,2,8,4,3,2,5] to [5,1,5,6,2,8,4,3,2] and so on.

Answer 1


Your problem is this line:

B[0]=A[ilg-1]

You're assigning an integer to B[0], which is not an iterable object. On your second iteration around the loop, you pass B[0] to the sum function, which attempts to iterate over it, throwing the exception.

Answer 2


A = [1,5,6,2,8,4,3,2,5]
NUM = 3
n = len(A) / NUM
# here make sure that len(A) is a multiple of NUM
sums = [sum([item for item in A[i * NUM :(i + 1) * NUM]]) for i in range(n)]
# for python versions older than 3 use xrange instead of range.
for i in sums[1:]:
    if i != sums[0]:
        print "FALSE"
        break
else:
    print sums[0]

Answer 3


Note that with the following statements:

B = [0] * len(A)
ilg = len(A)
B[0] = A[ilg-1]

You are assigning to B[0] an int object, specifically for me is 5, so I guess that at position ilg-1 of the list A, you have that number.

I think you want or you should to do something else...

Usually, one good way to find out these kind of errors is to print or input the values or the types of your variables. Next time you will need no more help for this kind of problems!