2

I want to create a function which produces a list of all the numbers from 1 through 300 that are divisible by both 6 and 10 by using a list comprhension. The expected output is below:

 ist_result = special_nums()
    list_result
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]

I think that I might have to use the range function in a way but im not sure. Any ideas?

cs95
  • 379,657
  • 97
  • 704
  • 746
user10019227
  • 117
  • 1
  • 2
  • 7
  • Which part are you struggling with? 3 thoughts: `range` by default starts at 0 and doesn't include the end of the range. You can include a guard condition in list comprehensions: `[i for i in x if ...]`. You can express "6 divides n" with `not n%6`. – Patrick Haugh Aug 06 '18 at 01:32

2 Answers2

1

From here, define a function to compute the prime of 2 or more numbers:

def gcd(a, b):
    """Return greatest common divisor using Euclid's Algorithm."""
    while b:      
        a, b = b, a % b
    return a

def lcm(a, b):
    """Return lowest common multiple."""
    return a * b // gcd(a, b)

def lcmm(*args):
    """Return lcm of args."""   
    return reduce(lcm, args)

Next, compute the lcm of your numbers and then iteratively emit numbers. Good thing is, if you know the lcm, you won't have to go over every number in the range.

from math import ceil

def get_multiples(start, end, *args):
   lcm = lcmm(*args)
   start = max(lcm, lcm * ceil(start / lcm))  # max(..., ...) in case start < lcm
   for i in range(start, end + 1, lcm):
       yield i

>>> list(get_multiples(1, 300, 6, 10))
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]

As noted above, this is efficient since it doesn't iterate over every value in the supplied range, and efficiently scales to > 2 values:

>>> list(get_multiples(79, 400, 6, 10, 20))
[120, 180, 240, 300, 360]
cs95
  • 379,657
  • 97
  • 704
  • 746
0

The following expression will do (since 30 is 6 and 10's lowest common denominator):

[n for n in range(1, 301) if n % 30 == 0]
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 2
    Note to readers: This (inefficiently) iterates through every element in the range when the stride can instead be pre-computed for better efficiency. – cs95 Aug 06 '18 at 01:46