File28. Дан файл вещественных чисел. Заменить в файле каждый элемент, кроме начального и конечного, на его среднее арифметическое с предыдущим и последующим элементом.
Решение на Python 3:
# -*- coding: utf-8 -*-
import random
def GenerateReals(fname):
#generate random real numbers and save them to file
N = random.randint(2,15)
#N = 9
print("N = ",N)
L = []
x = round(random.uniform(0, 10),1)
L.append(x)
for i in range(1,N):
lst_rnd = [round(random.uniform(0, 10),1) for _ in range(0,10)]
try:
lst_rnd.remove(x)
except:
pass
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)
f_input = "file28_in.txt"
f_output = "file28_out.txt"
GenerateReals(f_input)
print("Read from:",f_input)
print("Write to:",f_output)
try:
with open(f_input, 'r') as f_in, open(f_output, 'w') as f_out:
line = f_in.readline()
x1 = float(line.strip())
f_out.write(line)
line = f_in.readline()
x2 = float(line.strip())
for line in f_in:
x = float(line.strip())
x_avg = (x1 + x2 + x) / 3
s_avg = str(x_avg)+"\n"
f_out.write(s_avg)
x1 = x2
x2 = x
f_out.write(line)
except IOError:
print('Open error: ',file1)