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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (6)

我已经写了一些代码,我必须写一个程序,要求用户与他们煎饼的一排或者是字母一个,其中代码必须告诉多少翻转才能使所有的煎饼用户一个在用户必须输入一次连续翻转多少煎饼。如果煎饼不能翻转并且所有字母都是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()

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

谢谢。

提问于
用户回答回答于

Here's my code to solve this problem...

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

所属标签

可能回答问题的人

  • HKC

    红客学院 · 创始人 (已认证)

    26 粉丝7 提问5 回答
  • Dingda

    Dingda · 站长 (已认证)

    4 粉丝0 提问3 回答
  • 西风

    renzha.net · 站长 (已认证)

    9 粉丝1 提问3 回答
  • 螃蟹居

    1 粉丝0 提问2 回答

扫码关注云+社区

领取腾讯云代金券