Python: Iterate over list items, select other random item, with prob p, swap items
Question:
As in the title the problem involves iterating over a list, selecting a random other item, and with a probability p, swap them.
I must be close, but am getting the index out of range error. I can’t think of the case where the index would be out of range.
lst = [x for x in range(10)]
for i in lst:
random_index = random.randint(1, len(lst))
if random.random() <= p:
lst[i], lst[random_index] = lst[random_index], lst[i]
IndexError: list index out of range
Answers:
The problem is random.randint(1, len(lst))
will produce a random integer from 1 to 10, inclusively, meaning 10 is included and that will generate IndexError
. To fix, you need to adjust:
lst = list(range(10))
for index, element in enumerate(lst):
random_index = random.randint(0, len(lst) - 1)
if random.random() < p:
lst[index], lst[random_index] = lst[random_index], element
However, unless this is a homework, you are better off using the shuffle function to achieve the same result with less effort:
lst = list(range(10))
random.shuffle(lst)
As in the title the problem involves iterating over a list, selecting a random other item, and with a probability p, swap them.
I must be close, but am getting the index out of range error. I can’t think of the case where the index would be out of range.
lst = [x for x in range(10)]
for i in lst:
random_index = random.randint(1, len(lst))
if random.random() <= p:
lst[i], lst[random_index] = lst[random_index], lst[i]
IndexError: list index out of range
The problem is random.randint(1, len(lst))
will produce a random integer from 1 to 10, inclusively, meaning 10 is included and that will generate IndexError
. To fix, you need to adjust:
lst = list(range(10))
for index, element in enumerate(lst):
random_index = random.randint(0, len(lst) - 1)
if random.random() < p:
lst[index], lst[random_index] = lst[random_index], element
However, unless this is a homework, you are better off using the shuffle function to achieve the same result with less effort:
lst = list(range(10))
random.shuffle(lst)