Your team is going camping and you are taking a vote to decide what food to pack for dinner.
Everyone gets a vote and the food item that gets at least one more than half of the votes wins. None of the items wins if nothing gets at least one more than half votes. Assume that every person gets only one vote.
The input will contain a list of food items where each occurrence of an item represents one vote. You should print the winning food item as output. If there is no clear winner, print "NOTA".
Input1: {'a','b','a','a','b','b'} output1: NOTA Input2: {'a','b','a','a','b','b','b'} output2: b
我已经编写了代码,它给出了重复值的计数
import ast,sys
input_str = sys.stdin.read()
votes = ast.literal_eval(input_str)
d = {}
for i in votes:
if i not in d:
d[i]=1
else:
d[i] = d[i]+1
上面的代码给出了所有重复值的计数,例如它返回的Input1 dict_values[3,3]
但我想在字典中将键和值连接在一起。
例如:{'a': 3, 'b':3}
这样我就可以使用下面的代码了
vals = list(d.values())
for value in vals:
if value[0]==value[1]:
print('NOTA')
else:
if value[0] > value[1]:
print(max(d.key()) (something like this)
我组合了这两个函数,并稍微修改了代码:
词典已具有您需要的格式。所以我想这样做
这应该是你需要的,最好的部分,你可以有更多的a,b,你可以有c,和d,:-)
而不是查看^ {< CD1> }考虑使用^ {CD2>}。这将为您提供键/值对。您可以在生成器表达式中使用它并调用
next()
来获取键的值next()
在没有可返回的内容时采用默认值。例如:在用这种方法解决了^{} 之后,您还应该看看它
相关问题 更多 >
编程相关推荐