Python 递归错误:UnboundLocalError:赋值前引用了局部变量“n”洗牌甲板python代码

问题描述

从顶部到随机是一种简单的洗牌方法,您可以从牌堆中取出最上面的牌并将其放在牌堆中的随机位置,每个位置的可能性相同。 (随机位置可以包括将其留在一副牌的顶部。)。例如,假设我们有一副牌,其中包含编号为 0 到 9 的牌。想象一下,最初,牌的位置是(从上到下):0 1 2 3 4 5 6 7 8 9 然后在一次从顶部到随机的洗牌之后,顺序可能是 1 2 3 0 4 5 6 7 8 9 所以现在 1 在顶部。一开始,牌组不会很随意。但是随着多次重复,它会变得均匀随机。为什么?最终,一些牌将放在 9 之后。在此之后,最终,第二张牌将放在 9 之后。第二张牌放在第一张之前或之后的可能性相同。这样,虽然 9 之前的牌可能不是均匀随机的,但 9 之后的两张牌会是。慢慢地,9之后的一叠均匀随机的牌逐渐增加,直到9到达一副牌的最上面,9号被均匀随机地插入,此时这副牌就变成了均匀随机。

FROM node:lts

RUN mkdir -p /app

WORKDIR /app

COPY package*.json /app

RUN yarn

COPY . /app

CMD ["yarn","run","start"]

解决方法

您的函数中不存在变量“n”。你可以这样做:

def top_to_random(list1):
    n = int(input("Number of times to shuffle: "))

    if n == 0:
        return None
    else:
        first = list1[0]
        x = np.random.randint(len(list1)+1)
        list1.insert(x,first)
        list1.pop(first)
        print(list1)
        n -= 1
    return top_to_random(list1)


print(top_to_random(list1))

或者您可以将变量传递给函数 top_to_random(list1,n)

,

传递 n 参数可以解决您的问题。

def top_to_random(list1,n):
    if n == 0:
        return 
    else:
        first = list1[0]
        x = np.random.randint(len(list1)+1)
        list1.insert(x,first)
        list1.pop(first)
        print(list1)
        n -= 1
    return top_to_random(list1,n)

print(top_to_random(list1,n))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...