Welcome, guest | Sign In | My Account | Store | Cart

The most commonly used number system is the denary number system, a system of numbers to base 10. However, All the others numbers systems are used in the computing field. And the binary number system, a system of numbers to base 2 uses only two digits 0 and 1, and any position in a binary number system increases by powers of 2 in contrast with the decimal system, which increases by powers of 10. Though, the binary number system was invented by a Chinese poet and philosopher Shao Yong in the 11th century. Solving repetitive problems requires a powerful method and yet recursion allows the design of faster recursive algorithms. Recursion method could be used to solve higher-level mathematics problems, such as sequences and it is a branch in computer science study.

Python, 115 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#On the name of ALLAH and may the blessing and peace of Allah 
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 9/02/10
#version :2.6

"""
My program Binary_Decimal_Systems Recursion uses a Recursion method
in both binary_function and decimal_function, whether converting a
number from decimal to binary or vice versa, and in both functions it
applies mathematics' operations on the number entered by the user
until it reaches its base case value, where the function returns a
final value and the recursion stops and produce whether a binary or a
decimal number.
"""

import re

# Starting with an empty list.
binary_list = []

def binary_function(value):
    """
    It converts a decimal number into a binary number by using
    a recursion function.
    """
      
    try:
        binary_string = ''
        
        #Append binary_list 
        binary_list.append(value%2) 

        # recursion base cases 
        if value == 0 or value == 1 or value == -1:
            binary_list.reverse()
        
            for item in binary_list:
                #Append binary_string 
                binary_string += str(item)
                
            # Convert string to an int.
            return int(binary_string)
              
        else:
            if value > 0:
                return binary_function(value/2)
        
            else:
                return binary_function(-value/2)*-1
            
    #Raise TypeError if input is not numerical
    except TypeError:
        print 'Please enter an integer.'
        
def decimal_function(number):
    """
    It converts a binary number into a decimal number by using
    a re and a recursion function.
    """

    decimal_sum = 0
    #regular expression substitution
    transform = re.sub("(]?\w+)(\w{1})", '\g<1>.\g<2>',str(number))

    for arg in str(number):
        
        if  arg[0] != '-' and arg != '.' and int(arg) != 0 and int(arg)!= 1 :
            raise TypeError,\
              "\n<binary numbers should be composed of 0 and 1 digits only "
     
    try:   
        # recursion base case
        if number == transform:
            for item in xrange((len(number)-1)/2,-2,-1):
                for res in xrange(0,len(number)):
                    if transform[res].isdigit():
                        next_item = 2**item * int(transform[res])
                        item -= 1
                        decimal_sum += next_item

                return decimal_sum
        else:
            if number > 0:
                return decimal_function(transform)
        
            else:
                return decimal_function(transform)*-1
            
    #Raise TypeError if input is not a binary number          
    except TypeError,exception:
        print exception
     
if __name__ == '__main__':
    
    convert_binary = binary_function(37)
    print convert_binary
    del binary_list[:]
    convert_decimal = decimal_function(100101)
    print convert_decimal
    convert_binary1 = binary_function(-37)
    print convert_binary1
    del binary_list[:]  
    convert_decimal = decimal_function(-100101)
    print convert_decimal

##############

# FTpython "C:\Users\binary_decimal_Sys.py"
# 100101
# 37
# -100101
# -37

# FT

7 comments

Daniel Lepage 11 years, 10 months ago  # | flag

Python has built-in functions and syntax for this. Any number starting with 0b is assumed to be binary, and the built-in bin function converts numbers to their binary representations

if __name__ == '__main__':
    print bin(37)
    print 0b100101
    print bin(-37)
    print -0b100101

# 0b100101
# 37
# -0b100101
# -37

Also, using a global list to accumulate digits is terrible practice (it forces people to explicitly delete the list every time they convert a number, ruins thread-safety, and pollutes the global namespace); the correct way to do this, if you insist on using recursion, would be to write a recursive helper function that takes both the number and the list so far, and have binary_function(value) call binary_helper(value, []).

Recursion isn't necessary for this problem, though - the translation is pretty straightforward:

from math import log, floor

def asbinary(value):
    digits = []
    # Largest power of two less than value
    largest = int(floor(log(value)/log(2)))
    for i in range(largest,-1,-1):
        if value >= 2**i:
            digits.append('1')
            value -= 2**i
        else:
            digits.append('0')
    return ''.join(digits)

Also, it's very bad form to print out error messages instead of raising exceptions. The calling code (your ifmain block in this case) will generally want to catch exceptions and react to them, but specific functions will generally be better off raising exceptions so that the code calling them knows something went wrong and can react accordingly.

Eric-Olivier LE BIGOT 11 years, 10 months ago  # | flag

Standard Python offers these features:

print int('100101', 2)  # 37
print bin(37)  # '100101', in Python 2.6+
Denis Barmenkov 11 years, 10 months ago  # | flag

4 Daniel Lepage: you forgot specify your python's version number.

On Python 2.4.5 your example failed:

File "1.py", line 3
    print 0b100101
                 ^
SyntaxError: invalid syntax
Fouad Teniou (author) 11 years, 10 months ago  # | flag

Thank you Denis for pointing out the python's version to Daniel Lepage

Fouad Teniou (author) 11 years, 10 months ago  # | flag

To Daniel

Thank you for your comment.

However, I noticed that you wrote only one python program ( Rot13 Quine ) so far, and for fun, yet my Binary_Decimal Recursion program is for serious programmers.

And I wrote this program, because I assumed that programmers will prefer converting their numbers into integers, instead of strings, as it is the case for python’s conversion, and I do not find python’s 0b binary notation helpful or useful, but confusing.

Writing codes while using a recursion is very important, especially for certain types of programs, thus, the purpose of me using the recursion.

I would like to remind you that the “ if main block “ is just for testing the program, and not for writing exceptions or raising such exceptions. However, you could see clearly the way I wrote and caught during testing, some of these exceptions.

Fouad Teniou (author) 11 years, 10 months ago  # | flag

To Eric

Thank you for your comment.

Using Python’s functools module partial function allows you to perform such operations. However, the conversion’s outcome is a string and not an integer!!!.

Fouad Teniou (author) 10 years, 4 months ago  # | flag

A switch to C# and a new link

http://archive.msdn.microsoft.com/fouadteniou

Created by Fouad Teniou on Tue, 9 Feb 2010 (MIT)
Python recipes (4591)
Fouad Teniou's recipes (37)

Required Modules

Other Information and Tasks