File20. Дан файл вещественных чисел. Найти общее количество его локальных экстремумов, то есть локальных минимумов и локальных максимумов (определения локального минимума и локального максимума даны в заданиях File18 и 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 = "file20_input.txt"
#GenerateLine(f_input)
unique_num = 0
extr_num = 2
try:
with open(f_input,'r') as f_in:
for line in f_in:
x = int(line.strip())
print(x)
if unique_num > 0 and x == x_prev:
#print(" : skipped")
continue
x_prev = x
unique_num += 1
if unique_num == 1:
x1 = x
elif unique_num == 2:
x2 = x
elif unique_num == 3:
x3 = x
#print("hello: {0},{1},{2}".format(x1,x2,x3))
if (x1 < x2 and x2 > x3) or (x1 > x2 and x2 < x3):
extr_num += 1
else:
x1 = x2
x2 = x3
x3 = x
if (x1 < x2 and x2 > x3) or (x1 > x2 and x2 < x3):
extr_num += 1
#print(":",extr_num,":",unique_num)
except IOError:
print('Open error: ',f_source)
print("unique_num: ",unique_num)
if unique_num == 1:
extr_num = 1
elif unique_num == 2:
extr_num = 2
print("Number of local extremums:",extr_num)