Nested loop used in hcf finding code in Python returns IndexError:index out of range
Nested loop used in hcf finding code in Python returns IndexError:index out of range
我创建了一个程序,可以生成给定两个数字的 HCF(最大公因数)。
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))
在找到两个数字的因数之前,它工作正常。但是当程序是运行时,它在if f1[x]==f2[y]:
处显示索引错误。
错误是:
if f1[x]==f2[y]:
IndexError: list index out of range
出现此错误的原因是什么,我该如何纠正?
for x in range(0,(len(f1)+1) ):
for y in range(0,(len(f2)+1)):
if f1[x]==f2[y]:
hcf = f2[y]
问题是 range(0, len(f1)+1) 从 0 到列表的长度 + 1,我想你不会有这个问题,如果你将其替换为:
for x in f1:
for y in f2:
if x == y:
hcf = y
不需要len(f1)+1。以下应该有效。
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))
我创建了一个程序,可以生成给定两个数字的 HCF(最大公因数)。
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))
在找到两个数字的因数之前,它工作正常。但是当程序是运行时,它在if f1[x]==f2[y]:
处显示索引错误。
错误是:
if f1[x]==f2[y]:
IndexError: list index out of range
出现此错误的原因是什么,我该如何纠正?
for x in range(0,(len(f1)+1) ):
for y in range(0,(len(f2)+1)):
if f1[x]==f2[y]:
hcf = f2[y]
问题是 range(0, len(f1)+1) 从 0 到列表的长度 + 1,我想你不会有这个问题,如果你将其替换为:
for x in f1:
for y in f2:
if x == y:
hcf = y
不需要len(f1)+1。以下应该有效。
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))