Python | Avoid previous value from random selection from list -
basically want code print out 5 wrong()
func's without there being 2 in row of same text. , of course don't want luck. :)
though don't worry part of printing out 5 wrong()
s, want make sure if use function @ least twice 100% sure previous value won't same next.
for example, want avoid:
wrong! wrong!
though still fine:
wrong! incorrect! wrong!
my code:
import random def wrong(): wrong_stats=["\n wrong!","\n tough luck!","\n better luck next time!","\n not there yet!","\n incorrect!"] rand = random.choice(wrong_stats) rand3 = random.choice(wrong_stats) norep(rand,rand3,wrong_stats) def norep(rand,rand3,wrong_stats): if rand == rand3: same = true while same: rand = random.choice(wrong_stats) if rand != rand3: print(rand) break elif rand != rand3: print(rand) wrong() wrong() wrong() wrong() wrong()
you'll need keep track of last value returned; could
- use module global (usually messy in practice),
- or turn class (kind of verbose),
- or keep track externally , pass in each time (clunky , tedious),
but imo nicest way turn wrong
function generator instead: way can keep track of last returned value in generator execution state, , avoid next time around, without having worry in external code anywhere.
def wrong(): wrong_stats = ["wrong!","tough luck!","better luck next time!","not there yet!","incorrect!"] previous_value = none while true: value = random.choice(wrong_stats) if value != previous_value: yield value previous_value = value
and usage:
w = wrong() in range(5): print(next(w)) # tough luck! # incorrect! # not there yet! # tough luck! # better luck next time!
you can keep calling next
generator , produce infinite number of strings without ever repeating previous value.
Comments
Post a Comment