Home > OS >  Least Common Denominator, TypeError: 'float' object cannot be interpreted as an integer,
Least Common Denominator, TypeError: 'float' object cannot be interpreted as an integer,

Time:02-01

For the given list of denominators, find the least common denominator by finding their LCM.

Example

For denominators = [2, 3, 4, 5, 6], the output should be solution(denominators) = 60.

This is my code:


from math import gcd

def solution(denominators):
    return functools.reduce(lambda x,y: x * y / gcd(x,y), denominators)

But then it says: TypeError: 'float' object cannot be interpreted as an integer

Any suggestions, how to fix it?

CodePudding user response:

gcd arguments are integers so on the second iteration of reduce the argumentes passed are:

gcd(2*3/gcd(2,3)'''<-this is a float''' , 4)

rigth way

def solution(denominators):
   return functools.reduce(lambda x,y: x * y , denominators) / functools.reduce(lambda x,y: gcd(x,y) , denominators)

CodePudding user response:

First, you need to import functools as follows:

from math import gcd
import functools
def solution(denominators):
    return functools.reduce(lambda x,y: x * y / gcd(x,y), denominators)

Then let's try list test_list = [2, 3, 4, 5, 6], it returns:

TypeError: 'float' object cannot be interpreted as an integer

The problem is that in the / you are creating a float as a result. / always returns a float. The solution for this is to use the int division operator //. // returns an integer. For example:

a = 1
b = 2
int_div  = a // b
print(int_div)

returns 0.

Therefore the solution is to use:

functools.reduce(lambda x,y: x * y // gcd(x,y), denominators)
  •  Tags:  
  • Related