+ 1

Why does this code not work only in one of the test cases?

In the coding challenge "Longest Word" I made this code: txt = input() list = [] word_list = txt.split(" ") for word in word_list: list.append(word.index(word[-1])) print(word_list[list.index(max(list))]) Can someone tell me why this didn't work in only the second test case?

13th Aug 2021, 11:14 AM
Andreas Kav
8 ответов
+ 6
You say index of s and gives you first s it finds which is at index 3 So your program thinks its 4 letter word
13th Aug 2021, 11:43 AM
Abs Sh
Abs Sh - avatar
+ 4
a simple and pythonic way of getting the longest word of a string can be done like this: inp = input().split() print(max(inp, key = len)) # 'key = len' together with max() returns the longest word
13th Aug 2021, 2:26 PM
Lothar
Lothar - avatar
+ 3
Expected output: perspiciatis (12 characters) My output: accusantium (11 characters) This is from python core.
13th Aug 2021, 11:35 AM
Andreas Kav
+ 3
Thats because perspiciatis have two s you don't get the last index work with length.
13th Aug 2021, 11:40 AM
Abs Sh
Abs Sh - avatar
+ 2
Oh, I get it. Thanks.
13th Aug 2021, 11:46 AM
Andreas Kav
+ 2
You could append len(word) to your list instead of trying to deal with .index() (And just an advice: avoid naming lists "list" – it might overwrite the build-in list())
13th Aug 2021, 11:51 AM
Lisa
Lisa - avatar
+ 2
Right, I'll keep that in mind from now on. Thank you!
13th Aug 2021, 11:53 AM
Andreas Kav
+ 1
What did you get as output for the 2nd test case? Which Python course is it?
13th Aug 2021, 11:30 AM
Lisa
Lisa - avatar