我写了一些代码,其中我必须编写一个程序,要求用户要一排煎饼,它们可以是字母A或B,其中代码必须告诉用户需要多少次翻转才能制作所有的煎饼A,其中用户必须输入一次可以翻转多少个煎饼。如果煎饼不能翻转,并且全是字母_A_s,那么代码必须输出This couldn't be done. Would you like to try again?
。
代码当前输出以下内容:
Enter the row and the side of the pancakes A/B): BBBB
How many pancakes can flipped at one time? 2
It took 0 flips.
Would you like to run this program again?
其中,它应该输出以下内容:
Enter the row and the side of the pancakes (A/B): BBBB
How many pancakes can flipped at one time? 2
而且它不应该告诉用户他们是否想再玩一次,因为煎饼还没有完全翻到A。
我的代码如下:
i = True
flips = 0
while i == True:
pancakes = list(input('Enter the row and the side of the pancakes (A/B): '))
flipper = int(input('How many pancakes can be flipped at one time? '))
i = False
if 'O' in pancakes:
flips = flips + 1
for x in range(flipper):
if pancakes[x] == 'A':
pancakes[x] = 'B'
pancakes = (''.join(pancakes))
if flips == 1:
print('It took 1 flip.')
play = input("Would you like to run this program again? ")
if play == 'Yes' or play == 'yes' or play == 'Y' or play == 'y':
i = True
else:
quit()
if flips == 0:
print('It took', flips, 'flip.')
play = input("Would you like to run this program again? ")
if play == 'Yes' or play == 'yes' or play == 'Y' or play == 'y':
i = True
else:
quit()
if flips > 1:
print('It took', flips, 'flip.')
play = input("Would you like to run this program again? ")
if play == 'Yes' or play == 'yes' or play == 'Y' or play == 'y':
i = True
else:
quit()
代码的一个问题是它目前不能正确地输出正确的翻转次数。
谢谢。
发布于 2019-06-09 17:25:32
下面是我用来解决这个问题的代码。
while True:
pancakes = input('Enter the row and the side of the pancakes (A/B): ')
flipper = int(input('How many pancakes can be flipped at one time? '))
result, possible = 0, True
for row in pancakes.split('B'):
cnt, rem = divmod(len(row), flipper)
if rem != 0:
possible = False
break
result += cnt
if possible:
print('It took %d flips.' % result)
resp = input('Would you like to run this program again? ')
else:
resp = input("This couldn't be done. Would you like to try again? ")
if resp.lower() not in ['yes', 'y']:
break
https://stackoverflow.com/questions/56512446
复制相似问题