Reputation: 85
Okay so I made a list called numbersList, a variable number = 20, count = 0, and spot = 0.
numbersList = range(1, 11)
number = 20
count = 0
spot = 0.
I want to count the numbers in the list that go into 20. I tried this:
while spot <= len(numbersList):
if(number % int(numbersList[spot]) == 0):
count = count + 1
spot = spot + 1
print count
But it keeps saying list index is out of range. Please help!
Upvotes: 0
Views: 108
Reputation: 548
I prefer the classic map-reduce
reduce( lambda x,y: x+y, [ number%spot for spot in numbersList ] )
Upvotes: 0
Reputation: 304137
The first line is a SyntaxError
>>> when spot <= len(numbersList):
File "<stdin>", line 1
when spot <= len(numbersList):
I suspect you mean to use while
But it's easier to use a for loop
for spot in numbersList:
if number % spot == 0:
count += 1
print count
This can also be written more simply by passing a generator expression to sum
count = sum(number % spot == 0 for spot in numbersList)
Upvotes: 1
Reputation: 298106
Your index goes too far at the last iteration of the while
loop. Change the <=
to <
and it should work:
while spot < len(numbersList):
Or just use a for
loop:
for i in numbersList:
if number % i == 0:
count += 1
Upvotes: 2
Reputation: 1700
You can't index into a list with a float, and spot = 0. is a float. Try removing that spurious period!
Upvotes: 1