In: Computer Science
Python Question:
Write a function that checks to see if an array of integers is sorted in an increasing fashion, returning true if it is, false otherwise. Test it with at least4 arrays - 2 sorted and 2 not sorted. Use a CSV formatted input file as described in the previous question to run your program through some tests, where again the filename is passed as an argument.
Heres what I have so far:
import sys
# command line arguement 1. a csv file that contained rows of numbers to be tested.
file_name = sys.argv[1]
file = open(file_name)
# function that will check the csv file and see if the rows of numbers are sorted in an increasing pattern.
def is_sorted(arr):
_result = []
for i in range(len(arr) - 1):
if current_arr[i] > current_arr[i+1]:
return False
return True
# Read the file line by line
for line in file.readlines():
# For each line read,
# We create a new array to:
# Store the number we convert from strings,
current_arr = []
# Split the current line by commas,
for number in line.split(','):
# then convert each string in an array to an integer and
# then add it to the current array of numbers
current_arr += [int(number)]
when I order numbers in my csv file not sorted, I still get True returned instead of False
found_index = is_sorted(current_arr)
print(found_index)
I tried with the given code. It gives me the expected results.Make sure your indentation is proper. Attaching the updated properly indented code below:
CSV Data:
1,0,5,6
10,13,14,15
2,4,5,6
9,1,2,2
Python Code:
import sys
# command line arguement 1. a csv file that contained rows of numbers to be tested.
#file_name = sys.argv[1]
file = open('sample.csv')
# function that will check the csv file and see if the rows of numbers are sorted in an increasing pattern.
def is_sorted(arr):
for i in range(len(arr) - 1):
if current_arr[i] > current_arr[i+1]:
return False
return True
# Read the file line by line
for line in file.readlines():
# For each line read,
# We create a new array to:
# Store the number we convert from strings,
current_arr = []
# Split the current line by commas,
for number in line.split(','):
# then convert each string in an array to an integer and
# then add it to the current array of numbers
current_arr += [int(number)]
found_index = is_sorted(current_arr)
print(found_index)
Output:
False
True
True
False
Please take a look and let me know if you have any other specific format/number you are trying in csv which is not working. I will debug and check any other changes to be made.