Advertisement
gauravssnl

longest_word.py

Feb 24th, 2017
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. # longest_word.py by gauravssnl
  2. # find longest word in a sentence
  3.  
  4. def longest_word( sentence ) :
  5.     # words are separated by white space ,so get words_list by using split function where white space is delimiter
  6.     words_list = sentence.split( " "  )
  7.    
  8.     # initially set result as first word in words_list
  9.     res = words_list.pop(0)
  10.     # now check other words and set result res to longer word
  11.     for word in words_list :
  12.         if len( word ) > len( res ) :
  13.             res = word
  14.        
  15.         # change words_list to start from next index
  16.         words_list = words_list[ 1 : ]
  17.        
  18.     return res        
  19.  
  20. if __name__ == '__main__' :
  21.         print( longest_word( "She is Angela" ) )
  22.         print( longest_word( "Python is amazing" ) )
  23.         print ( longest_word( "A" ) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement