Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest).
Example: If the input is:
10 -7 4 39 -6 12 2
the output is:
2 4 10 12 39
My code that I came up with looks like this:
user_input = input()
numbers = user_input.split()
nums = []
for number in numbers:
nums.append(int(number))
for item in nums:
if int(item) < 0:
nums.remove(item)
list.sort(nums)
for x in nums:
print(x, end=' ')
It gives me an 8/10 for my score but on one of the input/outputs it gives me
input is -1 -7 -2 -88 5 -6 my output is -88 -7 5
Why is it only removing some of the negative numbers and not all of them?
CodePudding user response:
for item in nums:
if int(item) < 0:
nums.remove(item)
problem is probbably here, since you iterate thru a list for which you remove elements in the iterations of the for el in list loop.
You should just use list comprenhension to copy positive integers to a new list and return it.
So the return list would be:
onlyPositiveIntegers = [x for x in nums if x >= 0]
CodePudding user response:
nums.sort()
for item in nums:
if int(item) >= 0:
break
nums.remove(item)
print(*nums)
iterate only through -ve no. and remove them.