Nested loop used in hcf finding code in Python returns IndexError:index out of range

Question:

I created a program that will generate the HCF(highest common factor) of the given two numbers.

f1 = []
f2 = []
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
n1 = num1 + 1
n2 = num2 + 1
for i in range(1,n1):
      if num1%i == 0: f1.append(i)
for j in range(1,n2):
      if num2%j == 0: f2.append(j)
hcf = 1
for x in range(0,(len(f1)+1) ):
    for y in range(0,(len(f2)+1)):
        if f1[x]==f2[y]:
            hcf = f2[y]
print("The highest common factor of "+str(num1)+" and "+str(num2)+" is "+str(hcf))

It works fine until finding the factors of both the numbers. But when the program was run, it showed an index error at if f1[x]==f2[y]:.
the error is:

    if f1[x]==f2[y]:
IndexError: list index out of range

What is the cause of this error and how can I rectify it?

Asked By: user9104738

||

Answers:

for x in range(0,(len(f1)+1) ):
   for y in range(0,(len(f2)+1)):
    if f1[x]==f2[y]:
        hcf = f2[y]

the problem is that the range(0, len(f1)+1) goes from 0 to the length of the list + 1, I think you wouldn’t have the problem and it would be much cleaner if you replaced this for:

for x in f1:
  for y in f2:
    if x == y:
     hcf = y
Answered By: Gabriel

There is no need to have len(f1)+1. Below should work.

f1 = []
f2 = []
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
n1 = num1 + 1
n2 = num2 + 1
for i in range(1,n1):
    if num1%i == 0: f1.append(i)
for j in range(1,n2):
    if num2%j == 0: f2.append(j)
hcf = 1
for x in range(0,(len(f1)) ):
    for y in range(0,(len(f2))):
        print "{0} : {1}".format(x, y)
        if f1[x]==f2[y]:
            hcf = f2[y]
print("The highest common factor of "+str(num1)+" and "+str(num2)+" is "+str(hcf))
Answered By: Naresh Patil
# define hcf
# pass two arguments x,y
# solving using set comprehensions
def hcf(x,y): 
    x1 = {i for i in range(1,x+1) if x % i == 0}
    x2 = {j for j in range(1,y+1) if y % j == 0}
    y2 = x1.intersection(x2)
    print(max(y2))

hcf(54,24)

Best answer I came up with to solve HCF

Answered By: Mohan_ry
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.