Binary calculations

TrustyTony

Very trivial program which could be thought as conclusion from the Quiz posts (thanks Gribouillis for inspiration for format)

153 Views
About the Author

IT Pro doing Eng-Fin-Eng translations

from __future__ import print_function
try:
    input = raw_input
except:
    pass

from operator import iadd, imul, idiv, imod, isub

oper = dict(zip('+*/%-', (iadd, imul, idiv, imod, isub)))

def get_bin(prompt='Bin value'):
    while True:
        try:
            return int(input('%s: ' % prompt),2)
        except ValueError:
            print('Please  enter string of 0 or 1 digits')

def get_op(prompt='Give operator'):
    while True:
        try:
            op = input('%s (%s): ' % (prompt, ''.join(oper.keys()))).strip()
            assert op in oper
            return op
        except AssertionError:
            print('You must give one of the operators!')

if __name__ == '__main__':
    first = get_bin('Give first binary number')
    second = get_bin('Give second binary number')
    op = get_op()

    result = oper[op](first,second)
    
    fl = max(len(bin(b)) for b in (first, second, result))
    sl = fl - 2
    sep = '-' * fl
    print('''
    {first:>{fl}b}
    {op} {second:>{sl}b}
    {sep}
    {result:>{fl}b}
    '''.format(**locals()))
Gribouillis 1,391 Programming Explorer Team Colleague

Interesting, however the get_op() method won't work if python is run in optimized mode (python -O) because this mode removes assert statements. Assert statements should not influence the program's flow of control, except for debugging purposes.

TrustyTony 888 pyMod Team Colleague Featured Poster

Thanks, so then better to change to traditional if.. return there, also Python3 has not idiv(nor div), so I changed it to floordiv:

from __future__ import print_function
try:
    input = raw_input
except:
    pass

from operator import iadd, imul, floordiv, imod, isub

oper = dict(zip('+*/%-', (iadd, imul, floordiv, imod, isub)))

def get_bin(prompt='Bin value'):
    " input binary value with prompt (': ' added for you) "
    while True:
        try:
            return int(input('%s: ' % prompt),2)
        except ValueError:
            print('Please  enter string of 0 or 1 digits')

def get_op(prompt='Give operator'):
    """ input binary operator, which is in global oper dictionary
        (': ' added for you as is the list of valid operators)

    """
    while True:
        op = input('%s (%s): ' % (prompt, ''.join(oper.keys()))).strip()
        if op in oper:
            return op
        else:
            print('You must give one of the operators!')

if __name__ == '__main__':
    first = get_bin('Give first binary number')
    second = get_bin('Give second binary number')
    op = get_op()

    result = oper[op](first,second)
    
    fl = max(len(bin(b)) for b in (first, second, result))
    # get space for operator sign in second line
    sl = fl - 2
    sep = '-' * fl
    print('''
    {first:>{fl}b}
    {op} {second:>{sl}b}
    {sep}
    {result:>{fl}b}
    '''.format(**locals()))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.