0
How to get the longest word from a list or string.
#I tried up to getting length of each word.. txt=input() print("your input is--"+txt) def words(txt): return (txt.split()) #print(words(txt)) wordss=words(txt) print(wordss) def lenth(): for line in wordss: if "\n" in line: print(line+" -- " +str(len(line)-1)) else: print(line+" -- " +str(len(line))) lenth() #print(max(str(line))) """ It prints ==> your input is--how to get the longest word from the list or a sentence ['how', 'to', 'get', 'the', 'longest', 'word', 'from', 'the', 'list', 'or', 'a', 'sentence'] how -- 3 to -- 2 get -- 3 the -- 3 longest -- 7 word -- 4 from -- 4 the -- 3 list -- 4 or -- 2 a -- 1 sentence -- 8 """
5 odpowiedzi
+ 8
If you want to print them in order from longest to shortest, you could do this.
words = sorted(input().split(), key=len, reverse=True)
for word in words:
print(word, "len =", len(word))
+ 3
If you just want to get the longest word (without representations)
Just print that string.
If this is a challenge (maybe not), you dont need representations, you can just print the string right away.
https://code.sololearn.com/cQ95W1GB02Dg/?ref=app
+ 2
max here is not a function, it is a variable that holds the string that has greatest value temporarily.
It is iterating each string, if a string length is greater than the previous ones then that will be the new "max" value.
This is what it looks like using max function:
print(max(input().split(), key=len))
+ 1
Dude how we do it with out max function
+ 1
Ok i didn't even look my bad
Tnx