File26. Дан файл вещественных чисел. Поменять в нем местами минимальный и максимальный элементы.
Решение на Python 3:
# -*- coding: utf-8 -*-
import random
import string
import os
import sys
def GenerateReals(fname):
N = random.randint(2,15)
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)
file1 = "file26.txt"
GenerateReals(file1)
print("Read from:",file1)
try:
#file for temporary data
N = random.randrange(5,8)
S = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase \
+ string.digits) for _ in range(N))
temp_file = "temp_" + S + ".txt"
#print()
print("Temp file:",temp_file)
with open(file1, 'r') as f_in, open(temp_file, 'w') as f_out:
line = f_in.readline()
x = float(line.strip())
mx = x
mn = x
mx_line = 1
mn_line = 1
line_num = 1
s = str(x)+'\n'
f_out.write(s)
for line in f_in:
line_num += 1
x = float(line.strip())
if mx < x:
mx = x
mx_line = line_num
elif mn > x:
mn = x
mn_line = line_num
s = str(x)+'\n'
f_out.write(s)
print("Min: %1.1f : %2d" % (mn,mn_line))
print("Max: %1.1f : %2d" % (mx,mx_line))
swap1_value = mx
swap1_line = mn_line
swap2_value = mn
swap2_line = mx_line
print("Swap1: %1.1f : %2d" % (swap1_value,swap1_line))
print("Swap2: %1.1f : %2d" % (swap2_value,swap2_line))
#sys.exit()
with open(file1, 'w') as f_out, open(temp_file, 'r') as f_in:
line_num = 0
for line in f_in:
line_num += 1
if line_num == swap1_line:
f_out.write(str(swap1_value)+'\n')
elif line_num == swap2_line:
f_out.write(str(swap2_value)+'\n')
else:
f_out.write(line)
print(line,end="")
try:
os.remove(temp_file)
except OSError as e:
print("\nError:", e)
except IOError:
print('Open error: ',file1)