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.
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
|
Python has built-in functions and syntax for this. Any number starting with
0b
is assumed to be binary, and the built-inbin
function converts numbers to their binary representationsAlso, 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)
callbinary_helper(value, [])
.Recursion isn't necessary for this problem, though - the translation is pretty straightforward:
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.
Standard Python offers these features:
4 Daniel Lepage: you forgot specify your python's version number.
On Python 2.4.5 your example failed:
Thank you Denis for pointing out the python's version to Daniel Lepage
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.
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!!!.
A switch to C# and a new link
http://archive.msdn.microsoft.com/fouadteniou