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

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

import random

def GenerateLine(fname):
N = random.randrange(1,10)
print("N = ",N)
#N = 2
#line = "1, 5, 5, 5, 4, 4, 5"
try:
f = open(fname, "w")
try:
for i in range(N):
line = str(random.randint(1,4))+"\n"
f.write(line)
finally:
f.close()
except IOError:
print('Write error: ',fname)

f_input = "file19_input.txt"
GenerateLine(f_input)

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
elif i == 2:
x2 = x
elif i == 3:
x3 = x
if x3 >= x2:
l_max_prev = x3
elif x1 <= x2 and x2 > x3:
l_max_prev = x2
else:
l_max_prev = x1
else:
x1 = x2
x2 = x3
x3 = x
if x3 >= x2:
l_max_next = x3
elif x1 <= x2 and x2 > x3:
l_max_next = x2
else:
l_max_next = l_max_prev

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

if i == 1:
l_max = x1
elif i == 2:
if x1 > x2:
l_max = x1
else:
l_max = x2
elif i == 3:
l_max = l_max_prev
else:
l_max = l_max_next

print("Last local maximum:",l_max)