Generate a random combination on each line

Asked

Viewed 103 times

0

I made a number generator that looked like this:

import random
import math

for i in range(10):

    c1 = (random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9]))
    c2 = (random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9]))
    c3 = (random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9]))
for i in range(90):
 print  ('{}{}{}'.format(c1, c2, c3, ))

works almost everything, when I run the code in pycharm it generates 90 combinations but all of them are the same but I want them to be random as if I had run the code several times.

1 answer

2


What happens is that when you set the random values for C1, C2 and C3 they really were random and different from each other, carrying the Random function fulfilled its role. If you want them to be random within the for you need, for each iteration, to call the Random method again.

import random

def gerar_randomico():
    return random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9])

for i in range(3): 
    print ('{}{}{}'.format(gerar_randomico(), gerar_randomico(), gerar_randomico()))
  • 1

    A small detail would be to put range(1, 10) instead of the explicit erray in this case. Good answer

  • Thank you very much gave right, give me your contact that this code will give me some money and I pay you.

  • No need @Elipe, rest assured. Our goal here is to help the community. By the way, I’m glad my answer solved your problem. Big hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.