Python Exercise 14: sum of fractions
HHMathewChan
Posted on June 23, 2022
Question
- Create a function that takes a list containing nested lists as an argument.
- Each sublist has 2 elements.
- The first element is the numerator and the second element is the denominator.
- Return the sum of the fractions rounded to the nearest whole number.
Examples
sum_fractions([[18, 13], [4, 5]]) ➞ 2
sum_fractions([[36, 4], [22, 60]]) ➞ 9
sum_fractions([[11, 2], [3, 4], [5, 4], [21, 11], [12, 6]]) ➞ 11
My solution
- algorithm
>>separate the sublist in the nested list
iterate over the nested list
>>separate elementes in the sublist
iterate over the sublist
>>for each sublist, calculate the fraction
set the first element to the numerator
set the second element is the denominator
store the result to a variable called:total
>>return the variable total
- code
def sum_fractions(nested_list:list):
total = 0
list_of_sum = list()
for sublist in nested_list:
division = int(sublist[0]) / int(sublist [1])
total += division
return round(total)
Other solution
- unpacking the sublist by multiple assignment
- i.e. use numerator for the first element of the sublist
- use denominator for the second element of the sublist
- i.e. use numerator for the first element of the sublist
def sum_fractions(lst):
return round(sum(numerator/ denominator for numerator, denominator in lst))
My reflection
- I have learned using multiple assignment instead of using index to access the value of a list.
Credit
- challenge find on edabit
💖 💪 🙅 🚩
HHMathewChan
Posted on June 23, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.