(1)Write a program in Python that reads an arbitrary-length file. All lines that
ID: 3595111 • Letter: #
Question
(1)Write a program in Python that reads an arbitrary-length file.
All lines that start with semicolons (;) or pound signs (#) should be ignored.
All empty lines must be ignored
Lines containing a string between square brackets are sections.
Within each section, lines may contain numbers or strings.
For each section, calculate the lowest, highest and modal (most common) number, and print it. In each section, also count all non-whitespace characters, and print that.
Example input:
Your program must print the following output
Explanation / Answer
def is_int(s):
try:
float(s)
return True
except ValueError:
return False
import re
a = open("input.txt","r")
b = a.readlines()
for i in b:
if(i[0] == ";" or i[0] == "#" or i[0] == " "):
b.remove(i)
trimmedListIndices = []
for i in range(len(b)):
if(b[i][0] == "["):
trimmedListIndices.append(i)
trimmedListIndices.append(len(b))
for i in range(len(trimmedListIndices)-1):
extractedArray = b[trimmedListIndices[i]:trimmedListIndices[i+1]]
s = str(extractedArray[0])
val = s.split('[', 1)[1].split(']')[0]
for j in range(1,len(extractedArray),1):
high = 0
low = 0
length = 0
int_arr = []
if(is_int(extractedArray[j])):
int_arr.append(extractedArray[j])
else:
length += len(extractedArray[i])
print("%s: lowest=%d, highest=%d,characters=%d",%(val, min(int_arr),max(int_arr),length))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.