I've come across an interesting scenario while working on a Python program that involves generating unique options for a game. In my implementation, I initially used a set to store the options and encountered an issue where the program would freeze, leading to an infinite loop. However, after making a slight modification by switching to a list, the freezing problem disappeared.
I'm curious to understand the underlying reasons behind this behavior and why the second implementation caused the program to freeze. I have my own thoughts on the matter, but I want to gather insights from you all to gain a deeper understanding.
Prerequisite code
MAX = 20 MIN = 1 ans = random.randint(MIN, MAX) y = random.randint(MIN, ans) x = ans - y
Here are the two implementations:
Implementation 1 (No freezing issue):
opts = [x] while len(opts) < 4: opt = random.randint(MIN, MAX) if opt not in opts: opts.append(opt)
Implementation 2 (Caused program freezing):
opts = {x} while len(opts) < 4: opts.add(random.randint(MIN, MAX))
Edit
Here is the full contents of the function (with implementation 1)
def question_generator():
MAX = 20 MIN = 1 ans = random.randint(MIN, MAX) y = random.randint(MIN, ans) x = ans - y # Generate options list opts = [x] while len(opts) < 4: opt = random.randint(MIN, MAX) if opt not in opts: opts.append(opt) random.shuffle(opts) return (x, y, ans, opts)
Questions I have about this:
What exactly causes the freezing issue in the second implementation?
Why does the first implementation resolve the freezing problem?
Are there any underlying differences between sets and lists that contribute to this behavior?
I really can't seem to understand why there is such a drastic difference, thanks for any insight you may have.