+ 1

How ro check a longest wors in a file

file handling

29th Oct 2018, 1:38 PM
abinaya
abinaya - avatar
5 Respostas
+ 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))
29th Oct 2018, 1:43 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 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()
29th Oct 2018, 1:54 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 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
29th Oct 2018, 2:09 PM
Mert Yazıcı
Mert Yazıcı - avatar
0
can you please give me a simple program without using with function
29th Oct 2018, 1:48 PM
abinaya
abinaya - avatar
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
29th Oct 2018, 1:58 PM
abinaya
abinaya - avatar