1

I have a text file and I need to count the number of characters per line and then print the minimum, maximum value and range. Example (txt file):

lzaNDDRipfohkALungYAipuOhbWIpkmsSqvXkjRYNxCADTUKzS
aQLi
DwhhJfvUd

The output should be:

  • Min: 4 characters
  • Max: 50 characters
  • Range: 46 characters

and NULL if the file is empty.

Hagbard
  • 3,430
  • 5
  • 28
  • 64
ny123
  • 31
  • 5

1 Answers1

3

You can use the built-in min() and max() methods, using the built-in len() method as the keys:

with open("file.txt", "r") as f:
    lines = f.read().splitlines()

mi = len(min(lines, key=len))
ma = len(max(lines, key=len))
ra = ma - mi

print(f"Min: {mi} Max: {ma} Range: {ra}")

Output:

Min: 4 Max: 50 Range: 46
Red
  • 26,798
  • 7
  • 36
  • 58