Skip to content

Instantly share code, notes, and snippets.

@nirlanka
Created August 7, 2019 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirlanka/bb362a792ddf92bb8ec813e21f01ceba to your computer and use it in GitHub Desktop.
Save nirlanka/bb362a792ddf92bb8ec813e21f01ceba to your computer and use it in GitHub Desktop.
Answer to Hackerrank challenge "Password Cracker", which is correct, but not the expected answer in some test cases ¯\_(ツ)_/¯ (https://www.hackerrank.com/challenges/password-cracker/forum)
#!/bin/python3
DEBUG = False
import math
import os
import random
import re
import sys
#
# Complete the 'passwordCracker' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING_ARRAY passwords
# 2. STRING loginAttempt
#
def trie_traverse(trie, path):
matches = []
node = trie
pwd = ''
while path:
if node.get(path[0]) is not None:
pwd = pwd + path[0]
if len(path) == 1:
matches.append(pwd)
break
node = node[path[0]]
path = path[1:]
else:
if trie.get(path[0]) is None or not node.get('$'):
matches = None
break
else:
matches.append(pwd)
pwd = ''
node = trie
return matches
def trie_inc(node, path):
if not node.get(path[0]):
node[path[0]] = {}
if len(path) == 1:
node[path[0]]['$'] = True
if len(path) > 1:
trie_inc(node[path[0]], path[1:])
def passwordCracker(passwords, loginAttempt):
trie = {}
for pwd in passwords:
trie_inc(trie, pwd)
answers = trie_traverse(trie, list(loginAttempt))
return ' '.join(answers) if answers else 'WRONG PASSWORD'
if __name__ == '__main__':
if DEBUG:
lines = [l for l in open('in4.txt', 'r')]
t = int(lines[0])
lines = lines[1:]
i = 0
while i < len(lines):
n = int(lines[i])
passwords = lines[i+1].rstrip().split()
loginAttempt = lines[i+2].rstrip()
result = passwordCracker(passwords, loginAttempt)
print(result)
i = i+3
else:
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input().strip())
for t_itr in range(t):
n = int(input().strip())
passwords = input().rstrip().split()
loginAttempt = input()
result = passwordCracker(passwords, loginAttempt)
fptr.write(result + '\n')
fptr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment