首页 > 解决方案 > 代码无法决定在模拟中添加数字的位置

问题描述

一个房间里有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))

标签: pythonsimulation

解决方案


我会保存一份酒吧清单和每张桌子上的人数清单。对于每个新人,您可以找到他们通过加入表格可以获得的最大条数,并根据该表格选择正确的表格:

numpeople = int(input())
bars_on_tables = [1, 2, 3]
people_at_tables = [0, 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")

推荐阅读