0

The function at this link and reproduced below uses a yield instead of just return. Also there is a while True loop for some reason.

def lcg(modulus, a, c, seed):
    while True:
        seed = (a * seed + c) % modulus
        yield seed

I want to use the lcg() and have coded it up without the while loop and using return instead of yield. My code works fine on the fake decks of only 10 cards I have tested. But I need to ultimately shuffle 52 cards each time using my shuffle() which is based on code here .

def shuffle(deck,seed):
    global modulus
    global constant
    global mult
    global last

    n = len(deck)
    last = seed
    for i in range(n):
        last = lcg(modulus, mult, constant , last)
        j = last % n-i
        temp = deck[i-1]
        deck[i-1] = deck[j]
        deck[j] = temp
    return deck

My question is, how can I better use the yield and while in shuffle() in my app? (Employing yield may be overkill because my app only shuffles one deck at a time, not many.)

(Btw, I am aware that the lcg() code has statistical problems but I have not found any way to use built-in random() features at python that enable me to supply my user with the seeds as they are produced here so they can replay or share a shuffled deck. If you have a suggestion for that I would love to hear it.)

zerowords
  • 2,915
  • 4
  • 29
  • 44
  • 2
    I'm voting to close this question as off-topic because it belongs in https://codereview.stackexchange.com – Xorifelse Oct 09 '17 at 20:25
  • And yielding profides a benefit to not load everything at once, a line by line sequence. Does not seem useful to shuffle a deck of cards, but then again you gain performance if this happens a lot globally. That being said, you still would need to quit the loop, otherwise a normal loop will be the same. – Xorifelse Oct 09 '17 at 20:27
  • 1
    You really don't want to implement your PRNG unless you really absolutely need one. Consider using `my_reproducible_prng = random.Random(my_seed_arg)` – Asclepius Oct 09 '17 at 20:29
  • A-B-B, Do you just mean rename my lcg() to Random() and eliminate most of the arguments or do you mean something about [Rr]andom() that I don't understand. When I read the python library docs regarding random(), there does not seem to be an alternative which produces a single numerical result than can seed the next call. – zerowords Oct 09 '17 at 20:43
  • A-B-B, I have read more thoroughly the Random() docs and the fine answer by Dr. Drew at [https://stackoverflow.com/questions/5012560/] and understand what you meant now. I did not understand that although there is no way to tell how a random pattern finishes so that the finishing value or state can be used to set the next random sequence's seed, I can set the new sequence's seed with my own integer seed (Dr Drew show how to get system time as an integer for the seed). So I'll be using random() in my app. – zerowords Oct 10 '17 at 19:12

0 Answers0