'How to write the program that prints out all positive integers between 1 and given number , alternating between the two ends of the range?
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)
Solution 1:[1]
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()
Solution 2:[2]
x = flag = 1
for i in range(n-1, -1, -1):
print(x)
flag, x = -flag, x+flag*i
Solution 3:[3]
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())
Solution 4:[4]
Seemingly the most memory efficient way would be to use itertools.zip_longest
and range
s:
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)
Solution 5:[5]
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)))
Solution 6:[6]
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)`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris J |
Solution 2 | Marat |
Solution 3 | Samwise |
Solution 4 | Matiiss |
Solution 5 | |
Solution 6 | enigmacoder-bot |