你好,我有一个随机的问题,这是我的第一篇文章,所以如果我的礼仪有误,我道歉:
我正在用python做一场比赛,现在我有4辆“赛车”,每一轮它们都在1到10之间滚动,在这一轮之后,我想要显示一些类似"carX是领先的,滚动的Y“我有点迷失在如何比较每辆汽车的滚动,并打印出特定的文本取决于哪一辆是最高的。
感谢你抽出时间
发布于 2019-11-03 22:40:06
因此,基本上,您正在寻找一个"argmax“实现。这意味着您有一些N个值(rolls),与N个索引(cars)相对应,并且您希望找到包含最高值的索引。
无论如何,既然你没有提到它,我将假设如果几个值是最大的(几辆车得到相同的,最高的滚动),那么第一个被认为是赢家。
在您的例子中,给定N=4,您可以只比较所有变量。这给了你4个案例(每辆车获胜一个),每个案例有3个比较。实际上是3个案例,因为如果前3个没有赢,那么挑衅地第四个赢了。每个案例看起来都像这样:
if car_1 >= car_2 && car_1 > car_3 && car_1 > car_4:
print("Car 1 is in the lead with a roll of {}".format(car_1))
这是一种可怕的方式,。所以让我们首先把这些车变成一个车的列表
list_cars = [car_1, car_2, car_3, car_4]
您可以使用numpy中已经定义的argmax函数,但是对于这个简单的例子,让我们看看如何在不使用numpy的情况下做到这一点。
由于默认的'max‘函数只会给你一个值(滚动),而不是它的值所在的汽车,所以我们将给该函数一个list_cars的索引列表,以及一个键,该键表示对于每个索引,使用相应汽车的值。所以:
func = lambda idx: list_cars[idx]
best_car = max(range(len(list_cars)), key = func)
这里‘list_cars’定义了一个lambda函数,它为汽车列表中的每个索引返回汽车的值,range(len(list_cars))给出一个从0到list_cars长度的数字列表,所以它是0,1,2,3。
结果,'best_car‘将是一个介于0和3之间的数字,它是值最高的汽车。然后你只需打印
print("Car {} is in the lead with a roll of {}".format(best_car + 1, list_cars[best_car]))
我们使用best_car+1打印汽车的数量,因为索引从0开始计数,而汽车从1开始计数。
发布于 2019-11-03 22:41:32
你需要一些原始的“数据结构”来存储race的实际结果。然后计算得分最高的参赛者的最高points+select。将其转换为python:
from random import randint
# roll will generate numbers (uniformly) between LO,HI (HI is inclusive)
LO,HI=1,10
roll=lambda : randint(LO,HI)
n=4
# generate the participiants of the race
# here the first element is the cumulative point
parti=[[0,"car"+str(i)] for i in range(n)]
print(parti)
R=10 # num of rounds
r=0
while r<R:
r+=1
for i in range(n):
parti[i][0]+=roll()
# compute the top point
mx=max(v[0] for v in parti)
# select the top contestants
top=','.join([v[1] for v in parti if v[0]==mx])
# report the state
print('after the {0:d}. round {1:s} on the top with {2:d} points'.format(r,top,mx))
发布于 2019-11-03 22:57:14
如果我理解得好的话,每一轮你都要打印出领头车的名字。您可以通过创建汽车字典来实现这一点,其中键是汽车的名称,值是汽车的位置。每轮只更新所有汽车的值,并使用max()函数找到领先的汽车。
示例代码:
import random
number_of_rounds = 10
cars = {'Car1': 0, 'Car2':0, 'Car3':0,'Car4':0} #dictionary of cars
for round in range(1,number_of_rounds+1):
for car in cars:
roll_value = random.random()*9 + 1 # get the random value from 1 to 10
roll_value = int(roll_value) #convert to int
cars[car] = cars[car] + roll_value
print cars
leading_car = max(cars, key=cars.get) # find the key with highest value
print leading_car + " is in the lead with a roll of " + str(round)
https://stackoverflow.com/questions/58680993
复制相似问题