我正在开发一个程序,根据获胜的百分比显示随机获胜者。这是一种可以帮助您更好地理解的算法:
如何根据随机数与100的接近程度确定合适的百分比?
我理解这些代码可能无关紧要,但我希望通过理解整个程序让我的问题尽可能地有意义 - 这可以帮助你更多。
到目前为止,这是我的代码:
#Luck Draw#
#=========#
import time
import random
print("You will be given a number, the closer your number to 100, the higher the chance you win!")
print("Player 1, please input your name.")
player1 = input()
print("Player 2, please input your name.")
player2 = input()
print("Player 3, please input your name.")
player3 = input()
morePlayers = input("Would you like more players?")
morePlayers = morePlayers.upper()
if morePlayers == 'YES':
print("Player 4, please input your name.")
player4 = input()
print("Player 5, please input your name.")
player5 = input()
print("Player 6, please input your name.")
player6 = input()
print("** Unfortunately this program does not support more than six players yet! **")
time.sleep(2.5)
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player1num = random.randint(0,100)
print(player1 + " Your number is:", str(player1num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player2num = random.randint(0,100)
print(player2 + " Your number is:", str(player2num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player3num = random.randint(0,100)
print(player3 + " Your number is:", str(player3num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player4num = random.randint(0,100)
print(player4 + " Your number is:", str(player4num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player5num = random.randint(0,100)
print(player5 + " Your number is:", str(player5num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player6num = random.randint(0,100)
print(player6 + " Your number is:", str(player6num) + "! You have a percantage to win of: ")
print("And the winner is...")
time.sleep(1)
print("...")
time.sleep(1)
print(winner + "!")
else:
print("Calculating...")
player1num = random.randint(0,100)
print(player1 + " Your number is:", str(player1num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player2num = random.randint(0,100)
print(player2 + " Your number is:", str(player2num) + "! You have a percantage to win of: ")
time.sleep(0.75)
print("Calculating...")
time.sleep(3)
player3num = random.randint(0,100)
print(player3 + " Your number is:", str(player3num) + "! You have a percantage to win of: ")
答案 0 :(得分:0)
I think what you are looking for is random sampling with probabilities assigned to each item. You will be wanting to make use of the numpy library.
Something like this might be useful for you.
import numpy as np
players = ["fred", "alice", "mary"]
probabilities = [0.2, 0.7, 0.1] # probabilities of each player
winner = np.random.choice(players, p=probabilities)
Hope that helps.
Ronny