147k views
1 vote
# Specification: overhand(L, r=1) is yet another shuffling algorithm,

# like scramble() and randInsert(). Inspired by the (physical)
# overhand shuffle, the algorithm repeatedly performs a three-segment
# reordering of the deck as follows. First, pick two indexes at
# random; call the lesser one i and the larger one j (note your code
# should also work for i==j). Exchange the first i elements of L with
# the last len(L)-j elements of L. So, for example, if the list is
# initially
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# and i=3, j=8, we would restructure the list as follows:
# [0, 1, 2 | 3, 4, 5, 6, 7 | 8, 9]
# to yield
# [8, 9, 3, 4, 5, 6, 7, 0, 1, 2]
# To shuffle perform this operation r (default 1) times.
#
# Example:
# >>> L=list(range(10))
# >>> L
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>> overhand(L)
# [4, 5, 6, 7, 8, 9, 2, 3, 0, 1]
# >>> overhand(L, 100)
# [6, 2, 4, 9, 8, 0, 5, 1, 7, 3]
#
# Hint: Careful! The two sections you swap may not be the same
# length. To avoid going crazy, I'd avoid parallel assignment to start
# with, as it may not operate the way you might expect it to. This one
# is tricky!
#
from random import randint
def overhand(L, r=1):
pass

User Bhilstrom
by
8.2k points

1 Answer

2 votes

Answer:

Step-by-step explanation:

The overhand() function takes a list L and an optional argument r (default value 1). It shuffles the list L by performing a three-segment reordering of the deck r number of times.

To perform the reordering, two indexes i and j are picked at random from the list. The lesser index is stored in variable i and the greater index is stored in variable j. The first i elements of the list are exchanged with the last len(L)-j elements of the list.

To implement this, we can use a loop that iterates r times. Inside the loop, we can use the randint() function from the random module to generate two random integers i and j such that i <= j. We can then swap the two segments of the list as described above.

Here's the code:

from random import randint

def overhand(L, r=1):

for _ in range(r):

i = randint(0, len(L)-1)

j = randint(0, len(L)-1)

if i > j:

i, j = j, i

L[i:j+1], L[:i], L[j+1:] = L[len(L)-j-1:], L[i:j+1], L[:len(L)-j-1]

return L

In the code above, we use slicing to swap the segments of the list. The expression L[i:j+1] gets the sublist from index i to index j (inclusive). The expression L[:i] gets the sublist from the beginning of the list up to index i-1. The expression L[j+1:] gets the sublist from index j+1 to the end of the list.

Note that we swap the first segment (L[:i]) with the last segment (L[len(L)-j-1:]) and leave the middle segment (L[i:j+1]) unchanged.

User Mmc
by
8.6k points