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)
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))
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With