I've just started learning Python and am trying to do an exercise.
I feel like I am missing something really basic as I can't get some values that are returned to affect my code.
The point of the following code is to print the prime factors of a user input fraction, except that it will only print the entered fraction's prime factors and not the simplified fractions.
def gcd(a,b):
while b:
a,b = b,a%b
return a
def simplify_fraction(numerator,denominator):
cd = gcd(numerator,denominator)
(simple_num,simple_denom) = (numerator/cd,denominator/cd)
if simple_denom == 1:
return simple_num
elif cd == 1:
return simple_num,simple_denom
else:
return simple_num,simple_denom
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
while True:
try:
while True:
fraction = input("Input a positive fraction then press enter:")
numerator,denominator = fraction.split("/")
numerator = int(numerator)
denominator = int(denominator)
if denominator == 0:
raise ValueError
elif numerator < 0:
print("That is not a positive fraction, please try again.")
continue
elif denominator < 0:
print("That is not a positive fraction, please try again.")
continue
elif numerator == 0:
print(str(numerator) + " / " + str(denominator) + " -> [0]")
elif numerator == 1:
print(str(fraction) + " -> [1] / " + str(prime_factors(denominator)))
elif int(denominator) == 1:
print(str(fraction) + " -> " + str(prime_factors(numerator)))
else:
simplify_fraction(numerator,denominator)
I'm sure I'm missing something here to link my simplify_fraction function to my this code block but I can't figure out what that is.
print(str(fraction) + " -> " + str(prime_factors(numerator)) + " / " + str(prime_factors(denominator)))
while True:
character = str(input('Continue (y/n)? '))
if character == "y":
break
if character == "n":
quit()
else:
print ("That was not a valid choice, please select (y/n).")
continue
except ValueError:
print("That is not a fraction, please try again.")
continue
Here's 2 examples:
An input of 3/9 gives 3/9 -> [3] / [3,3]. I want it to be 3/9 -> [1] / [3].
An input of 138/24 gives 138/24 - > [2,3,23] / [2,2,2,3]. I want it to be 138/24 -> [23]/[2,2]
Can someone please give me some advice on this?
simplify_fraction(numerator,denominator)towards the end of your loop does nothing because you don't assign the result to anything. Just calling the function won't modify the strings in-place.