File18. Файли ададҳои ҳақиқӣ дода шудааст. Якумин минимуми локалии он ёфта шавад.
Минимуми локалӣ гуфта элементеро, ки аз ҳамсояҳояш хурд аст, меноманд.
Ҳал дар 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 = "file18_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
if x1 < x2:
l_min = x1
flag = True
break
elif i == 3:
x3 = x
if x1 >= x2 and x2 < x3:
l_min = x2
flag = True
break
else:
x1 = x2
x2 = x3
x3 = x
if x1 >= x2 and x2 < x3:
l_min = x2
flag = True
break
except IOError:
print('Open error: ',f_source)
if not flag:
if i == 1:
l_min = x1
else:
l_min = x
print("First local minimum:",l_min)