Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Int not iterable error

Tags:

python

I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:

TypeError: 'int' object is not iterable

Any help would be appreciated.

n = 100
p = 0
while p<n:
   p = p + 1
x = range(0, p)

# check to see if numbers are divisable by 3 or 5
def numcheck(x): 
   for numbers in x:
      if numbers%3==0 and numbers%5==0:
          sum(numbers)
numcheck(x)
like image 373
TheOneTrueMorty Avatar asked Oct 17 '09 20:10

TheOneTrueMorty


3 Answers

In the for-loop

for numbers in x:

"numbers" steps through the elements in x one at a time, for each pass through the loop. It would be perhaps better to name the variable "number" because you are only getting one number at a time. "numbers" equals an integer each time through the loop.

sum(numbers)

throws a TypeError because the function sum() expects an iterable object (like a list of numbers), not just one integer.

So perhaps try:

def numcheck(x):
    s=0
    for number in x:
        if number%3==0 and number%5==0:
            s+=number
    print(s)
numcheck(range(1000))
like image 193
unutbu Avatar answered Sep 25 '22 19:09

unutbu


numbers needs to be a list or similar when it is passed to sum(). In the code example above, it is an integer - one of the integers from x.

Try something like:

numbers = [num for num in x if num%3==0 and num%5 ==0]
print sum(numbers)
like image 42
Stephen Doyle Avatar answered Sep 23 '22 19:09

Stephen Doyle


The sum function expects a list, not a single number.

When you do for numbers in, then the variable numbers has a single integer object. Add a print statement, you'll see that numbers is a single number.

You might want to accumulate all the multiples of 3 and 5 in a list. Once you have the list, you can then use the sum function on that list.

like image 21
S.Lott Avatar answered Sep 25 '22 19:09

S.Lott