1

I have to solve some Python regex tasks in one line of code. An example of such a task would be this one: print (one of) the longest word in a text. Here is how I did it:

import re
print(sorted([(word, len(word)) for word in list(filter(None, re.split("[\s.?!,:;]", input())))], 
key=lambda x: x[1], reverse=True)[0][0])

Now comes my question: can I somehow put the import part in the print so that everything is in one line? I mean, I don't know if I am allowed to have the import part on a separate line or if I can somehow put it inside my print, this is why I am asking you if this can be made "more one line".

EDIT: I will provide a sample input and output as requested:

INPUT: John is tall. 
OUTPUT: John (it would also be all right if it printed "tall", I just want one of the longest words)
Alexdanut
  • 111
  • 6
  • 1
    are you only restricted to regex? I think there might be better ways to get around this solution. it would also be nice to show an example of the text – Ade_1 May 31 '21 at 17:29
  • @Ade_1 Yes, I am restricted to regex. I don't know if an example is really useful, the code itself does the job, I am mostly interested in whether I can get the import in the print line, but I will add one. – Alexdanut May 31 '21 at 17:33
  • @Ade_1 I have added the example, I think I know which part was a bit unclear, I hope I cleared it up now. – Alexdanut May 31 '21 at 17:36
  • Is the 'one line' strictly related to Python syntax? Or you want plain text to have only one line? You can use `;` after importing the module to use only one line. That is interpreted as two lines, for Python, but the file itself can have only one line. – MatBBastos May 31 '21 at 17:47
  • @MatBBastos Yes, it is restricted to Python sintax. – Alexdanut May 31 '21 at 17:48
  • 1
    Well, I believe there is no way for you to import and print using only one line without making use of `;` to separate the `import` statement from the `print` function – MatBBastos May 31 '21 at 18:29
  • 1
    But this will grant you a one line file: `import re; print(sorted([(word, len(word)) for word in list(filter(None, re.split(r"[\s.?!,:;]", input())))], key=lambda x: x[1], reverse=True)[0][0])` – MatBBastos May 31 '21 at 18:30
  • There may be ways to use the [Python import system](https://docs.python.org/3/reference/import.html) for achieving that, but it would be very hacky. – Lenormju Jun 01 '21 at 15:08

0 Answers0