Reputation: 31
I have written this python code. When I run it I get an index error at the end; I don't know why. I was wondering if someone could help me out.
The problem is to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. My analysis is correct but just the code at the end is giving me hard time.
def leastCommonDenominator(num1, num2):
'''
Returns the least common denominator of two numbers
'''
num2List = range(1,num2+1)
if num1 < num2:
for i in num2List:
if (num1*num2List[i]) % num2 == 0:
return num1*num2List[i]
num1List = range(1, num1+1)
if num2 < num1:
for i in num1List:
if (num2*num1List[i]) % num1 == 0:
return num2*num1List[i]
else:
return num1
def leastNum():
'''
Prints the least number divisible
'''
myList = range(1,4)
print myList
num = 1
for i in myList:
num = leastCommonDenominator(num, myList[i])
print num
def main():
leastNum()
Upvotes: 1
Views: 90
Reputation: 189
Use
for i in myList:
num = leastCommonDenominator(num,i)
print num
instead of
for i in myList:
num = leastCommonDenominator(num,myList[i])
print num
Here i is the iterator over the elements of the list.It is not over the index of elements.So you cannot use myList[i].On the other hand you can write
for i in range(0,len(myList)):
num=leastCommonDenominator(num,myList[i])
Upvotes: 2
Reputation: 37259
When you define myList
, its value is (as you know):
myList = [1, 2, 3]
When you iterate, you are cycling through each of the elements (1, 2, 3), but when you call leastCommonDenominator
, you are using the index of the list, not the element itself (i.e. in the first pass through, you aren't calling the first element of myList
, you are calling myList[1]
, which is the second element. This causes an IndexError
on the final pass, because myList[3]
is referring to the fourth element in the list, which as we can see does not exist (since range
doesn't include the upper bound in its value). In order to fix, you should be able to do this:
num = leastCommonDenominator(num, i)
When you use the for
loop like you are, you can simply use the values themselves. If you want to refer to the position of the elements, you can use enumerate
, which returns both the index/position of a value and the value itself (this is more FYI - you don't need it here I don't believe :) ). For example:
for index, i in enumerate(myList):
num = leastCommonDenominator(num, myList[index])
And you would get the same result.
Upvotes: 2