Search code examples
pythonlistrandommultiplication

How to generate random numbers by a certain step?


For school we have to create a program in python in which we generate a given number of random numbers and you can choose by what multiplication. I tried this code (which will show my list is empty) but I'm wondering if there is a specific function for this in python because I cant seem to find out how to do it.

Also, we can't use any other function than randint()

from random import randint

list = []
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))

for i in range(aantal):
    getal = randint(1, 100)
    if getal % veelvoud == 0:
        list.append(getal)
    else:
        i -= 1

print(list)

Solution

  • Here's a different way to approach the problem:

    • Request user input for the number of random numbers, and the step

    • Create an empty list

    • While the list contains less elements than the number requested, generate random numbers between 1 and 100

    • Check if the random number is a multiple of the step, and if so, add it to the list

    from random import randint
    
    number = int(input("How many random numbers to generate?: "))
    step = int(input("Multiple of which number? : "))
    
    nums_list = []
    
    while len(nums_list) < number:
      rand = randint(1, 100)
      if rand % step != 0:
        continue
      else:
        nums.append(rand)
    
    print(nums_list)
    

    An even more efficient way would be to generate random numbers in a way such that the number will always be a multiple of the step:

    from random import randint
    
    number = int(input("How many random numbers to generate?: "))
    step = int(input("Multiple of which number? : "))
    
    # The highest number that can be multiplied with the step to
    # produce a multiple of the step less than 100
    max_rand = floor(100/step)
    
    nums_list = []
    
    for _ in range(number):
      rand = randint(1, max_rand) * step
      nums_list.append(rand)
    
    print(nums_list)