Python for循环具有非期望的结果

时间:2014-09-09 17:27:30

标签: python loops

我应该从命令行获得一个整数输入并输出一个循环:

AA
BBAA
AABBAA
BBAABBAA

其中输出行数由输入给出。

这就是我的尝试:

height = int(input('input height: '))

for row in range(1,height+1):
    for pattern in range(1,row+1):
        if row % 2 != 0:
            for x in range(1, pattern+1, 2):
                print('AA', end = '')
                break
            for x in range(2, pattern+1, 2):
                print('BB', end = '')
                break
        else:
            for x in range(1, pattern+1, 2):
                print('BB', end = '')
                break
            for x in range(2, pattern+1, 2):
                print('AA', end = '')
                break
    print()

给出了:

input height: 4
AA
BBBBAA
AAAABBAABB
BBBBAABBAABBAA

4 个答案:

答案 0 :(得分:3)

您可以更轻松地完成整个过程。请注意,在每一行上,您只需在前一个字符串的前面添加“AA”或“BB”。

height = int(input('input height: '))

laststring = ""
for i in range(height):
    if i%2==0:
        laststring = "AA" + laststring
    else:
        laststring = "BB" + laststring
    print laststring

答案 1 :(得分:0)

这个怎么样?假设我已正确解释您想要的输出。请注意,我正在使用奇偶校验(ii+jj)%2来生成您尝试生成的交替“AA”和“BB”的“棋盘”模式。

height = int(input('input height: '))

for ii in range(1, height+1):
    s = ""
    for jj in range(1, ii+1):
        s += ["AA","BB"][ (ii+jj)%2 ]
    print(s)

结果:

input height: 7
AA
BBAA
AABBAA
BBAABBAA
AABBAABBAA
BBAABBAABBAA
AABBAABBAABBAA

答案 2 :(得分:0)

  print "".join(["BBAA" for x in range(height/2+1)][-2*height:]

  AABBAABBAABBAA


   for height in range(1,10):
          print "".join(["BBAA" for x in range(height/2+1)][-2*height:]


  AA
  BBAA
  AABBAA
  BBAABBAA
  AABBAABBAA
  BBAABBAABBAA
  AABBAABBAABBAA
  BBAABBAABBAABBAA
  AABBAABBAABBAABBAA

答案 3 :(得分:0)

原始帖子非常接近可行的解决方案,除了无条件休息。解决方案只是原始版本的略微修改版本:

height = int(input('input height: '))

for row in range(1,height+1):
    for pattern in range(1,row+1):
        if row % 2 != 0:
            if pattern % 2 == 1:
                print('AA', end = '')
            else:
                print('BB', end = '')
        else:
            if pattern % 2 == 1:
                print('BB', end = '')
            else:
                print('AA', end = '')
    print()