Created
May 29, 2015 04:22
-
-
Save tecoholic/410eefc6ba851c035b36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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