python - Python guessing game (need help getting closest number)
问题描述
im trying to have 2 players, both guesses a number between 1-10. script generates a random number from 1-10 and both users guess and i need a algorithm that says which player was the closest to the guess
python
import random
x = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
w = random.choice(x)
close = user - 1
close2 = user + 2
while 1:
user = raw_input('bet: ')
if user == w:
print('you won')
break
else:
print 'you lost'
解决方案
import random
value = random.choice(range(1,11))
distance = {}
for player in ['p1', 'p2']:
distance[player] = abs(int(input(player + ' bet:')) - value)
print('Winner: {}'.format(min(distance, key=distance.get)))
这不涉及不输入整数或平局游戏的玩家。我会把它留给你。
推荐阅读
- php - 如何从 Laravel 中的对象数组中获取日期
- angularjs - ?^^ 在 Angular JS 1.x 组件中使用
- go - 铸造接口到具体类型 - 类型开关
- redis - 如何访问我的 Redis 云数据库中的密钥?
- datetime - elasticsearch - 日期格式恰好需要 3 位小数
- mongoose-schema - 在 Mongoose 模式类型选项中为字段提供两种有效类型
- reactjs - 组件异常:未定义不是对象(评估“props.textInputId”)
- python - 我在行输出 = 模型(输入)中从 CNN 模块制作模型时遇到了 NotEmplemented 错误
- arrays - 如何在codesys中将多个数组合并为一个数组
- javascript - 当我 react-router 更改页面时,渲染不适用于 React