Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Good morning! Here's your coding interview problem for today.
- This problem was asked by Palantir.
- The ancient Egyptians used to express fractions as a sum of several terms where each numerator is one.
- For example, 4 / 13 can be represented as 1 / 4 + 1 / 18 + 1 / 468.
- Create an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian fraction.
- '''
- import random
- # FUNCTION 1
- def egyptian(a, b):
- if a != int(a) or b != int(b) or a <= 0 or b <= 0 or a >= b:
- print("Error while using function " + egyptian.__name__)
- # Now, I will begin the scanning
- SUM = 0
- target = a / b
- counter = 2
- LIMIT = 10 ** 5
- numbers = list()
- while SUM < target and counter <= LIMIT:
- if target - SUM >= 1 / counter:
- SUM += 1 / counter
- numbers.append(counter)
- counter += 1
- return numbers
- # FUNCTION 2
- def prettyPrint(a, b):
- numbers = egyptian(a, b)
- result = ""
- for i in range(len(numbers)):
- if i != len(numbers) - 1:
- result += "1/" + str(numbers[i]) + " + "
- else:
- result += "1/" + str(numbers[i])
- print(str(a) + "/" + str(b) + " = " + result)
- # MAIN FUNCTION
- prettyPrint(7, 12)
- prettyPrint(1, 12)
- prettyPrint(5, 6)
- prettyPrint(2, 3)
- prettyPrint(4, 13)
- prettyPrint(3, 10)
- prettyPrint(random.randrange(2, 10), random.randrange(11, 20))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement