简体   繁体   English

如何管理while循环以反转此打印

[英]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".我最近开始编码,目前我正在做一个练习,我需要创建一个打印“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".我已经达到了可以打印“5、9、12、14、15”的程度,但我不知道如何用这些“拼图”来扭转这一点。 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:如果不使用 while:

Using split() on string converts it into a list, then used [::-1] to reverse a list, then used replace() to remove duplicate separator ",,"对字符串使用split()将其转换为列表,然后使用[::-1]反转列表,然后使用replace()删除重复的分隔符“,,”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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