Source

codeeval_challenges / 050_StringSubstitution / string_substitution.py

Full commit
#! /usr/bin/env python

import sys
from optparse import OptionParser

def print_binary(number):
    if number == 0:
        return str(0)

    binary = []
    while number > 0:
        binary.append(
            str(number & 1)
        )
        number = number >> 1

    return ''.join(reversed(binary))

def string_to_binary(string):
    binary = 0
    for count, digit in enumerate(string):
        binary = binary | int(digit)
        if count < len(string)-1:
            binary = binary << 1
    return binary

def main():

    parser = OptionParser('%s testcase.txt' % __file__)
    options, args = parser.parse_args()

    if len(args) < 1:
        parser.error("No input file provided. Please check help.")

    test_cases = open(sys.argv[1], 'r')

    for test in test_cases:
        test = test.strip()

        if test != '':
            string, replacements = test.split(';')
            replacements = replacements.split(',')

            binary = string_to_binary(string)

            print print_binary(string_to_binary('1101011001111'))
            print '1101011001111'

            assert(print_binary(binary) == '10011011001')

    test_cases.close()


if __name__ == "__main__":
    main()