'LAB: Output values in a list below a user defined amount
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, which indicates a threshold. Output all integers less than or equal to that last threshold value.
Ex: If the input is:
5
50
60
140
200
75
100
the output is:
50,60,75,
The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100 indicates that the program should output all integers less than or equal to 100, so the program outputs 50, 60, and 75.
For coding simplicity, follow every output value by a comma, including the last one.
Such functionality is common on sites like Amazon, where a user can filter results.
My code is:
n = int(input())
user_values =[]
def get_user_values():
for i in range(n):
num = int(input())
user_values.append(num)
upper_threshold=user_values[-1]
return user_values, upper_threshold
def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
user_values = [i for i in user_values if i <= upper_threshold]
print(*user_values, sep = "\n")
if __name__ == '__main__':
user_values, upper_threshold = get_user_values()
output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold)
With inputs:
7
25
30
47
28
27
25
31
30
My output:
25
30
28
27
25
31
But my expected output:
25,30,28,27,25,
Solution 1:[1]
You are requesting the following routine:
- Read the nr of inputs
- Read the input numbers (in the code below, they will be appended to the
list) - Read the threshold
- Filter the list
list = []
result = []
n = int(input()) # 1
for i in range(n): # 2
number = int(input())
list.append(number)
threshold = int(input()) # 3
# --- The following is one way of filtering the list, it checks every entry and either appends it to the result-list or ignores it
for i in list: # 4
if i <= threshold:
print(i, end=",")
result.append(i)
In the result variable, you will find your answer
Solution 2:[2]
def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
for value in user_values:
if value <= upper_threshold:
print(value, end="," )
def get_user_values():
n = int(input())
lst = []
for i in range(n):
lst.append(int(input()))
return lst
if __name__ == '__main__':
userValues = get_user_values()
upperThreshold = int(input())
output_ints_less_than_or_equal_to_threshold(userValues, upperThreshold)
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 | STh |
| Solution 2 | Javad Nikbakht |
