python file exercises

【Problem Description】

Read the scores of any number of students from a text file, find the highest score, the lowest score and the average score and store them in the file result.txt.

【Input form】

A file with scores separated by newlines. The input file name is grade.txt. The fractions entered are all integers.

[Output form]

Calculate the highest score, lowest score and average score of all scores in grade.txt and store them in 3 lines in the file result.txt. The average score is rounded to 1 decimal place.

[Sample input]

60

70

80

[Sample output]

80

60

70.0

[Sample description]

The output of 70 is the average score.

【Grading】

with open("grade.txt", 'r') as f:
    ls = []
    for s in f:
        s = s.strip("\n")
        ls.append(int(s))
    o = open("result.txt", "w")
    o.writelines (str(max(ls)))
    o.write('\r\n')
    o.writelines(str(min(ls)))
    o.write('\r\n')
    o.writelines (str(round(sum(ls)/len(ls),1)))
    o.close()
    

【Problem Description】

Write a program to implement: input the integer n from the keyboard. Read n lines from the file "text.txt", and print the lines starting with the letter A to the standard output (here refers to the screen).
[Input form]

从键盘输入整数n;
文件输入的第1至n行的每一行构成一个字符串。

[Output form]

标准输出的每一行是字母A开头的行。若未找到符合条件的字符串,则输出"not found";若输入数据不合法(指n为小数或负数)则输出"illegal input"。

[Sample input]

  键盘输入:      5

  文件输入:
        hello world
        An apple
        hello C++
        A man
        a program

[Sample output]

        An apple
        A man
n=eval(input())
if n<=0:
    print("illegal input")
elif not (n*10)%10 == 0:
    print("illegal input")
else:
    flag=False
    f=open("text.txt", 'r') 
    for i in range(int(n)):
        p=f.readline()
        pre=p[0]
        if pre=='A':
            print(p)
            flag=True
    if flag==False:
        print("not found")

【Problem Description】

Read data from the in.txt file, for each line of the file:

Find the maximum and minimum values ​​of each number (may be an integer or a floating point number) in the row,

Write the maximum and minimum values ​​to the file out.txt as one line, with the maximum value first and two spaces between the two numbers.

30 30 0 30 20 10 395 92

35 35 0 50 20 20 430 100

35 35 0 50 20 20 430 100

35 35 1.2 50 20 20 365 85

32.5 32.5 0 47.5 20 0 381.33333 89

[Sample output]

395 0

430 0

430 0

365 1.2

381.33333 0

[Sample description]

The value output must be exactly the same as the value input. For example, if the input content is 381.33333, the output content must also be 381.33333, and cannot be output as 381.33.

f=open("in.txt", 'r')
o=open("out.txt", "w")
for i in f:
    ls=list(i.split(" ")[:-1])
    ls=list(map(eval,ls))
    m=max(ls)
    o.write(str(str(max(ls))+" "+str(min(ls))))
    o.write('\r\n')

Guess you like

Origin blog.csdn.net/X131644/article/details/127728735