Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate random numbers by a certain step in python

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.

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)

thanks in advance and sorry for the language it’s dutch.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading