Python Interview Questions

Infra/SRE focuse

Dictionary File Problem

circle-exclamation
circle-info
  1. Implement a function exists that indicates whether an argument passed in is part of the dictionary.

circle-check
dict_binary_search.py
def get_word_at_pos(dict_file, pos):
    word = ''
    while pos > 0 and dict_file.read(1) != ' ':
        pos -= 1
        dict_file.seek(pos)
    cur = dict_file.read(1)
    while cur != ' ':
        word += cur
        cur = dict_file.read(1)
    return word, pos


def search(word, dict_file, begin, end):
    if begin == end:
        return False
    else:
        mid = (end+begin) / 2
        current_word, pos = get_word_at_pos(dict_file, mid)
        if word == current_word:
            return True
        else:
            mid = pos
            if word > current_word:
                next_begin = mid+len(current_word)+1
                if begin == next_begin:
                    return False
                else:
                    return search(word, dict_file, next_begin, end)
            else:
                next_end = mid
                if next_end == end:
                    return False
                else:
                    return search(word, dict_file, begin, mid)


def exists(word, filename):
    with open(filename, 'r') as dict_file:
        dict_file.seek(0, 2)
        begin = 0
        end = dict_file.tell()-1
        return search(word, dict_file, begin, end)

circle-info

2. If you could modify the format of this file to support more efficientlookups, what would you change about the file format?

circle-check
circle-info

3. Compound words are words that are composed of other words. Using the exists() function you implemented earlier, implement a function that indicates whether a word is a compound word.

Example solution:

Last updated