python - 代码无法决定在模拟中添加数字的位置
问题描述
一个房间里有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, 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")
推荐阅读
- javascript - 我的 vue.js 代码从服务器重复获取数据
- javascript - 使用带有回调条件的 .join()
- python - 从给定的日期记录创建开始日期和结束日期的列
- jenkins - 如何参数化作业 dsl 代码块,例如权限
- javascript - 在 Javascript 中对 HTML 文本区域的内容传递函数
- java - If 语句不适用于 Java 中的 .equals 并且始终显示 else 语句的答案
- javascript - 图像永远不会在 nodeJs Azure 函数中加载
- amazon-web-services - 无法加载 AWS 凭证
- python - 元类在使用类型函数时不调用 __prepare__
- python - Python使用多列合并数据框