File21. Дан файл вещественных чисел. Создать файл целых чисел, содержащий номера всех локальных максимумов исходного файла в порядке возрастания (определение локального максимума дано в задании File19).
Решение на Python 3:
import random
def GenerateNumbers(fname):
N = random.randint(1,11)
print("N = ",N)
L = []
x = random.randint(1,4)
L.append(x)
for i in range(1,N):
lst_rnd = list(range(1,5))
lst_rnd.remove(x)
x = random.choice(lst_rnd)
L.append(x)
print(L)
try:
f = open(fname, "w")
try:
for x in L:
line = str(x)+"\n"
f.write(line)
finally:
f.close()
except IOError:
print('Write error: ',fname)
def EmptyFile(fname):
open(fname, 'w').close()
def Write2File(fname,value):
try:
f = open(fname, "a")
try:
s = str(value)+'\n'
f.write(s)
finally:
f.close()
except IOError:
print('Write error: ',fname)
f_input = "file21_input.txt"
#GenerateNumbers(f_input)
f_output = "file21_output.txt"
EmptyFile(f_output)
i = 0
flag = False
try:
with open(f_input,'r') as f_in:
for line in f_in:
i += 1
x = int(line.strip())
print(x)
if i == 1:
x1 = x
l_max = x1
l_max_line = 1
elif i == 2:
x2 = x
if x1 > x2:
print("Local maximum:",l_max,"; Max line:",l_max_line)
Write2File(f_output,l_max_line)
else:
l_max = x2
l_max_line = 2
elif i == 3:
x3 = x
if x3 > x2:
l_max = x3
l_max_line = 3
elif x1 < x2 and x2 > x3:
l_max = x2
print("Local maximum:",l_max,"; Max line:",l_max_line)
Write2File(f_output,l_max_line)
else:
x1 = x2
x2 = x3
x3 = x
if x3 > x2:
l_max = x3
l_max_line = i
elif x1 < x2 and x2 > x3:
print("Local maximum:",l_max,"; Max line:",l_max_line)
Write2File(f_output,l_max_line)
except IOError:
print('Open error: ',f_source)
if i == 1:
print("Local maximum:",l_max,"; Max line:",l_max_line)
Write2File(f_output,l_max_line)
elif i == 2:
if x1 < x2:
print("Local maximum:",l_max,"; Max line:",l_max_line)
Write2File(f_output,l_max_line)
else:
if x2 < x3:
print("Local maximum:",l_max,"; Max line:",l_max_line)
Write2File(f_output,l_max_line)