Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Created July 9, 2017 03:34
Show Gist options
  • Save onelharrison/34c12272cc5f7f6105ce76257c16c489 to your computer and use it in GitHub Desktop.
Save onelharrison/34c12272cc5f7f6105ce76257c16c489 to your computer and use it in GitHub Desktop.
Your order, please
"""
# Your order, please
#
# Sort a given string. Each word in the String will contain a single number. This number is the position the
# word should have in the result.
#
# Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
#
# If the input String is empty, return an empty String. The words in the input String will only contain valid
# consecutive numbers.
#
# For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"
"""
def find_number(word):
index = 0
if word[index].isdigit():
return int(word[index])
return find_number(word[index + 1: ])
def order(sentence):
return " ".join(sorted(sentence.split(), key=find_number))
@onelharrison
Copy link
Author

onelharrison commented Jul 9, 2017

I've since found this more elegant version of the solution to this problem that I think captures the same concepts I tried to put into practice.

  • solution as a function of a series of transformations
  • avoid iteration
  • avoid mutations and side effects
def order(sentence):
  return ' '.join(sorted(sentence.split(), key=lambda w: int(filter(str.isdigit, w))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment