如何解决代码无法决定在模拟中在何处添加数字
一个房间里有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")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。