0

How can i create a function that finds the multiples of a number in a certain range on python ?

3rd Apr 2017, 7:17 PM
Penny Jacobs
Penny Jacobs - avatar
5 odpowiedzi
+ 14
personally, I would use a generator (because I love generators) def multiplesOf(x,max): i=0 while i<max: i+=x yield i for i in multiplesOf(10,100): print(i) #outputs the 10 times table up to 100
4th Apr 2017, 2:17 AM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 11
@Tobi Nice! I wish I knew how to make one liners like that. Hopefully the OP will vote your answer as best :)
4th Apr 2017, 5:20 PM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 10
def multiples(n): for number in range (100): if number%n == 0: print(number)
3rd Apr 2017, 7:24 PM
LayB
LayB - avatar
+ 4
Cheeky one liner for multiples of n in range(a,b): range(a+n*int(a%n != 0) - (a%n), b, n)
4th Apr 2017, 5:17 PM
Tob
Tob - avatar
+ 3
@Aidan: Thank you! Although shorter is not always better. The cleanest solution code wise would be a list comprehension (also one line). My solution is probably the most efficient, but not too pythonic, as it is not super readable. Best practice would be a generator, but instead of checking each number in the range, just find the first one and increase by n until you are out of the boundary.
4th Apr 2017, 5:34 PM
Tob
Tob - avatar