Skip to content

Instantly share code, notes, and snippets.

@anbnyc
Created March 21, 2017 21:36
Show Gist options
  • Save anbnyc/7d6ac5a6662b1a2acda370cee9d0b1db to your computer and use it in GitHub Desktop.
Save anbnyc/7d6ac5a6662b1a2acda370cee9d0b1db to your computer and use it in GitHub Desktop.
Code Dojo (Hackerrank melodious passwords) solution
#!/bin/python3
import sys
import itertools
import functools
n = int(input().strip())
letters = [
[x for x in "aeiou"],
[x for x in "bcdfghjklmnpqrstvwxz"]
]
def memoize(f):
memo = {}
def helper(x,y):
if (x,y) not in memo:
memo[(x,y)] = f(x,y)
return memo[(x,y)]
return helper
def pwords(n,start_w_cons):
if n == 1:
return letters[start_w_cons]
prod = itertools.product(letters[start_w_cons], pwords(n-1, not start_w_cons))
return prod
def unnest(tup):
if(isinstance(tup, str)):
return tup
else:
return tup[0] + unnest(tup[1])
pwords = memoize(pwords)
all_pwords = list(pwords(n,True)) + list(pwords(n,False))
for i in all_pwords:
print(unnest(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment