183k views
4 votes
9.16 LAB: Elements in a range 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. That list is followed by two more integers representing lower and upper bounds of a range. Your program should output all integers from the list that are within that range (inclusive of the bounds). For coding simplicity, follow each output integer by a space, even the last one

2 Answers

2 votes

Answer:

  1. numList = []
  2. length = int(input("Enter a number: "))
  3. numList.append(length)
  4. for i in range(0, length):
  5. num = int(input("Enter a number: "))
  6. numList.append(num)
  7. lowerBound = int(input("Enter a number: "))
  8. numList.append(lowerBound)
  9. upperBound = int(input("Enter a number: "))
  10. numList.append(upperBound)
  11. output = ""
  12. for i in range(1, len(numList) - 2):
  13. if(numList[i] >= lowerBound and numList[i] <= upperBound):
  14. output += str(numList[i]) + " "
  15. print(output)

Step-by-step explanation:

The solution is written in Python 3.

Firstly create a list to hold a list of input (Line 1).

Prompt user to enter the number of desired integer and add it to the numList (Line 3- 4).

Create a for-loop that loop for length times and prompt user to enter a number and add it to numList repeatedly (Line 6 -8).

Next, prompt user to input lowerBound and upperBound and add them as the last two elements of the list (Line 10 - 14).

Create an output string (Line 16) and create another for loop to traverse through the numList from second element to third last elements (Line 18). if the current value is bigger to lowerBound and smaller than upperBound then add the current value to the output string.

At last, print the output string (Line 22).

User Jumar
by
6.6k points
3 votes

Below is a simple Python program that accomplishes the described task.

def filter_integers_in_range():

# Get the number of integers

num_integers = int(input("Enter the number of integers: "))

# Get the list of integers

integer_list = []

for _ in range(num_integers):

integer = int(input("Enter an integer: "))

integer_list.append(integer)

# Get the lower and upper bounds of the range

lower_bound = int(input("Enter the lower bound of the range: "))

upper_bound = int(input("Enter the upper bound of the range: "))

# Output integers within the specified range

result = [str(num) for num in integer_list if lower_bound <= num <= upper_bound]

print("Integers within the range:", " ".join(result))

# Run the program

filter_integers_in_range()

User Cruel
by
6.9k points