In: Computer Science
Python
DESCRIPTION
Write a program that will read an array of integers from a file and do the following:
●
Task 1: Revert the array in N/2 complexity time
(i.e., number of steps)
.
●
Task 2: Find the maximum and minimum element of the array.
INPUT OUTPUT
Read the array of integers from a file named “
inputHW1.txt
”. To do this, you can use code snippet
from the “
file.py
” file. This file is provided in
Canvas. Copy the “
read
” function from this file and
paste it to your program file. Then, if you call the read function like the following:
numbers = read()
# The following "read" function reads values from a file named "inputHW1.txt" and
returns the values in an array.
def read():
file = open("inputHW1.txt", "r")
line = file.readline()
values = []
for value in line.split(' '):
values.append(int(value))
return values
the integers will be read from file and loaded in the numbers array.
Now, print the reverted arra
y, minimum element and maximum element of the array.
For example, if the input array is: 1 4 9 11 8 3 2 5 10
the following will be printed on the screen:
Reverted array: 10 5 2 3 8 11 9 4 1
Maximum element: 11
Minimum element: 1
def read():
file = open("inputHW1.txt", "r")
line = file.readline()
values = []
for value in line.split(' '):
values.append(int(value))
return values
numbers = read()
#task 1, reverting the array
n = len(numbers)
mid = int(n/2)
#swap ith number with (n-1-i)th number
for i in range(mid):
numbers[i], numbers[n-1-i] = numbers[n-1-i],
numbers[i]
#task 2, finding maximum and minimum
maximum = numbers[0]
minimum = numbers[0]
for i in range(n):
maximum = max(maximum, numbers[i])
minimum = min(minimum, numbers[i])
print("Reverted array:", end=" ")
for i in range(n):
if(i<n-1):
print(numbers[i], end=" ")
else:
print(numbers[i])
print("Maximum element:", maximum)
print("Minimum element:", minimum)