'Making a GCF calculator in python
I'm making a calculator in python that takes in two numbers and returns the greatest common factor of it. When I create a function that returns the same numbers of the two lists of factors, I keep getting a 'index' error even if I stated
if len(one) == 0 and len(two) == 0:
here's my code:
def work(one, two):
for i in range(len(one)):
for j in range(len(two)):
if len(one) != 0 and len(two) != 0:
if one[i] == two[j]:
one.pop(i)
two.pop(j)
if len(one) == 0 or len(two) == 0:
break
else:
work(primeF, primeF2)
break
work(primeF, primeF2)
What could I do to fix this?
Solution 1:[1]
I think that instead of checking whether the list length is 0, you need to be checking that the list is long enough to include your index.
Solution 2:[2]
There is an even easier way to do it without modules (I just used time for supplements)
import time
def gcf (num1, num2): #The Actual Calculator
if num1 > num2:
num1, num2 = num2, num1
for x in range (num1, 0, -1):
if num1 % x == 0 and num2 % x == 0:
return x
def run(): #This section is defined so that it can be run multiple times
num1 = int(input("First Number: ")) #First number
num2 = int(input("Second Number: ")) #Second number
print (str (gcf (num1, num2)))
run_again = input("Run again? y or yes for yes: ")
if run_again == "yes" or run_again == "Y" or run_again == "Yes" or
run_again == "y":
run()
elif run_again == "hello":
print("hi")
run()
else:
print("Goodbye!")
time.sleep(1.5)
quit()
#Runs the code
run()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ehaymore |
| Solution 2 | CodeWizard777 |
