Python 一旦目标匹配,如何停止发电机?
试图创建一个生成器,该生成器生成指定范围内的随机数字集,然后在生成指定目标数字后停止。将打印尝试达到该数字的次数。如果在指定的尝试次数内未生成该数字,则用户将收到单独的提示。以下是我目前掌握的情况:Python 一旦目标匹配,如何停止发电机?,python,random,generator,Python,Random,Generator,试图创建一个生成器,该生成器生成指定范围内的随机数字集,然后在生成指定目标数字后停止。将打印尝试达到该数字的次数。如果在指定的尝试次数内未生成该数字,则用户将收到单独的提示。以下是我目前掌握的情况: try: min_value = int(input("Enter the minimum value for your random generator: ")) max_value = int(input("Enter the maximum val
try:
min_value = int(input("Enter the minimum value for your random generator: "))
max_value = int(input("Enter the maximum value for your random generator: "))
target = int(input("Enter the target value you are trying to find: "))
max_attempts = int(input("Enter the maximum number of attempts to find the target before stopping generation: "))
except ValueError:
print("Please enter an integer value for your input!")
def find_target(target: int, min_value: int, max_value: int, max_attempts: int) -> Optional[int]:
# Start counter for number of attempts
j = 0
while j in range(max_attempts):
#Increment the attempts counter
j += 1
for k in range(min_value, max_value):
if not target:
yield k
gen = find_target(target, min_value, max_value, max_attempts)
while True:
print(next(gen))
一旦找到目标,理想情况下会发生这样的事情:
# Stop the generator
print("Target acquired! It only took ", j, "tries to find the target!")
gen.close()
if find_target(target, min_value, max_value, max_attempts) is None:
print("Could not find target within the max number of attempts. Maybe better luck next time?")
现在,生成器只是立即停止(我猜这与如何指定
而不是target
有关)。我怎样才能让逻辑工作呢?如果您想返回目标,只需将收益率放在If语句之后
随机导入
def gen(低、高、尝试、目标):
对于范围(1,尝试次数+1)内的j:
guess=random.randint(低、高)
产量猜测
如果guess==目标:
打印()
打印(“已获取目标!只需,”,j,“尝试找到目标!”)
打破
其他:
打印()
打印(“未能在最大尝试次数内找到目标。下次可能会更走运?”)
低,高=0,10
尝试次数=10次
目标=5
对于发电机中的el(低、高、尝试、目标):
打印(el,结束=“”)
产出:
7 0 0 3 3 5
Target acquired! It only took 6 tries to find the target!
#or
4 2 0 6 1 4 3 6 1 6
Could not find target within the max number of attempts. Maybe better luck next time?
若要返回目标,只需将收益率放在If语句之后
随机导入
def gen(低、高、尝试、目标):
对于范围(1,尝试次数+1)内的j:
guess=random.randint(低、高)
产量猜测
如果guess==目标:
打印()
打印(“已获取目标!只需,”,j,“尝试找到目标!”)
打破
其他:
打印()
打印(“未能在最大尝试次数内找到目标。下次可能会更走运?”)
低,高=0,10
尝试次数=10次
目标=5
对于发电机中的el(低、高、尝试、目标):
打印(el,结束=“”)
产出:
7 0 0 3 3 5
Target acquired! It only took 6 tries to find the target!
#or
4 2 0 6 1 4 3 6 1 6
Could not find target within the max number of attempts. Maybe better luck next time?
不是要求什么,但我没有看到任何随机张贴的代码
range
是一个序列生成器,如果有的话。不是要求的,但是我在发布的代码中没有看到任何随机的东西range
是一个序列生成器(如果有的话)。我能够修复错误,但现在它在每个生成的值之后打印找不到目标的消息。我怎么能让它只在最后打印?数字是在控制台中垂直打印的,而不是在编码的“哦,我的其他缩进不正确,成功了,非常感谢您的帮助!”!我能够修复错误,但现在它会在每个生成的值之后打印找不到目标
消息。我怎么能让它只在最后打印?数字是在控制台中垂直打印的,而不是在编码的“哦,我的其他缩进不正确,成功了,非常感谢您的帮助!”!