1

can anyone help me with this code. It must be done using for and if only.

        0
      1 0 1
    2 1 0 1 2
  3 2 1 0 1 2 3
4 3 2 1 0 1 2 3 4

I tired and think every stuff but I dont understand what i am missing. I am having a issue with generating 101, 21012, 3210123, 43211234

here is my code(which is wrong)

for i in range (1,6):
    for t in range (i,5):
        print('\t', end="")
    for j in range (0,(2*i-1)):
        print(2*i-1-j, "\t", end="")
    print("")

enter image description here

2
  • the formating is disturbed after posting. Please check the image attached. I Commented Dec 1, 2018 at 3:56
  • Please fix formatting. At least for the code. Commented Dec 1, 2018 at 3:57

5 Answers 5

1

If you allow list-comprehension

num = 4
for i in range(num+1):
    j = [str(n) for n in range(i+1)]
    k = list(reversed(j))
    print (' '.join([' '] * (num-i) + k + j[1:]))

Output:

        0
      1 0 1
    2 1 0 1 2
  3 2 1 0 1 2 3
4 3 2 1 0 1 2 3 4
Sign up to request clarification or add additional context in comments.

1 Comment

thats something new. I have not come across list-comprehension till now. I am going to study about it. Thanks
0

In each row, the numbers start high, then go down to zero, then go up again. Since loops typically only go in one direction, why not use two loops? If you have one loop count from i down to one and then the next one count from 0 up to i, you should get your desired result. Let me know if there's anything you would like for me to clarify about this.

Comments

0

so here is my final code which run correctly strong text

for i in range (1,6):
    for t in range (i,5):
        print('\t', end="")
    for j in range (0,i):
        print(i-j-1, "\t", end="")
    for k in range (1,i):
        print (k,"\t" ,end="")
    print("")

1 Comment

Try remove \t in j and k print loop.
0

This is a different solution using list:

n = 4
lizst = [0]
for h in range (1, n+2):
  print("\t"*(n+1-h), end = "")
  [print(e, "", end = "") for e in lizst]
  lizst = [h] + lizst + [h]
  print()

Comments

0

Soultion using just for loop.

spaces=4
limits=0

for line in range(5):
    for space in range(spaces):
        print(' ',end=' ')
    for limit in range(limits,-1,-1):
        print(limit,end=' ')
    for limit in range(1,limits+1):
        print(limit,end=' ')
    spaces-=1
    limits+=1
    print('\n')

Output

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.