Skip to content

Instantly share code, notes, and snippets.

BBischof/expandIt.py

Created March 22, 2016 19:05
Show Gist options
• Save BBischof/83609ea1bcab94f6c97e to your computer and use it in GitHub Desktop.
A solution to a codefights daily puzzle that was amusing and might be useful to reference
This file contains 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
 # You are given a string s composed of letters and numbers, which was compressed with some algorithm. Every letter in s is followed by a number (possibly with leading zeros), which represents the number of times this letter occurs consecutively. For example, "aaaaaaaabbbbbbcc" would be given as "a8b6c2". # Decompress s, sort its letters and return the kth (1-based) letter of the obtained string. # Note: each letter occurs in s no more than 251 times. # Example # Expand_It("a2b3c2a1", 2) = "a" # The decompressed s equals "aabbbcca", and once sorted it becomes "aaabbbcc". Its second 1-based letter is 'a', which is the answer. import itertools def Expand_It(s, k): if k <= 0: return -1 fixed_list = [(key, sum(int(r[1]) for r in rows)) for key, rows in itertools.groupby(sorted([(x,y) for x, y in pairwise(re.findall('[a-zA-Z]+|\\d+', s.strip(" ")))], key=lambda t: t[0]), key=lambda t: t[0])] if k <= sum(k for j,k in fixed_list): for pair in fixed_list: if k <= pair[1]: return pair[0] else: k -= pair[1] else: return -1
to join this conversation on GitHub. Already have an account? Sign in to comment