A practical alternative to this is to use functions that the library random
already offers you:
from random import sample
def loteria() -> list:
return sorted(sample(range(1, 61), 6))
print(loteria()) # [6, 13, 15, 25, 32, 60]
It is worth noting that the correct is range(1, 61)
, for range(1, 60)
generates the sequence [1, 59], not including the number 60.
To allow the amount of games to be set, simply receive a parameter in the function:
from random import sample
from typing import Iterator, List
def loteria(n: int) -> Iterator[List]:
for _ in range(n):
yield sorted(sample(range(1, 61), 6))
But that doesn’t guarantee you’ll be drawn n
distinct sequences. A simple way to do this would be to store the generated sequences and verify that it is not duplicated:
from random import sample
from typing import Iterator, List
def loteria(n: int) -> Iterator[List]:
sequences = []
while len(sequences) < n:
sequence = sorted(sample(range(1, 61), 6))
if sequence not in sequences:
yield sequence
sequences.append(sequence)
You can also work with sets, set
, which by definition do not allow duplicated values, but for this to happen, you will need to pass the return of sorted
, which is a list, for a guy hashable, as a tuple, for example.
Bro 4 lines of code, crazy thing kkk, but why
def loteria() -> list:
why this arrow, I thought it would give syntax error.– user141036
But I missed the amount of games that the user wants to play, but it’s okay I find a way to enter it into the code
– user141036
@Alexf. Arrow sets the return type annotation. While doing
loteria() -> list
am stating that the functionloteria
will return a list. You can read about this here– Woss