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

Question:

The program should work as follow:

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

My code doesn’t do the same. I think there is should be the 2nd loop, but I don’t really understand how can I do it. Could you possibly give me a hint or advice to solve this task. Thanks.
My code looks like this:

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)
Asked By: Denis

||

Answers:

Not the most space-efficient way, but if the number is relatively small, an easy approach is to build a list and just pop off either end in turn:

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

This should work:

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()
Answered By: Chris J

Seemingly the most memory efficient way would be to use itertools.zip_longest and ranges:

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)
Answered By: Matiiss
x = flag = 1
for i in range(n-1, -1, -1):
    print(x)
    flag, x = -flag, x+flag*i
Answered By: Marat

This is a cute way to do it:

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)))
Answered By: Jon Kiparsky
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)`
Answered By: enigmacoder-bot
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.