My goal is to write code that picks several random numbers from a range without repeating any previously chosen numbers. I figured out a functional solution for my problem but it seems very bulky and there must be a way to do this in fewer lines. Mine feels brute force and not very elegant and becomes super unwieldy if stretched to larger ranges and repetitions. Would love any suggestions for cleaning up what I already have.
import random key1 = random.randint(1, 4) while True: key2 = random.randint(1, 4) if key2 != key1: break while True: key3 = random.randint(1, 4) if key3 != key1 and key3 != key2: break while True: key4 = random.randint(1, 4) if key4 != key1 and key4 != key2 and key4 != key3: break key_order = [key1, key2, key3, key4] print(key_order)
If it means totally taking my code apart and rebuilding it, that is fine. I am here to learn.