What type of repetition would be appropriate for calculating the sum of arbitrary number of positive numbers?

Article type: {{ thisQuesInfo.pageType.substr(0, 1).toUpperCase() + thisQuesInfo.pageType.substr(1) }}

{{ thisQuesInfo.Title }}

{{ thisQuesInfo.Author }} published this on {{ thisQuesInfo.Date.replace(/-/g, '/') }}

Comments ({{ bestVotes.length }})

{{ comment.value }}

{{ comment.thisAnsInfoAuthor }} commented on {{ comment.thisAnsInfoDate }}

Leave a comment

Log in to submit a comment.

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 Nov 1, 2021 at 19:45

2

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 Nov 1, 2021 at 19:57

Chris JChris J

1,3758 silver badges19 bronze badges

2

x = flag = 1 for i in range(n-1, -1, -1): print(x) flag, x = -flag, x+flag*i

answered Nov 1, 2021 at 20:10

MaratMarat

14.1k2 gold badges37 silver badges45 bronze badges

1

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 Nov 1, 2021 at 19:56

SamwiseSamwise

58k3 gold badges29 silver badges38 bronze badges

2

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 Nov 1, 2021 at 20:00

MatiissMatiiss

5,6562 gold badges12 silver badges27 bronze badges

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 Nov 1, 2021 at 20:15

Jon KiparskyJon Kiparsky

7,2212 gold badges22 silver badges38 bronze badges

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 Apr 30 at 15:36

1

Toplist

Neuester Beitrag

Stichworte