On 29/08/2021 20:44, joseph pareti wrote:
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.
So you do you want us to debug the _EXPLICIT version?
The assignment
> X[i] = [randint(0, n_unique-1)]
creates a list with one element and turns it into an item in the list X.
You don't want a list, you want the numerical value, the
straight-forward way to achieve that being
X[i] = randint(0, n_unique-1)
An alternative is to assign to a slice
X[i:i+1] = [randint(...)]
but that would only make sense if the right-hand-side list weren't
created in the line and ditched immediately afterwards.
import random
from random import randint, seed
def generate_sequence(length, n_unique):
*return [randint(0, n_unique-1) for k in range(length)]*
The above is the most pythonic of the three versions. Once you
understand how for loops with a list.append() are turned into
comprehensions it will be easy to write and read that style. Definitely
worth learning and adopting.
def generate_sequence_JP(length, n_unique):
LI = []
for k in range(length):
LI.append(randint(0, n_unique-1))
return(LI)
This is also fine and often used when the loop body is a bit more
complex, but
def generate_sequence_EXPLICIT(length, n_unique):
X =[None] * length
for i in range(length):
X[i] = [randint(0, n_unique-1)]
return X
this is garbage even when it works, usually indicative of premature
optimization.
Random (yeah!) remark: Python uses half-open intervals (i. e. intervals
that include the lower bound, but not the upper bound) almost
everywhere. randint() is one exception.
Personally I prefer its conformist sister randrange(); with that
randint(0, n_unique-1)
becomes
randrange(n_unique)
#
# MAIN PROGRAM
#
random.seed(2)
A = generate_sequence(4, 10 )
random.seed(2)
B = generate_sequence_JP(4, 10)
random.seed(2)
C = generate_sequence(4, 10 )
random.seed(2)
D = generate_sequence_EXPLICIT(4, 10 )
print(A)
print(type(A))
print('-----------------------------')
print(B)
print(type(B))
print('-----------------------------')
print(C)
print(type(C))
print('-----------------------------')
print(D)
print(type(D))
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
--
https://mail.python.org/mailman/listinfo/python-list