我忘记了一个简单的循环错误

2024-06-02 06:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想建立一个列表。列表中有用户要求的值的数量,不能超过限制,也不能重复,但我不知道我的错误在哪里。程序没有按照我想要的方式生成列表。这有点难以解释,但您可以自己使用以下属性运行代码:

class Mundo:
    def __init__(self):
        self.existValues = list()
        self.world = self.grid()
        self.blues = self.blue()
        print(f"Map: {self.world}\n"
              f"Exist Values: {self.existValues}\n"
              f"Blue values: {self.blues}")
        # self.theArray = [[self.world, ], [self.world, ]]

    def grid(self):
        while True:
            self.size = input("Size of Map: ")
            if self.size.isnumeric() and int(self.size) >= 2:
                self.size = int(self.size)
                intSize = self.size * self.size
                mapH = list()
                gridMap = list()
                for elementos in range(1, intSize + 1):
                    if len(mapH) == self.size - 1:
                        mapH.append(elementos)
                        gridMap.append(mapH)
                        mapH = []
                    else:
                        mapH.append(elementos)
                return gridMap

    def blue(self):
        while True:
            try:
                qt = int(input("How many blues to spawn?"))
            except ValueError:
                continue
            posBlue = list()
            controle = list()
            control = False
            for _ in range(qt):
                while not control:
                    x = rint(1, self.size)
                    y = rint(1, self.size)
                    controle.append([x, y])
                    for elements in controle:
                        if elements in self.existValues:
                            control = True
                        else:
                            posBlue.append([x, y])
                            self.existValues.append([x, y])
                            control = False

            return posBlue

如果我运行代码(qt==2,self.size==4),一次、两次或三次代码输出一个包含3个或2个值的列表,有时是4个

我会跑3次来展示

产出1: Only 3 values in blues, i asked for 4.

产出2: Only 2, i ask for 4.

产出3: Again.

我需要用户要求的输出


Tags: 代码inself列表forworldsizedef
1条回答
网友
1楼 · 发布于 2024-06-02 06:25:13

以下是您的MRE表单代码:

from random import randint


def blue(qt: int, size: int):
    existValues = []
    posBlue = list()
    controle = list()
    for _ in range(qt):
        x = randint(1, 4)
        y = randint(1, 4)
        controle.append([x, y])
        for elements in controle:
            if elements in existValues:
                continue
            else:
                posBlue.append([x, y])
                existValues.append([x, y])

    return posBlue


print(len(blue(2, 4)))    # prints 2 because odds are good of getting 2 uniques
print(len(blue(10, 4)))   # prints 8 because it missed some
print(len(blue(100, 4)))  # prints 16 because that's the maximum number

通过使用不同的量进行测试,很容易看出问题出在哪里,您依赖于随机机会来生成唯一的组合,因此不能保证for循环的每次迭代都会找到一个不存在的组合

简单的方法是生成一个详尽的组合列表,然后随机选择:

from itertools import product
from random import sample


def blue(qt: int, size: int):
    possibilities = list(product(range(1, size+1), range(1, size+1)))
    return sample(possibilities, qt)


print(len(blue(2, 4)))    # prints 2
print(len(blue(10, 4)))   # prints 10
print(len(blue(100, 4)))  # ValueError: Sample larger than population

请注意,如果qt大于size^2,则会引发异常。您可以决定是否要以不同的方式处理此问题,如果可以接受足够大数量的重复?下面是一个简单的修复方法:将possibilities乘以所需的数量,以确保它至少与qt一样大

def blue(qt: int, size: int):
    possibilities = list(product(range(1, size+1), range(1, size+1)))
    possibilities *= 1 + (qt - 1) // len(possibilities)
    return sample(possibilities, qt)

相关问题 更多 >