\$\begingroup\$
\$\endgroup\$
0
The aim is to have any strings with integers within to be reorder by these integers.
Let's say you have the following string:
re5 Forty1 cash2 Man3 Booker4
The aim is to have the string order by the integer contained within the string:
Forty1 cash2 Man3 Booker4 re5
I created this function:
def reorder(wordchain):
from re import findall
splitchain = wordchain.split()
entier = findall('\d+',wordchain)
chaineok = [(a,b) for a,b in zip(entier,splitchain)]
chaineok.sort(reverse = False)
chaineok1 = [b[1] for b in chaineok]
chaineok2 = " ".join(chaineok1)
return chaineok2
The function is fine, however, there are a few things I would like to improve:
- The number of variable; I would like to have less. What should I do?
- The number of lines; I feel there can be fewer lines and definitely fewer operations.
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 6, 2016 at 18:58
1 Answer 1
\$\begingroup\$
\$\endgroup\$
7
You should use sorted()
for sorting and give your function and variables better names.
Something like this:
import re
find_int = re.compile('(\d+)')
def reorder(sentence):
def num_part(word):
return int(find_int.search(word).group(0))
return ' '.join(sorted(sentence.split(), key=num_part))
janos
113k15 gold badges154 silver badges396 bronze badges
-
3\$\begingroup\$ This answer does not provide any explanation. Why is your solution better than the OPs' ? Why did you choose to do it like this and not like OP did ? \$\endgroup\$Grajdeanu Alex– Grajdeanu Alex2016年11月06日 19:16:28 +00:00Commented Nov 6, 2016 at 19:16
-
\$\begingroup\$ Hi @user3637203, I'm not familiar with Lambda. Can you explain a bit,please? \$\endgroup\$Andy K– Andy K2016年11月06日 19:16:31 +00:00Commented Nov 6, 2016 at 19:16
-
\$\begingroup\$ @Dex'ter seems fine to me. He pointed out
sorted()
, and that names can be improved, and demonstrated how. He made other, unexplained improvements, but that doesn't make it a bad answer. \$\endgroup\$janos– janos2016年11月06日 19:19:14 +00:00Commented Nov 6, 2016 at 19:19 -
\$\begingroup\$ @janos I didn't say it's a bad answer but it lacks some explanations which would help the OP understand what he actually did there ^_^. \$\endgroup\$Grajdeanu Alex– Grajdeanu Alex2016年11月06日 19:20:49 +00:00Commented Nov 6, 2016 at 19:20
-
4\$\begingroup\$ I made a few changes: assigning a lambda to a variable is not recommended, using a
def
is better, and probably OP understands this better too. The original function returned a string, so I added ajoin
. I also further improved the variables a bit. Hope you don't mind, feel free to change it. \$\endgroup\$janos– janos2016年11月06日 19:34:04 +00:00Commented Nov 6, 2016 at 19:34
lang-py