首页 > 解决方案 > 必须告诉用户将 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()

代码的一个问题是它当前没有正确输出正确的翻转次数。

谢谢。

标签: python

解决方案


这是我解决此问题的代码...

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

推荐阅读