首页 > 解决方案 > 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'

标签: python

解决方案


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)))

这不涉及不输入整数或平局游戏的玩家。我会把它留给你。


推荐阅读