Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Longest Word Python
    Hi guys, So I am trying to get through the "LongestWord" challenge, but keep getting Syntax Error because there is no module named string Please let me know what is wrong with my code and if possible, please do share other easier way of doing this, thanks guys. Here is my code:
    def LongestWord(sen): 
      # code goes here
      import string
      for char in string.punctuation:
        sen = sen.replace(char,' ')
      text = sen.split()
      text.sort(key = lambda x: len(x))
      return text[-1]
    
    # keep this function call here  
    # to see how to enter arguments in Python scroll down
    print LongestWord(raw_input()) 
    
    kplau posted this question on 1/24/14 | python
    Answers
  • +
  • 3
  • -
  • Hi, the issue is that your trying to access a module that doesn't exist in the environment provided. This a library tht comes with the python ide (e.g. python 3.3). However, it is not avaiblable here. If you download the latest python ide and then try your code. It will work fine, since the library comes with the ide. As for your algorithm: I like how you try to take account of all possible punctuation marks, but I think the only case you really need to worry about is " ". If you change your algorithm to only worry about that case. You should be fine.
  • +
  • 1
  • -
  • Having Import Statment in Function is Not Correct Thing to Do
    import string
    def longest_words(l):
    #...
    
  • +
  • 1
  • -
  • @smk1992 Non alphanumeric characters will make your words longer, and there are actually several tests in the challenge which include them. As smk also said, you can't import modules, otherwise it might be comfortable to import re to get rid of these chars using regular expressions:
    def longest_word2(sen):
        sen = re.sub('[^A-Za-z0-9 ]', ' ', sen)
        return max(sen.split(), key=len)
    
    But since you can't, my approach was kinda similar to kplau's:
    def longest_word(sen):
        for char in sen:
            if not char.isalnum():
                sen = sen.replace(char, ' ')
        return max(sen.split(), key=len)
    
  • +
  • 1
  • -
  • >>> s
    'my name is mehta'
    >>> a=s.split()
    >>> a
    ['my', 'name', 'is', 'mehta']
    >>> print max(a,key=len)
    mehta
    >>> print min(a,key=len)
    my
    >>>
    
  • +
  • 0
  • -
  • import re, string
    regex = re.compile('[%s]' % re.escape(string.punctuation))
    
    def LongestWord(sen): 
    
        return sorted(regex.sub('', sen).split(),key = len).pop()
    
    # keep this function call here  
    print LongestWord(input())
    
  • +
  • 0
  • -
  • This works in PyCharm, but for some reason, doesn't work here:
    def LongestWord(sen):
    
        table = str.maketrans(",[email protected]#:;'\/][$%^&*()_+=-?", 24*" ")
        sen = str(sen.translate(table))
        sen = sen.split()
        max_len = []
        for x in sen:
            max_len.append(len(x))
    
        sen = max(max_len)
    
        return sen
    
    
    print(LongestWord(input()))
  • +
  • 0
  • -
  • You can import modules now
    import re
    def LongestWord(sen): 
        return sorted(re.findall(r"w+",sen), key= lambda x: -len(x))[0]
    
  • +
  • 0
  • -
  • >>> str = 'Hi my name is sam'
    >>> print sorted(list( map(lambda x: (len(x),x)  , str.split(' ') ) ) )[-1][-1]
    name
    
  • +
  • 0
  • -
  • How about this To display code include the following tags:
    def longest_words(l):
        import string
        l = l.translate(str.maketrans("", "", string.punctuation))
        l = l.split(' ')
        length = [len(i) for i in l]
    
        d = {}
        for n, i in enumerate(length):
            if i in d:
                if l[n] in d[i]:
                    pass
                else:
                    d[i].append(l[n])
            else:
                d[i] = [l[n]]
        return ",".join(d[max(d)])
    
    print (longest_words ("Argume!!nt go!!es !!here"))
    Log in to write an answer.