Problem

Description

Create a function with two arguments that will return an array of the first n multiples of x.
Assume both the given number and the number of times to count will be positive numbers greater than 0.
Return the results as an array or list (depending on language).

Test Cases

count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]

Solution

My Solution

def count_by(x, n):
    """
    Return a sequence of numbers counting by `x` `n` times.
    """
    sequence = []
    for i in range(1,n+1):
        sequence.append(x*i)
    return sequence

Other Solutions

def count_by(x, n):
    return [i * x for i in range(1, n + 1)]
def count_by(x, n):
    """
    Return a sequence of numbers counting by `x` `n` times.
    """
    return list(range(x, n * x + 1, x))

Learning Experiences

  • Solution 1. uses list comprehension to shorten the length of the solution - this squashes the for loop to one line, and with the benefit of already returning a list.
  • Solution 2. uses the range function, which ensures that the first digit of the returned list is already x and that the sequence progresses via step x.
    • Syntax: range(start, stop, step)
    • The range function is not inclusive, which explains the need for value n * x + 1.
    • list(foo) converts the range method into a list, as succeeding the introduction of Python 3, range returns an iterator (object with values that can be traversed) instead.