Reputation: 21
I'm having trouble on printing alternate pattern, the output is suppose to look like this:
input height: 7
22
1122
221122
11221122
2211221122
112211221122
22112211221122
But instead it came out like this:
input height: 7
22
1111
222222
11111111
2222222222
111111111111
22222222222222
Code:
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()
By using looping, while, for loop, no list. How can I do this?
Upvotes: 2
Views: 135
Reputation: 45562
You could add to the string each iteration by inserting new characters from the left:
s = ""
for i in range(height):
s = ('22', '11')[i % 2] + s
print(s)
Or just build the whole string each iteration:
for i in range(height):
print ''.join(('11', '22')[j % 2] for j in range(i + 1, 0, -1))
Or precompute the last row and slice it from the right:
s = '1122' * (height / 2 + 1)
for i in range(height):
print s[(i+1) * -2:]
Upvotes: 2
Reputation: 11775
tmp = "1122" * height
for tail in range(1, height+1):
print tmp[-2*tail:]
done
Upvotes: 0
Reputation: 39403
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()
Upvotes: 0
Reputation: 622
change:
if( level%2==0): #Even row starts with "11" first
to
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",
Upvotes: 0
Reputation: 3131
For everything inside your x
loop, level
never changes. You need to alternate based on x
while choosing your start based on 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()
Notice how I add level
and x
before modding it against 2.
Upvotes: 1
Reputation: 49886
It's not coming out like you want it, because you are choosing to use only one type of fill character per line with if(level%2==0):
.
It looks like you need to figure out how to switch between two different fill values on each line. I suggest that:
itertools
you could use.Upvotes: 2