Skip to content
Advertisement

I have to make a function which adds the fractions

I am kind of new to python lists

def sum_fractions(lst):
  for i in range(len(lst)):
    i+=1
    s=lst[i][0]/lst[i][1]+lst[i][0]/lst[i][1]
    ss=round(s)
  return ss
sum_fractions([[11, 2], [3, 4], [5, 4], [21, 11], [12, 6]])

the desired result should be like this

sum_fractions([[11, 2], [3, 4], [5, 4], [21, 11], [12, 6]]) ➞ 11

error: list index out of range actually, I have to go through all lists in a 2d list and first divide the first element of the list with the second and then add it to the fraction of another lists

Advertisement

Answer

Your current code implementation has several problems:

  1. You haven’t initialized ss to 0
  2. You don’t need to increment i inside the loop again. range(len(lst) does this for internally.
  3. You don’t need to round at each iteration if you want the output to be 11. Use round only while returning the output.
  4. Additionally, it is not clear why you are adding the fractions twice.

The correct implementation would be:

def sum_fractions(lst):
    ss = 0
    for i in range(len(lst)):
        s=lst[i][0]/lst[i][1]
        ss+=s
    return round(ss)

lst = [[11, 2], [3, 4], [5, 4], [21, 11], [12, 6]]
res = sum_fractions(lst)
print(res)

As suggested by others, you can modify the function to directly iterate over elements and not index.

def sum_fractions_0(lst):
    ss = 0
    for l in lst:
        ss += l[0]/l[1]
    return round(ss)
Advertisement