File22. Дан файл вещественных чисел. Создать файл целых чисел, содержащий номера всех локальных экстремумов исходного файла в порядке убывания (определение локального экстремума дано в задании File20).

Решение на Python 3:

import random

def GenerateNumbers(fname):
N = random.randint(1,15)
print("N = ",N)
L = []
x = random.randrange(1,10)
L.append(x)
for i in range(1,N):
lst_rnd = list(range(1,10))
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 = "file22_input.txt"
GenerateNumbers(f_input)

f_output = "file22_output.txt"
EmptyFile(f_output)

i = 0
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
print("Local extremum:",x1,"; Extremum line:",1)
Write2File(f_output,1)
elif i == 2:
x2 = x
elif i == 3:
x3 = x
if (x1 < x2 and x2 > x3) or (x1 > x2 and x2 < x3):
print("Local extremum:",x2,"; Extremum line:",i-1)
Write2File(f_output,i)
else:
x1 = x2
x2 = x3
x3 = x
#print(x1,x2,x3)
if (x1 < x2 and x2 > x3) or (x1 > x2 and x2 < x3):
print("Local extremum:",x2,"; Extremum line:",i-1)
Write2File(f_output,i)

except IOError:
print('Open error: ',f_source)

if i == 2:
print("Local extremum:",x2,"; Extremum line:",2)
Write2File(f_output,2)
elif i >= 3:
print("Local extremum:",x3,"; Extremum line:",i)
Write2File(f_output,i)