首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >必须告诉用户需要多少次翻转才能将B更改为A的代码无法正常工作

必须告诉用户需要多少次翻转才能将B更改为A的代码无法正常工作
EN

Stack Overflow用户
提问于 2019-06-09 14:21:32
回答 1查看 100关注 0票数 0

我写了一些代码,其中我必须编写一个程序,要求用户要一排煎饼,它们可以是字母A或B,其中代码必须告诉用户需要多少次翻转才能制作所有的煎饼A,其中用户必须输入一次可以翻转多少个煎饼。如果煎饼不能翻转,并且全是字母_A_s,那么代码必须输出This couldn't be done. Would you like to try again?

代码当前输出以下内容:

代码语言:javascript
复制
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? 

其中,它应该输出以下内容:

代码语言:javascript
复制
Enter the row and the side of the pancakes (A/B): BBBB
How many pancakes can flipped at one time? 2

而且它不应该告诉用户他们是否想再玩一次,因为煎饼还没有完全翻到A。

我的代码如下:

代码语言:javascript
复制
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()

代码的一个问题是它目前不能正确地输出正确的翻转次数。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-09 17:25:32

下面是我用来解决这个问题的代码。

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56512446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档