70.1k views
4 votes
Write a program to prompt the user to enter integers and then adds them to a list (hint: use a loop here). Then convert the list to a NumPy array. Then find and print a subset of the array that contains the given indexes.

For example:

Enter values for the list (Q to quit):
1
2
3
4
5
the printed list would be:

['1', '2', '3', '4', '5']
and the printed ndarray array would be:

[1, 2, 3, 4, 5]
NOTE: The list contains strings and the array contains int's. You will need to declare a type when converting a list to an ndarray.

Finally, output the substring of the array for the given index(es).

For example:

Enter the starting index: 2
Enter the ending index: 4
the printed subset would be: ``` [3, 4]

1 Answer

7 votes

Final answer:

To write this program, use a loop to prompt the user for integers and add them to a list. Then convert the list to a NumPy array with the 'NumPy. Array ()' function, specifying the data type as 'int'. Finally, use array indexing to find and print a subset of the array based on given indexes.

Step-by-step explanation:

To write a program that prompts the user to enter integers and adds them to a list, you can use a while loop. Inside the loop, you can append each input to the list until the user enters 'Q' to quit. Here's an example:

numbers = []
while True:
value = input ('Enter an integer (Q to quit): ')
if value. Upper () == 'Q':
break
numbers. Append(value)
print ('The printed list would be:', numbers)

To convert the list to a NumPy array, you can use the 'NumPy. Array ()' function. You can specify the data type as 'int' to ensure the array contains integers:

import NumPy as np.
array = np.array(numbers, dtype=int)
print ('The printed Nd array array would be:', array)

To find and print a subset of the array based on given indexes, you can use array indexing. Here's an example:

start index = int(input('Enter the starting index: '))
end index = int(input('Enter the ending index: '))
subset = array [start index: end_index+1]
print ('The printed subset would be:', subset)
User AJ Venturella
by
8.7k points