I am trying to achieve this
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
And I'm getting close but now I'm stuck. Here is my current code
def triangle():
n = 9
numList = [0,1,2,3,4,5,6,7,8,9]
for i in range(10):
for i in numList:
print(i, end=" ")
print()
numList[n] = 0
n -= 1
triangle()
And this is the current output
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 0
0 1 2 3 4 5 6 7 0 0
0 1 2 3 4 5 6 0 0 0
0 1 2 3 4 5 0 0 0 0
0 1 2 3 4 0 0 0 0 0
0 1 2 3 0 0 0 0 0 0
0 1 2 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
So I'm there in a round about way, except, its backwards, and there is 0's instead of spaces
You can try this code:
def triangle():
for i in range(10):
print i * " ",
for j in range(10 - i):
print j,
print
triangle()
The code is almost self explaining.
Online example is here
interesting puzzle, you could try this:
n = range(0,10) #set your range
while len(n)<20: #loop until it exhausts where you want it too
print ''.join(str(e) for e in n[0:10]) #print as a string!
n = [' ']+n #prepend blank spaces
You could apply the same logic to your attempt. Basically I add a space to the beggining of N after each loop and then print only the first ten elements. The way I print the list is a little clunky because I am joining, I need to change each element to a string.
The other solutions are fine, but life becomes a little easier with numpy
's arange
and the overloaded *
operator for strings. Python's built-ins are very powerful.
for i in range(11):
print ' ' * i + ''.join(str(elt) for elt in np.arange(10 - i))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.