+ 1
How ro check a longest wors in a file
file handling
5 Réponses
+ 5
with open("file.txt", "w") as f:
f.write("Hello World Helo Wrld")
def f1(words):
return max(words, key=len)
def f2(words):
m = len(max(words, key=len))
return [i for i in words if len(i)==m]
with open("file.txt") as f:
words = f.read().split()
print(f1(words))
print(f2(words))
+ 4
If you have a file, remove first "with" and replace second with
f = open( filename )
words = f.read().split()
print(f1(words))
print(f2(words))
f.close()
+ 4
f1 finds max item in iterable using len function for comparing
f2 finds length of longest word and returns a list containing items with same length
you can read more about key here (second part)
https://docs.python.org/3/howto/sorting.html
0
can you please give me a simple program without using with function
0
def f1(words):
return max(words, key=len)
def f2(words):
m = len(max(words, key=len))
return [i for i in words if len(i)==m]
can you please explain this part alone