如何编写程序打印出 1 和给定数字之间的所有正整数,并在范围的两端之间交替?

How to write the program that prints out all positive integers between 1 and given number , alternating between the two ends of the range?

该程序应按如下方式运行:

Please type in a number: 5
1
5
2
4
3

我的代码不这样做。我认为应该有第二个循环,但我真的不明白我该怎么做。你能给我一个提示或建议来解决这个任务吗?谢谢。 我的代码如下所示:

num = int(input("Please type in a number:"))
n=0
while num>n:
    a = num%10
    num -= a
    num = num/10
    print(a)
    n = n + 1   
print(n)

这不是最 space 最有效的方法,但如果数量相对较少,一个简单的方法是构建一个列表,然后依次从两端弹出:

nums = list(range(1, int(input("Please type in a number:"))+1))
while nums:
    print(nums.pop(0))
    if nums:
        print(nums.pop())

这应该有效:

num = int(input("Please type in a number:"))
number_list = [i+1 for i in range(num)]

while number_list:
    print(number_list.pop(0))
    number_list.reverse()

似乎最有效的内存方法是使用 itertools.zip_longestranges:

from itertools import zip_longest

n = int(input("Please type in a number: "))
for lower, upper in zip_longest(range(1, n // 2 + 1), range(n, n // 2, -1)):
    if lower:
        print(lower)
    print(upper)
x = flag = 1
for i in range(n-1, -1, -1):
    print(x)
    flag, x = -flag, x+flag*i

这是一种可爱的方式:

l = list(range(1,6))
def index_generator():
    while True:
        yield 0
        yield -1

index = index_generator()
result = []
while l:
    result.append(l.pop(next(index)))
number = int(input())
 
left = 1
right = number
 
while left < right:
    print(left)
    print(right)
    left += 1
    right -= 1
# In case of odd numbers
if left == right:
    print(left)`