954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Binary calculations

0
By Tony Veijalainen on Sep 10th, 2011 4:05 am

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

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()))

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.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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()))
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: