2

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

2
  • For starters, can you not work out where the extra 0s come from and do something about it? numList[n] = 0 --> numList.pop() for example. Commented Jul 31, 2016 at 23:27
  • Sorry kaylum, I'm still learning basics and completely forgot about the .pop() function, this will make it a lot easier, now I can just figure out how to 'reverse' it Commented Jul 31, 2016 at 23:30

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

here is an example

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.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.