代码无法决定在模拟中在何处添加数字

问题描述

一个房间里有3张桌子。表1包含1条巧克力,表2具有2条巧克力,表3具有3条巧克力。一个人一次进入房间,走到餐桌上,这将给他们带来最多的巧克力。

我尝试创建一个模拟是python,但是当它达到4个人时,由于每张桌子会给出相同数量的巧克力,所以无法弄清楚去哪里。我尝试过这样,如果choc1,choc2和choc3的每个值相等,则只会在一个随机表中添加一个人,但这没用。

numpeople = int(input())
numtab3 = int(1)  # number of people at table 3
numtab2 = int(1)  # number of people at table 2
numtab1 = int(1)  # number of people at table 1
choc3 = float(3 / numtab3)  # how much chocolate people will get at table
choc2 = float(2 / numtab2)
choc1 = float(1 / numtab1)
while numpeople > 0:
    if choc3 > choc1 and choc3 > choc2:
        numtab3 = numtab3 + 1
        numpeople = numpeople - 1
        choc3 = float(3 / numtab3)
        print("table 3")
    if choc2 > choc3 and choc2 > choc1:
        numtab2 = numtab2 + 1
        numpeople = numpeople - 1
        choc2 = float(2 / numtab2)
        print("table 2")
    if choc1 > choc3 and choc1 > choc2:
        numtab1 = numtab1 + 1
        numpeople = numpeople - 1
        choc1 = float(1 / numtab1)
        print("table 1")

numtab3 = numtab3 - 1  # minus 1 to account for starting value being 1
numtab2 = numtab2 - 1
numtab1 = numtab1 - 1
print("total at table 3 = " + str(numtab3))
print("total at table 2 = " + str(numtab2))
print("total at table 1 = " + str(numtab1))

解决方法

我要在每张桌子上放一个酒吧列表和一个人数列表。对于每个新人,您都可以找到他们通过加入表格可获得的最大杠数,然后根据以下内容选择合适的表格:

numpeople = int(input())
bars_on_tables = [1,2,3]
people_at_tables = [0,0]

for i in range(numpeople):
    # choice is a tuple with the index of the table and the number of bars for that selection:
    potential_bars = (z[0]/(z[1] + 1) for z in zip(bars_on_tables,people_at_tables))
    choice = max(enumerate(potential_bars),key = lambda e: e[1])

    people_at_tables[choice[0]] += 1

    print(f"person #{i + 1} selected table #{choice[0] + 1} in order to get {choice[1]} bars")

相关问答

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