Sort Mixed Tokens
Programming Interview
Hard
4 views
Problem Description
You get {x}. Token types: INT, FLOAT (with dot), WORD. Sort by type order INT then FLOAT then WORD. For ints sort by numeric value, for floats sort by numeric value, for words sort lexicographically. Output sorted tokens in one line.
Input Format
First line n. Second line n tokens.
Output Format
One line sorted tokens.
Sample Test Case
Input:
7
10 2.5 apple -1 3.0 bat 2
Output:
-1 2 10 2.5 3.0 apple bat
Official Solution
import sys,re
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0])
a=p[1:1+n]
items=[]
for s in a:
if re.fullmatch(r'[+-]?\\d+',s):
items.append((0,int(s),s))
elif re.fullmatch(r'[+-]?(?:\\d+\\.\\d*|\\d*\\.\\d+)',s):
items.append((1,float(s),s))
else:
items.append((2,s,s))
items.sort(key=lambda x:(x[0],x[1]))
sys.stdout.write(' '.join([x[2] for x in items]))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!