目前正在努力从头开始学习Python 3.5并彻底享受这个过程。最新的事情是编写一个执行以下操作的基本程序..
现在我认为我已经完成所有工作减去更高/更低的功能。我的问题是这个。
注意这与该主题的其他问题不同,因为我不想为PC输入任何数字来处理。还希望生成伪随机数,其被限制在给定值内,以用于来自PC的后续猜测。不增加。
“我如何实现一个查看var' guess'的功能,并根据用户输入将其修改为更高或更低,同时保持高于0且低于100”。
代码:
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a lower guess, 3 for a higher one and 2 if I get it right\n")
tries = int(1)
guess = random.randint(1, 100)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 if too high, 3 if too low or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
print("Balls! Guess I need to go Higher will", + guess, + "do?")
elif feedback == 3:
print("\nSh*te! Lower it is then...")
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
print("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")
答案 0 :(得分:0)
你可以做类似二元搜索的事情。使用low_number和high_number通过取两者的中间值来计算猜测。这些最初可以设置为0和100.您还应该跟踪上次猜测。如果你的上次猜测太低,你可以将你的low_number设置为等于猜测+ 1。如果您的上一次猜测太高,可以将您的high_number设置为该guess-1。
答案 1 :(得分:0)
好的,这是我到目前为止所拥有的。它的工作原理是它将根据用户输入以(半)随机更高或更低的猜测进行响应,但尚未将原始猜测存储为参考。我明天会看。再次感谢您的建议。
BTW一旦工作,我打算使用数学,并提出一个解决方案,总是在x次尝试中正确... import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a higher guess, 3 for a lower one and 2 if I get it right\n")
tries = int()
guess = random.randint(1, 100)
high_number = int(100 - guess)
low_number = int(1 + guess)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 to go higher, 3 to go lower or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
guess = random.randint(high_number, 100)
print("Balls! Guess I need to go Higher how about", + guess)
elif feedback == 3:
guess = random.randint(1, low_number)
print("\nSh*te! Lower it is then... what about", + guess)
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
input("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")