Skip to content

Instantly share code, notes, and snippets.

@mattmusc
Last active December 12, 2020 16:04
Show Gist options
  • Select an option

  • Save mattmusc/36e72bb41b2afb58e260b750b3ded939 to your computer and use it in GitHub Desktop.

Select an option

Save mattmusc/36e72bb41b2afb58e260b750b3ded939 to your computer and use it in GitHub Desktop.
Google Coding Interview
#!/usr/bin/env python3
# Google Former Coding Interview
# https://techdevguide.withgoogle.com/resources/former-coding-interview-question-word-squares/
from itertools import product
import re
import sys
def has_word_square(words_list):
# each j-th character in the i-th word
# must match the i-th character in the j-th word
for i, word in enumerate(words_list):
for j, char in enumerate(word):
j_word_char = words_list[j][i]
if j_word_char != char:
return False
return True
def has_any_word_square(words_list):
# words must have the same lengths
all_words_have_same_length = all(map(lambda l: l == len(words_list[0]), map(len, words_list)))
if not all_words_have_same_length:
return False
total_lists = 0
for perm in product(words_list, repeat=len(words_list[0])):
total_lists += 1
if has_word_square(perm):
return True
print('I have created and analyzed', total_lists, 'words list')
return False
def find_word_squares(words_list):
total_lists = 0
word_squares = []
for perm in product(words_list, repeat=len(words_list[0])):
total_lists += 1
if has_word_square(perm):
word_squares.append(tuple(perm))
print('I have created and analyzed', total_lists, 'words list')
return word_squares
def read_words(iterable, spaces_regex):
return [re.sub(spaces_regex, ' ', line.strip()) for line in iterable]
if __name__ == '__main__':
words = []
if len(sys.argv) > 1 and sys.argv[1] == '-i':
spaces_regex = re.compile('( ?)+')
words = read_words(sys.stdin.readlines(), spaces_regex)
else:
words = ['AREA', 'BALL', 'DEAR', 'LADY', 'LEAD', 'YARD']
if len(words) == 0:
sys.exit(1)
squares = find_word_squares(words)
print(squares)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment