python - 必须告诉用户将 B 更改为 A 需要多少次翻转的代码无法正常工作
问题描述
我写了一些代码,我必须编写一个程序,要求用户提供一排煎饼,它们要么是字母A要么是B ,代码必须告诉用户制作所有煎饼A需要多少次翻转用户必须输入一次可以连续翻转多少个煎饼。如果煎饼不能翻转并且都是字母A,则代码必须输出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()
代码的一个问题是它当前没有正确输出正确的翻转次数。
谢谢。
解决方案
这是我解决此问题的代码...
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
推荐阅读
- reactjs - 如何在 redux reducer 中更新我的初始状态
- python - 如何在 python 中全屏查看图像?
- android - 如何获取 android constraint-layout-solver 1.0.2 源代码?
- python - 能够让图像在 Pygame 中移动;但我必须继续按下按钮才能让它移动
- python - Python - 在散点处绘制已知大小的矩形
- php - 如果字符串包含,从 utf-8 到 windows-1252 的 php iconv 不起作用
- ffmpeg - 将 OpenEXR 转换为 WebM Alpha Edges Gray
- javascript - 绘制倒圆弧改变圆心坐标
- docker - 如何在 dockerfile 本身中限制 docker 容器的内存
- instagram - 如何使用 api 通过主题标签获取 instagram 媒体?