0

I need to write a program that first gets a list of integers from input. That list is followed by two more integers representing lower and upper bounds of a range. Then output all integers from the list that are within that range (inclusive of the bounds).

For example, if the input is:

27 200 49 71
0 60

the output should be:

27 49

This is what I have so far:

input_numbers = input().split(' ')
input_range = input().split(' ')

for number in input_numbers:
    if input_range[0] <= number <= input_range[1]:
        print('{}'.format(number), end = ' ')

I'm not sure what I'm doing wrong.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
takuyasama
  • 1
  • 1
  • 1
  • 1

3 Answers3

0

input() returns a string, you have to cast the numbers to integers, i.e.:

input_numbers = [int(x) for x in input().split(' ')]
input_range = [int(x) for x in input().split(' ')]

for number in input_numbers:
    if input_range[0] <= number <= input_range[1]:
        print('{}'.format(number), end = ' ')
0

The input() method gives a string, then you split() so you have an array of string, so you comparison < is done on string and not on int, so the order you use is the lexicographical (alphabetical) order, where '0' < '200' < '60'


You can convert to int each one at the comparison moment

for number in input_numbers:
    if int(input_range[0]) <= int(number) <= int(input_range[1]):
        print('{}'.format(number), end=' ')

But the best is to convert the values, once, after getting them from user (alo provide a text to input, that helps to know what to write, and not wait without knowing the code expects something)

input_numbers = list(map(int, input("Please input values: ").split()))
input_range = list(map(int, input("Please 2 boundaries").split()))

for number in input_numbers:
    if input_range[0] <= number <= input_range[1]:
        print('{}'.format(number), end=' ')
azro
  • 53,056
  • 7
  • 34
  • 70
0

Just another way of doing it:

numbers = map(int, input().split())
ran = range(*map(int, input().split()))

out = [n for n in numbers if n in ran]
print(*out)
#27 49

Note: The method str.split splits by white spaces by default.

Pablo C
  • 4,661
  • 2
  • 8
  • 24