简体   繁体   中英

How to get rid of the use of “end” in loops(python) for only the last element?

By using end="-" I got this loop. I want to remove that '-' for the last element.

  m=4
  n=1
  for i in range(1,4):
      for x in range(5,n,-1):
          print(" ",end="")
      n+=2  
      for y in range(3,3-i,-1):
          print(y,end="-")
      for z in range(m,4):
          print(z,end="-")
      m-=1  
      print()

Output:

           3-
       3-2-3-
    3-2-1-2-3-

Instead of using end , you can actually use sep , which only separates between elements which sounds like what you want. This will even reduce your loops a bit.

You will have to change the prints to be something like: print(*range(m, 4), sep='-') .

The spaces ( ' ' ) loop is also not necessary and can be a single print , so your whole code can look like:

m = 4
n = 1
for i in range(1, 4):
    print(" " * abs(5-n), end='')
    n += 2
    print(*range(3, 3-i, -1), *range(m, 4), sep='-')
    m -= 1

It is also possible to only use the loop variable i and avoid maintaining m and n . So the code can be reduced to:

m = 4
for i in range(1, m):
    print(" " * abs(5-i*2+1), end='')
    print(*range(3, 3-i, -1), *range(m-i+1, m), sep='-')

which gives:

    3
  3-2-3
3-2-1-2-3

Finally, to make it more reasonable by m being the range being printed, and making it completely generic to allow any m you can do:

m = 4
for i in range(1, m+1):
    print(" " * (m*2-i*2), end='')
    print(*range(m, m-i, -1), *range(m-i+2, m+1), sep='-')

Which will now print up-to 4 :

      4
    4-3-4
  4-3-2-3-4
4-3-2-1-2-3-4

Welcome to SO!

Nice work progress, Here. in my solution I am trying to is to divide the responsibilities into smaller tasks.

  1. To generate the number to print
  2. To print these in design format
m=4
n=1
max_line_length = 20

def special_print(items):
    # convert each number to string
    str_items = [str(each) for each in items]
    # prepare output string
    output_string = '-'.join(str_items)
    prefix = ' ' * (max_line_length - len(output_string))
    print(prefix + output_string)
    # try
    # print(output_string.center(max_line_length))

for i in range(1,4):
    items = []
    n+=2  
    for y in range(3,3-i,-1):
        items.append(y)
    for z in range(m,4):
        items.append(z)
    m-=1
    # print(items)
    special_print(items)

Output

                   3
               3-2-3
           3-2-1-2-3

Note: This solution can be further simplified by Python Pros but I tried to keep simple enough for you to understand.

You can explore python string objects features like center , join and list-comprehension, len function to improve your Python skills.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM