简体   繁体   中英

How to manage while-loop to reverse this print

I have recently started coding and currently I'm doing an exercise where I need to create a program that prints "15, 14, 12, 9, 5". The program should be created with the pieces provided in the code. This means that I can only move these lines of code around but not alter them or add new code . I have reached a point where I can print "5, 9, 12, 14, 15", but I don't know how to reverse this with these "puzzle pieces". Could someone help me out?

EDIT: Got an answer, thanks!

i = 0
MAX = 5
sum = 0
j = MAX
while j > i:
    while i < MAX:
        sum += j
        print(sum)
        j -= 1
        i += 1

This seems to work

i = 0
MAX = 5
while i < MAX:    
  sum = 0
  j = MAX
  while j > i:
    sum += j
    j -= 1
  i += 1
  print(sum)

Very interesting task they gave you :)

Try this

sum = 15
i = 1
while sum > 0:
    print(sum)
    sum -= i
    i += 1

Edit:

i = 0
MAX = 5
while i < MAX:
    sum = 0
    j = MAX
    while j > i:
        sum += j
        j -= 1
    i += 1
    print(sum)

if not using while:

Using split() on string converts it into a list, then used [::-1] to reverse a list, then used replace() to remove duplicate separator ",,"

",".join("15, 14, 12, 9, 5".split()[::-1]).replace(",,",",")

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