2

我在打印替代图案时遇到问题,输出应该是这样的:

input height: 7

22
1122
221122
11221122
2211221122
112211221122
22112211221122

但结果却是这样的:

input height: 7
22
1111
222222
11111111
2222222222
111111111111
22222222222222

代码:

height = int (input ("input height: "))

for level in range (1, height+1):
    num = level

    for x in range (num):
        if( level%2==0): #Even row starts with "11" first
            print ("11",end = "")
        else:
            print ("22",end = "")
    print()

通过使用循环,while,for 循环,没有列表。我怎样才能做到这一点?

4

6 回答 6

2

它不会像您想要的那样出现,因为您选择每行仅使用一种类型的填充字符if(level%2==0):

看起来您需要弄清楚如何在每行的两个不同填充值之间切换。我建议:

  1. 在打印之前为每一行累积一个字符串
  2. 您研究了如何使用序列(列表或元组)循环遍历值。itertools您还可以使用一个工具。
于 2013-09-24T15:26:49.270 回答
2

您可以通过从左侧插入新字符来在每次迭代中添加字符串:

s = ""
for i in range(height):
    s = ('22', '11')[i % 2] + s
    print(s)

或者每次迭代都构建整个字符串:

for i in range(height):
    print ''.join(('11', '22')[j % 2] for j in range(i + 1, 0, -1))

或预先计算最后一行并从右侧切分:

s = '1122' * (height / 2 + 1)
for i in range(height):
    print s[(i+1) * -2:]
于 2013-09-24T15:30:43.920 回答
1

对于x循环中的所有内容,level永远不会改变。您需要交替基于,x同时选择基于 的开始level

height = int (input ("input height: "))

for level in range (1, height+1):
    num = level

    for x in range (num):
        if( (level+x)%2==0): #Even row starts with "11" first
            print ("11",end = "")
        else:
            print ("22",end = "")
    print()

请注意我如何添加level以及x在修改它之前针对 2。

于 2013-09-24T15:27:58.753 回答
0
tmp = "1122" * height
for tail in range(1, height+1):
    print tmp[-2*tail:]

完毕

于 2013-09-24T15:35:48.530 回答
0

改变:

if( level%2==0): #Even row starts with "11" first

if( (level+x) %2==0): #Even row starts with "11" first

蟒蛇 2.7:

for level in range(1,height+1):
     for x in range(level):                                                   
        if((level+x)%2==0):                                                  
            print "11",                                                      
        else:                                                                
            print "22",
于 2013-09-24T15:29:55.167 回答
0
height = int (input ("input height: "))

for level in range (1, height+1):
   # Starting at level gives the proper oddity, while 2* level give the proper loop length
    for x in range (level, 2 * level):
        if( x%2==0): #Even row starts with "11" first
            print ("11",end="")
        else:
            print ("22",end="")
    print()
于 2013-09-24T15:30:33.137 回答