In: Computer Science
Create a new Python program (you choose the filename) that contains a main function and another function named change_list. Refer to the SAMPLE OUTPUT after reading the following requirements.
In the main function:
In the change_list function:
Back in the main function:
SAMPLE OUTPUT
Here is the list of random integers...
99 66 57 81 75 59 58 74 56 90 75 65
The 4th element in the list is 81
The element at index 9 is 90
The smallest element in the list is 56
The size of the list is now 6
change_list returned this sorted list...
56 58 59 74 75 81
'''
Python version : 2.7
Python program to create a main function and another function named change_list.
'''
import random
'''
function change_list that takes as input a list and returns another list consisting of middle
6 elements and sorts them i ascending order and retruns it
'''
def change_list(in_list):
new_list = []
# check if length of input is list <=6, then copy the entire list to new_list
if len(in_list) <= 6:
new_list = in_list
else: # copy the middle 6 elements from in_list to new_list
idx = (len(in_list)-6)//2
new_list = in_list[idx:idx+6]
# print the size of the list
print('The size of the list is now '+str(len(new_list)))
# sort the new_list
new_list.sort()
# return the new_list
return new_list
# main function
def main():
# create an empty list
in_list = []
# randomly add 12 elements between [50,100]
for i in range(12):
in_list.append(random.randint(50,100))
# print the list of elements
print('Here is the list of random integers...')
for i in range(len(in_list)):
print(str(in_list[i])+ ' '),
# print the 4th element
print('\nThe 4th element in the list is '+str(in_list[3]))
# print the element at index 9
print('The element at index 9 is '+str(in_list[9]))
# print the smallest element of the list using min function
print('The smallest element in the list is '+str(min(in_list)))
# get the new_list returned by calling change_list function
new_list = change_list(in_list)
# display the new_list
print('change_list returned this sorted list...')
for i in range(len(new_list)):
print(str(new_list[i])+ ' '),
#call teh main function
main()
#end of program
Code Screenshot:
Output: