+ 2
Given a text as input. Find and output the longest word.
I do not know why (continue) is not working. And is there a short way to solve this code. txt = input() a = txt.split() word = "" c=0 while c < len(a): b = 0 while b < len(a): if len(a[c]) >= len(a[b]): word = a[c] else: word = a[b] #continue is not working, why??? b=len(a) # i used this line instead of continue. b+=1 c+=1 print(word)
8 ответов
+ 6
# Solved
txt = input()
result=txt.split(" ")
num=max(result,key=len)
print(num)
+ 1
x="i love python !"
lst=[len(i) for i in x.split()]
print(x.split()[lst.index(max(lst))])
'''
input : I love python!
output : python
'''
0
Continue does not work, because it only stops the current Iteration. You want is to break out of the inner while loop, which is done by keyword "break".
Some more things:
In the inner loop You could Set b = c+1.
When you have reached the end of the list in the inner loop, you should break out of the outer loop.
Below Code should be working as expected:
c=0
while c < len(a):
b = c+1
while b < len(a):
if len(a[c]) >= len(a[b]):
word = a[c]
else:
word = a[b]
#continue is not working, why???
#b=len(a) # i used this line instead of continue.
break
b+=1
if b == len(a):
break
c+=1
print(word)
0
thanks a lot for help me. But can you please explain why you added the last code...
if b == len(a):
break
0
Aurora just try to comment it out and See what happens ;)
I'll try to explain:
For example the words given are:
"a bb ccc dd e"
1. c = 0, b = 1; len("a") >= len("bb") --> word = "bb"
2. c = 1, b = 2;len("bb") >= len("ccc") --> word = "ccc"
3. c = 2, b = 3;len("ccc") >= len("dd") --> word = "ccc"
4. c = 2, b = 4;len("ccc") >= len("e") --> word = "ccc"
(my code would now break the outer loop with the result word = "ccc". Without this break it would go on:)
5. c = 3, b = 4;len("dd") >= len("e") --> word = "dd"
6. c = 4, b = 5; (inner loop will not be entered)
(Without breaking the outer loop the result would be word = "dd", which is wrong.)
Hope you understand...
0
txt = input()
result=txt.split(" ")
max=" "
for i in result:
if len(i)>len(max):
max=i
print(max)
0
txt = input()
result=txt.split(" ")
num=max(result,key=len)
print(num)
0
txt = input()
list_words = txt.split()
max_len=0
longest_word=""
for word in list_words:
if len(word)>max_len:
max_len = len(word)
longest_word = word
print(longest_word)