Home > Enterprise >  Function returning certain integers
Function returning certain integers

Time:02-22

I am trying to create a 'def' function. It will include 'maxInt', an integer, and 'twoInts', a tuple of two integers. I will then have to create and return a list of all the ints in the range from 1 to maxInt (not including maxInt) that are divisible of both ints in twoInts. Ex: if maxInt = 100, and twoInts = (2, 5) the values returned will be every number divisible by 2 and 5 up to 100, so 10, 20, 30, 40..etc. This would ideally be done using a for loop inside of the def function I have something similar to this but is obviously not working

def isDivisible(maxInt, twoInts):
output = []
for i in maxInt:
    if i%(twoInts)==0:
return output

CodePudding user response:

I think you missing append part. (add element into output list)

def isDivisible(maxInt, twoInts): output = [] for i in range(maxInt): if (i%(twoInts[0])==0) and (i%(twoInts[1]==0): output.append(i) return output

CodePudding user response:

When you want divisibility by multiple numbers, use their least common multiple:

from math import lcm

def isDivisible(maxInt, twoInts):
    m = lcm(*twoInts)
    return list(range(m, maxInt, m))

Before Python 3.9:

from math import gcd

def isDivisible(maxInt, twoInts):
    a, b = twoInts
    lcm = a * b // gcd(a, b)
    return list(range(lcm, maxInt, lcm))

Fixing yours:

def isDivisible(maxInt, twoInts):
    output = []
    for i in range(1, maxInt):
        if all(i % oneInt == 0 for oneInt in twoInts):
            output.append(i)
    return output
  • Related