0

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?

3
  • 1
    I don't fully understand your code, but note that 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. Commented Apr 24, 2015 at 13:01
  • 1
    wow that's a lot of code as for question "how do I use function's return value". Try to shrink the unrelated code. Commented Apr 24, 2015 at 13:02
  • Hey Taras, sorry I know it is, I was trying to give the full picture to allow for complete understanding and clarity. And Kevin, yes that's the core of the problem... I am trying to figure out how to assign those results to modify the strings in place... working on a string variation at the moment, hoping it works. Commented Apr 24, 2015 at 13:15

1 Answer 1

1

Tried a few more ways to achieve this over past couple hours and got it sorted. Felt I had answer this as it's now moot so... Here's the finished code:

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)
    return int(simple_num),int(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
            simple_num,simple_denom = simplify_fraction(numerator,denominator)
            if simple_denom == 1 and simple_num == 0:
                print(str(fraction) + " -> [0]")
            elif simple_denom == 1:
                print(str(fraction) + " -> " + str(prime_factors(simple_num)))
            elif simple_num == 1:
                print(str(fraction) + " -> [1] / " + str(prime_factors(simple_denom)))
            else:
                print(str(fraction) + " -> " + str(prime_factors(simple_num)) + " / " + str(prime_factors(simple_denom)))
            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 valid fraction, please try again.")
    continue

Here's a test of the program:

Input a positive fraction then press enter: -6/2
That is not a positive fraction, please try again.
Input a positive fraction then press enter: 6/-2
That is not a positive fraction, please try again.
Input a positive fraction then press enter: 10/0
That is not a valid fraction, please try again.
Input a positive fraction then press enter: 0/0
That is not a valid fraction, please try again.
Input a positive fraction then press enter: 0/10
0/10 -> [0]
Continue (y/n)? y
Input a positive fraction then press enter: 138/24
138/24 -> [23] / [2,2]
Continue (y/n)? y
Input a positive fraction then press enter: 24/138
24/138 -> [2,2] / [23]
Continue (y/n)? u
That was not a valid choice, please select (y/n).
Continue (y/n)? tt
That was not a valid choice, please select (y/n).
Continue (y/n)? Y
That was not a valid choice, please select (y/n).
Continue (y/n)? y
Input a positive fraction then press enter: 66
That is not a valid fraction, please try again.
Input a positive fraction then press enter: 1024/512
1024/512 -> [2]
Continue (y/n)? y
Input a positive fraction then press enter: 1024/511
1024/511 = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] / [7, 73]
Continue (y/n)? n

Program exits.

My main mistake was in not setting the variables simple_num and simple_denom in my main code block.... knew it was something basic. Once that was done it was just a matter of tweaking to get it perfect.

WOW, what a rant. Sorry about that.

If anyone looks at this and knows of a better way to do it I'd love to see it... always trying to improve.

Thanks to this awesome website and community!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.