0
def LongestWord(sen): 

  # first we remove non alphanumeric characters from the string
  # using the translate function which deletes the specified characters
  sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")

  # now we separate the string into a list of words
  arr = sen.split(" ")
  print(arr)
  # the list max function will return the element in arr
  # with the longest length because we specify key=len
  return max(arr, key=len)

**print LongestWord("Argument goes here")**

what's wrong with this line? How can I change it? I can't understand it! It make me really uneasy, cause in Coderbyte.com says that it is true and it work!

Jimmy Hoho
  • 37
  • 4

2 Answers2

1

I'm not exactly sure what line you're referring too? Perhaps the last line.

If so you need a parenthesis with the print statement in python 3.x

print(LongestWord("Argument goes here"))

additionally, string translate works differently in python 3

def LongestWord(sen): 

  # first we remove non alphanumeric characters from the string
  # using the translate function which deletes the specified characters
  intab ="~!@#$%^&*()-_+={}[]:;'<>?/,.|`"
  trantab= str.maketrans(dict.fromkeys(intab))

  sen = sen.translate(trantab)

  # now we separate the string into a list of words
  arr = sen.split(" ")
  print(arr)
  # the list max function will return the element in arr

  # with the longest length because we specify key=len
  return max(arr, key=len)

print(LongestWord("Argument. 'Go' @goes here"))

The above worked for me on python 3.6.2

Nick Dima
  • 340
  • 1
  • 8
1

It is working properly but instead of return try

print max(arr, key=len)

as if you called the function directly without print keyword preceding it won't show the max or you can return both arr, max in single line and print the function output so it would look like this:

def LongestWord(sen):
    sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
    arr = sen.split(" ")
    print(arr)
    print max(arr, key=len)


LongestWord("Argument goes here ! @")

NOTE : it worked in Python 2.7

IF YOU WOULD LIKE TO USE PYTHON 3.7 use the following

to_remove = sen.maketrans("", "", "~!@#$%^&*()-_+={}[]:;'<>?/,.|`")
sen = sen.translate(to_remove)
Mina Samy
  • 86
  • 1
  • 5
  • It doesn't work. Error starts on line 5 of your code. If I put brackets it give me like this:Traceback (most recent call last): File "/root/.PyCharmCE2018.2/config/scratches/scratch_1.py", line 8, in LongestWord("Argument goes here ! @") File "/root/.PyCharmCE2018.2/config/scratches/scratch_1.py", line 2, in LongestWord sen = sen.translate(None, "~!@#$%^&*()-_+={}[]:;'<>?/,.|`") TypeError: translate() takes exactly one argument (2 given) – Jimmy Hoho Sep 05 '18 at 19:12
  • Make sure you are using python version 2.7 or you can make it like this of you want to use version higher than 3.5 to_remove = sen.maketrans("", "", "~!@#$%^&*()-_+={}[]:;'<>?/,.|`") sen = sen.translate(to_remove) – Mina Samy Sep 08 '18 at 00:07