Given question from Hackerrank:
- a password consists of exactly
n
lowercase English letters. - the password is melodious, meaning that consonants can only be next to
vowels and vowels can only be next to consonants. Example:
bawahaha
- the password cannot contain the letter
y
(because it's both a consonant and vowel). - the first letter of the password can be either a vowel or consonant.
###Given the length, n
, of the password,
print all of the possible passwords that meet the conditions above.
##Input Format
The line of input contains the integer (the length of the password).
###Constraints
##Output Format
Print each of the possible passwords, one per line. The order of the passwords does not matter.
My Code in Python:
import sys
import itertools
n = int(raw_input().strip())
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
test4 = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z', 'a', 'e', 'i', 'o', 'u']
answer = set(itertools.product(test4, repeat=n))
for letters in answer:
for j in xrange(len(letters)):
flag = 1
if j != len(letters) - 1:
if letters[j] in vowels and letters[j+1] in vowels:
flag = 0
break
if letters[j] in consonants and letters[j+1] in consonants:
flag = 0
break
if flag:
for j in letters:
sys.stdout.write(j)
print ""
##Can this code be optimized in any way?