code to initialize a sequence
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sun Aug 29 15:42:52 EDT 2021
On Sun, 29 Aug 2021 20:44:53 +0200, joseph pareti <joepareti54 at gmail.com>
declaimed the following:
>In the code attached below, the A-variant is from somebody else who knows
>Python better than I. But I do not like to just use any code without having
>a grasp, specifically the line in* bold*, so I wrote the B-variant which
>gives the same results. The C-variant is identical to A and is there for
>verification: after resetting the seed I expect the same sequence. The
>D-variant is closer to the way I code, and it does not work.
>
>
>import random
>from random import randint, seed
>
>def generate_sequence(length, n_unique):
>*return [randint(0, n_unique-1) for k in range(length)]*
This does NOT ensure length_UNIQUE values. With a bad seed, it could be
possible to return length IDENTICAL values. If you really need unique
values, I suggest
return random.sample(range(n_unique), k=length)
which handles both the range of values, and ensures the subset selected is
all unique.
"""
Generate n unique samples (multiple items) from a sequence without
repetition. Here, A seq can be a list, set, string, tuple. Sample without
replacement.
"""
>
>def generate_sequence_JP(length, n_unique):
> LI = []
> for k in range(length):
> LI.append(randint(0, n_unique-1))
> return(LI)
Again, nothing is checking for UNIQUE values...
LI = []
while len(LI) < length: #untested, may need length - 1
ri = randint(0, n_unique-1)
if ri not in LI:
LI.append(ri)
>def generate_sequence_EXPLICIT(length, n_unique):
> X =[None] * length
> for i in range(length):
> X[i] = [randint(0, n_unique-1)]
> return X
Same -- nothing about UNIQUE values. Prefilling a list with None, just
to immediate replace all the values feels "unPythonic".
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Python-list
mailing list