Home > Blockchain >  What I am doing wrong? Output values below an amount
What I am doing wrong? Output values below an amount

Time:07-29

Here is the question I am working on:

Write a program that first gets a list of integers from input. The last value of the input represents a threshold. Output all integers less than or equal to that threshold value. Do not include the threshold value in the output.

For simplicity, follow each number output by a comma, including the last one.

Ex: If the input is:

50 60 140 200 75 100

the output should be:

50,60,75,

My code is:

n = int(input())
lst = []
for i in range(n):
    lst.append(int(input()))
threshold = int(input())
for i in range(n):
    if list[i] <= threshold:
        print(last[i],end=',')

I keep getting an error, and I can't seem to know why:

ValueError: invalid literal for int() with base 10: '50 60 140 200 75 100' 

CodePudding user response:

This is a clean way to do this:

# import numbers separated with a space
n = input()
n = n.split(' ')
n = [int(x) for x in n]  # <-- converts strings to integers

# threshold is the last number
threshold = n[-1]

# get the result
result = [x for x in n if x < threshold]
print(result)

the result:

[50, 60, 75]

CodePudding user response:

The following expects one number. Not a list of them.

n = int(input())

Seems like you want to get a list of numbers through one/few prompts. Try something like the following:

n = list(map(int,input("\nEnter the numbers : ").strip().split()))[:]

So your code would look like:

n = list(map(int,input("\nEnter the numbers : ").strip().split()))[:]
lst = []
for i in range(n):
    lst.append(int(input()))
threshold = int(input())
for i in range(n):
    if list[i] <= threshold:
        print(last[i],end=',')

Source: https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/

  • Related