Share your repls and programming experiences

← Back to all posts
##### #WEEKLY Challenges 1: Fractions solution

For this first weekly challenges, my solution uses fractions to solve the problem.

My Solution uses how division of fractions works. Dividing two fractions is the same as multiplying the first fraction by the reciprocal of the second fraction. This means that I can do the opposite: multiply fractions by following the same steps and dividing.

This project uses the python standard library module `fractions`.

To convert a given number `n` to a fraction, I use two rules. 1. If `n` is a whole number, its fraction can be `n/1`.
2. Otherwise for decimals, I take the whole part and the decimal part strings, concatenate them (this avoids using multiplication) and set them over 10 raised to the length of the decimal part. To create this power of 10 I use simple string concatenation ("1" plus "0" times the power) since I know it will always be positive.

Once I have the two fractions I check that they're the same as their decimal version to make sure there are no errors. Then, I flip the second fraction and divide.

I have a main function that will prompt the user for input, run my function, and then check if it was correct!

This is an original solution not copied from anywhere.

# Thanks for reading! Upvote if you found it interesting.

##### Comments
hotnewtop
HuhBoi (1)

do you know if there is any way to add to fractions together, and then have the output not be a float but a fraction?

CodingCactus (4355)

doesn't work with 0 :(

Scoder12 (870)

@CodingCactus yes that is what is supposed to happen. Would you rather me return "undefined" or something like that?

CodingCactus (4355)

@Scoder12 well, just have something like if num2 == 0:
Print(0)

Scoder12 (870)

@CodingCactus well thats not true. 1/0 is undefined, not 0.