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
Asked By: Ryan Sheridan

||

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)
Answered By: Hai Vu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.