Haven’t posted in a couple weeks, but I’ve been plugging away with Python. (Maybe `struggling away’ more accurate.)
Anyway, I have code to generate a list of random integers.
Ctr = 0
AlDif = False # Not using `All Different' yet.
NumLst = []
while Ctr < 5:
NumLst.append (random.randint (1, 9))
Ctr += 1
print (NumLst)
Output something like [4, 6, 8, 6, 4]
I want to replace the with a different, unique random integer. In the above list, I’d like to replace the second six and the second four.
Now, I can do that by brute force:
If (NumLst [0] == NumLst [1] or NumLst [0] = NumLst [2] …) and so on.
I did exactly that with a list that had only four items and it worked fine. But obviously inefficient. Any suggestions how I might be able to change the duplicates efficiently??
Also, while others have given you much better solutions for this case, in light of your “brute force” method, I wanted to point out the in operator is equivalent to checking if the object on the LHS is present in the collection (list, tuple, set, etc) on the RHS. To check one element with index i of a list against the rest, you can replace if (NumLst [0] == NumLst [1] or NumLst [0] == NumLst [2] or ... NumLst[0] == NumList[n]) with if NumLst[i] in (NumLst[:i] + NumLst[i + 1:]).
As a minor sidenote, as a matter of universal convention in Python (and the other common languages I know of), there is no space before ( and [ in function calls and slicing, and adding one may confuse others reading your code (as it did me).