Skip to content

Instantly share code, notes, and snippets.

@tecoholic
Created May 29, 2015 04:22
Show Gist options
  • Save tecoholic/410eefc6ba851c035b36 to your computer and use it in GitHub Desktop.
Save tecoholic/410eefc6ba851c035b36 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
#-------------------------------------------------------------------------------
# File: wordint_sort.py
# Author: Arunomzhi P
# Date: Fri 29 May 2015
# Email: [email protected]
# Description: Sort a given line consisting of string and integer while retaining
# the position of string and integer.
# Usage: python wordint_sort.py
#--------------------------------------------------------------------------------
def sort_this(instring):
parts = instring.split()
# extract words and numbers
words = []
numbers = []
for part in parts:
# try converting the parts to number if not add it to word list
try:
numbers.append(int(part))
except ValueError:
words.append(part)
# sort them seperately
numbers = sorted(numbers)
words = sorted(words)
# now replace each occurance of word with a word & number with a number
for i,part in enumerate(parts):
try:
int(part)
parts[i] = str(numbers.pop(0))
except ValueError:
parts[i] = words.pop(0)
# now print the sorted list as a single line
print " ".join(parts)
if __name__ == '__main__':
userinput = str(raw_input("Enter your string:\n"))
sort_this(userinput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment