Home > Mobile >  Is their a way to create a number generator without a whole bunch of lists
Is their a way to create a number generator without a whole bunch of lists

Time:12-14

I can technically make this no problem but its just of a bunch of lists assigned to a bunch of variables with the random.choice() function. Is their an easier way to do this?

import random
while True:
    
    numbers = '1 2 3 4 5 6 7 8 9 10'.split()
    
    red = random.choice(numbers)


    print(red  red   red   '.'   red  red  red  '.' red '.' red  red )
    break
    

The code above is an example of the code i need to randomly generate. Right now, its technically random generating 1 number for all the numbers. for example 777.777.7.77 My goal is to get every character random but not a heap of code

CodePudding user response:

For the problem as written, probably the simplest solution is to make all the choices up front, then substitute them into a simple format string:

import random
numbers = range(1, 11)  # Don't need them to be strings; faster to type range(1, 11)

# Generate nine values, each randomly selected from numbers
red = random.choices(numbers, k=9)

# Format string with nine placeholders by unpacking the nine generated values
print('{}{}{}.{}{}{}.{}.{}{}'.format(*red))

CodePudding user response:

A list comprehension will create an array of values from 1-10.

You can run a choice on the list each time in the string to return the value.

import random

numbers = [i for i in range(1, 10)]

print(f'{random.choice(numbers)}{random.choice(numbers)}{random.choice(numbers)}.{random.choice(numbers)}{random.choice(numbers)}{random.choice(numbers)}.{random.choice(numbers)}.{random.choice(numbers)}{random.choice(numbers)}')

  • Related