Skip to content

Instantly share code, notes, and snippets.

@binhngoc17
Created December 13, 2014 09:37
Show Gist options
  • Save binhngoc17/ea6711df6e8c9ed4b67d to your computer and use it in GitHub Desktop.
Save binhngoc17/ea6711df6e8c9ed4b67d to your computer and use it in GitHub Desktop.
Example of using memorization
memo_array = {}
def stringReductionHelper(a):
if len(a) == 1:
memo_array[1] = (a, 1)
return memo_array[1]
if memo_array.get(len(a[:-1])):
prevChar, prevNum = memo_array.get(len(a[:-1]))
else:
prevChar, prevNum = stringReductionHelper(a[:-1])
if prevChar == a[-1]:
memo_array[len(a)] = (a[-1], prevNum + 1)
return memo_array[len(a)]
else:
if prevNum % 2 == 1:
samples = set(['a', 'b', 'c'])
samples.discard(prevChar)
samples.discard(a[-1])
memo_array[len(a)] = (list(samples)[0], 1)
return memo_array[len(a)]
else:
memo_array[len(a)] = a[-1], 1
return memo_array[len(a)]
#!/usr/bin/py
# Head ends here
def stringReduction(a):
answer = 0
char, num = stringReductionHelper(a)
return num
# Tail starts here
if __name__ == '__main__':
t = input()
for i in range(0,t):
a=raw_input()
print stringReduction(a)
memo_array = {} # Reset memo array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment