我在打印备用图案时遇到问题,输出假设如下:
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循环,没有列表。我怎样才能做到这一点?
答案 0 :(得分:2)
它不会像你想要的那样出现,因为你选择只使用if(level%2==0):
每行一种类型的填充字符。
看起来你需要弄清楚如何在每一行上的两个不同的填充值之间切换。我建议:
itertools
中的工具。答案 1 :(得分: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:]
答案 2 :(得分: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()
注意我在将其修改为2之前添加level
和x
的方式。
答案 3 :(得分:0)
变化:
if( level%2==0): #Even row starts with "11" first
到
if( (level+x) %2==0): #Even row starts with "11" first
Python 2.7:
for level in range(1,height+1):
for x in range(level):
if((level+x)%2==0):
print "11",
else:
print "22",
答案 4 :(得分: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()
答案 5 :(得分:0)
tmp = "1122" * height
for tail in range(1, height+1):
print tmp[-2*tail:]
完成