Skip to content

Instantly share code, notes, and snippets.

@AdrienHorgnies
Last active April 23, 2020 18:51
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 AdrienHorgnies/74afff130a65039ba9c45bbc15cde4fc to your computer and use it in GitHub Desktop.
Save AdrienHorgnies/74afff130a65039ba9c45bbc15cde4fc to your computer and use it in GitHub Desktop.
Interviews programming questions
def check(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
#!/usr/bin/env python3
import argparse
def check(strings, shuffle):
if len(''.join(strings)) != len(shuffle):
return False
# a scenario consists of a list of index which corresponds to each string plus the shuffle string
# each index refers to the last assigned char of the corresponding string
first_scenario = (-1,) * (len(strings) + 1)
scenarios = [first_scenario]
while scenarios:
scenario = scenarios.pop()
next_char_idx_in_shuffle = scenario[-1] + 1
if next_char_idx_in_shuffle >= len(shuffle):
return True
for string_idx in range(len(strings)):
char_idx_in_string = scenario[string_idx] + 1
string = strings[string_idx]
if char_idx_in_string < len(string) and string[char_idx_in_string] == shuffle[next_char_idx_in_shuffle]:
new_strings_idx = scenario[:string_idx] + (char_idx_in_string,) + scenario[string_idx + 1:-1]
new_scenario = new_strings_idx + (next_char_idx_in_shuffle,)
scenarios.append(new_scenario)
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser(
'Check if the third given string is a valid shuffle of the first two while preserving original order')
parser.add_argument('strings', nargs='+', metavar='string', help='A given string')
parser.add_argument('shuffle', help='The shuffle candidate')
args = parser.parse_args()
print(args)
print(check(args.strings, args.shuffle))
#!/usr/bin/env python3
def count(string):
return sum(1 for char in string if char in 'aeuioAEUIO')
#!/usr/bin/env python3
import argparse
from collections import defaultdict
def duplicates(string):
char_count = defaultdict(int)
for char in string:
char_count[char] += 1
return ''.join([char for char, count in char_count.items() if count > 1])
if __name__ == '__main__':
parser = argparse.ArgumentParser('Print duplicate characters in given string')
parser.add_argument('string', help='A string to detect duplicate characters within')
args = parser.parse_args()
print(duplicates(args.string))
#!/usr/bin/env python3
import argparse
from collections import defaultdict
def find(string):
char_count = defaultdict(int)
for char in string:
char_count[char] += 1
for char, count in char_count.items():
if count == 1:
return char
if __name__ == '__main__':
parser = argparse.ArgumentParser('Print the first unique character in a given string')
parser.add_argument('string', help='The given string')
args = parser.parse_args()
print(find(args.string))
#!/usr/bin/env python3
from math import factorial
from collections import defaultdict
import argparse
def find(string):
possibilities = [(string, '')]
permutations = []
while possibilities:
stock, permu = possibilities.pop()
if not stock:
permutations.append(permu)
for char in set(stock):
shorter_stock = stock.replace(char, '', 1)
longer_permu = permu + char
possibilities.append((shorter_stock, longer_permu))
return permutations
# Not required, did to check answer
def count_chars(string):
char_count = defaultdict(int)
for char in string:
char_count[char] += 1
return char_count
# Not required, did to check answer
def count_permutations(string):
char_count = count_chars(string)
prod = factorial(len(string))
for count in count_chars(string).values():
prod //= factorial(count)
return prod
if __name__ == '__main__':
parser = argparse.ArgumentParser('Print all permutations of a given string')
parser.add_argument('string', help='The given string')
args = parser.parse_args()
permutations = find(args.string)
for permutation in permutations:
print(permutation)
count = count_permutations(args.string)
assert len(permutations) == len(set(permutations))
assert len(permutations) == count
print('There are {} different permutations of the word "{}"'.format(count, args.string))
#!/usr/bin/env python3
import argparse
from numpy import prod
def product_except_index(array):
if array.count(0) > 1:
return [0] * len(array)
elif array.count(0) == 1:
product = prod([n for n in array if n != 0])
return [0 if n != 0 else product for n in array]
else:
product = prod(array)
return [product // n for n in array]
assert product_except_index([1, 3, 2, 3]) == [18, 6, 9, 6]
assert product_except_index([1, 0, 2, 3]) == [0, 6, 0, 0]
assert product_except_index([1, 0, 2, 0]) == [0, 0, 0, 0]
assert product_except_index([2]) == [1]
if __name__ == '__main__':
parser = argparse.ArgumentParser('For each given number, print the product of the other numbers')
parser.add_argument('numbers', nargs='+', metavar='number', help='A given number', type=int)
args = parser.parse_args()
print(product_except_index(args.numbers))
#!/usr/bin/env python3
def reverse_iteration(string):
reversed_string = ''
for char in string:
reversed_string = char + reversed_string
return reversed_string
def reverse_recursion(string):
def reverse_acc(string_in, string_out):
if string_in:
return reverse_acc(string_in[:-1], string_out + string_in[-1])
else:
return string_out
return reverse_acc(string, '')
import pytest
from check_anagrams import check
def test_no_input():
with pytest.raises(TypeError):
check()
def test_one_input():
with pytest.raises(TypeError):
check('abcde')
def test_one_blank():
assert not check('', 'coucou')
def test_two_blanks():
assert check('', '')
def test_one_letter_anagram():
assert check('a', 'a')
def test_nominal_anagrams():
assert check('arc', 'car')
def test_different_case_anagrams():
assert check('Arc', 'Car')
def test_nominal_no_anagrams():
assert not check('arc', 'orc')
from check_shuffle import check
def test_check_blanks():
assert check([''], '')
assert check(['', ''], '')
assert check(['a', ''], 'a')
assert check(['', 'a'], 'a')
assert not check(['', 'alqkdhsg'], '')
def test_check_nominal():
assert check(['a', 'ab'], 'aba')
assert check(['ba', 'a'], 'aba')
assert check(['ba', 'a'], 'aba')
assert check(['abc', 'def'], 'defabc')
assert check(['abc', 'def'], 'daebfc')
assert check(['abc', 'def'], 'abdecf')
assert not check(['abc', 'def'], 'abedcf')
assert not check(['abc', 'def'], 'bdecfa')
#!/usr/bin/env python3
from count_vowels import count
def test_count_blank():
assert count('') == 0
def test_nominal():
assert count('Java') == 2
def test_case():
assert count('JAVA') == 2
def test_special_chars():
assert count('°908743"&é"') == 0
def test_special_chars_w_vowels():
assert count('°90i8743ee"&é"') == 3
import pytest
from duplicate_chars import duplicates
def test_empty():
with pytest.raises(TypeError):
duplicates()
def test_blank():
assert duplicates('') == ''
def test_single():
assert duplicates('Java') == 'a'
def test_several():
assert duplicates('Les chaussetes') == 'es'
def test_no_duplicates():
assert duplicates('Adrien') == ''
from reverse_string import reverse_iteration, reverse_recursion
def test_iter_blank():
assert reverse_iteration('') == ''
def test_rec_blank():
assert reverse_recursion('') == ''
def test_iter_nominal():
assert reverse_iteration('Adrien') == 'neirdA'
def test_rec_nominal():
assert reverse_recursion('Adrien') == 'neirdA'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment