必须告诉用户将B更改为A需进行几次翻转的代码无法正常工作

时间:2019-06-09 06:21:31

标签: python

我已经编写了一些代码,其中我必须编写一个程序来询问用户一排煎饼,其中包含字母 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()

代码存在问题,因为当前无法正确输出正确的翻转次数。

谢谢。

1 个答案:

答案 0 :(得分:1)

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

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