I'm having trouble trying to add these together correctly. I have kind of ran into a brick wall. I have gotten it converted and that's it as of now.
My Code: - class BinaryNumber:
-
'''A Binary Number Class'''
-
#pass
-
def __init__(self, bitString = ''):
-
'''Constructor'''
-
#pass
-
self._bits = bitString
-
-
def __str__(self):
-
'''string representation'''
-
if self._bits:
-
return self._bits
-
else:
-
return '0'
-
-
def __int__(self):
-
'''conversion'''
-
#pass
-
total = 0
-
for pos in range(len(self._bits)):
-
if self._bits[pos] == '1':
-
total += 2 ** (len(self._bits) - 1 - pos)
-
return total
-
-
def __add__(self, other):
-
'''addition: implementation of the + operator'''
-
pass
-
I am not allowed to import math either.
Any help would be much appreciated! :]
14 13447 bvdet 2,851
Recognized Expert Moderator Specialist
All you need is a conversion of a decimal integer to binary. Then your magic method __add__ would be: - def __add__(self, other):
-
'''addition: implementation of the + operator'''
-
return self.dec2bin((int(self)+int(other)))
Have you tried to write code for it?
I have tried a similar code that used "import math" and tried changing it to get it to work, but it didn't.
This is all of my code as of right now for my project: -
# Program: ex6_18.py
-
# Authors: Robert Mineweaser
-
#
-
# This example is discussed in Chapter 6 of the book
-
# Object-Oriented Programming in Python
-
#
-
-
class BinaryNumber:
-
'''A Binary Number Class'''
-
#pass
-
def __init__(self, bitString = ''):
-
'''Constructor'''
-
#pass
-
self._bits = bitString
-
-
def __str__(self):
-
'''string representation'''
-
if self._bits:
-
return self._bits
-
else:
-
return '0'
-
-
def __int__(self):
-
'''conversion'''
-
#pass
-
total = 0
-
for pos in range(len(self._bits)):
-
if self._bits[pos] == '1':
-
total += 2 ** (len(self._bits) - 1 - pos)
-
return total
-
-
def __add__(self, other):
-
'''addition: implementation of the + operator'''
-
#pass
-
'''carry = 0
-
result = ''
-
-
# Work from right to left.
-
for i in range(0, len(self._bits))[::-1]:
-
tmp = int(((a[i]) + int(b[i]) + carry)/2)
-
res = str(int(a[i]) + int(b[i]) + carry - 2 * tmp)
-
result += res
-
carry = tmp
-
-
result = (result + str(carry))[::-1]
-
try:
-
return result[result.index('1'):]
-
except ValueError, ex:
-
return '0'
-
'''
-
return self.dec2bin((int(self)+int(other)))
-
-
def __subtract__(self, other):
-
'''subtraction: implementation of the - operator''' # Optional
-
pass
-
-
def __lt__(self, other):
-
'''less: implementation of the < operator'''
-
#pass
-
if int(a) <= int(b):
-
return True
-
else:
-
return False
-
-
def __gt__(self, other):
-
'''great: implementation of the > operator'''
-
#pass
-
if int(a) >= int(b):
-
return True
-
else:
-
return False
-
-
def __eq__(self, other):
-
'''equal: implementation of the = operator'''
-
#pass
-
if int(a) == int(b):
-
return True
-
else:
-
return False
-
-
-
if __name__ == '__main__':
-
a = BinaryNumber('01111001') # binary numbers must start with 0
-
b = BinaryNumber('00110101') # a = 121, b = 53
-
print 'a = ', a, int(a)
-
print 'b = ', b, int(b)
-
-
print 'a + b', a + b, int(a + b)
-
#print 'a - b', a - b, int(a - b) # optional
-
-
print 'a < b', a < b
-
print 'a > b', a > b
-
print 'a == b', a == b
-
-
print 'Press the Enter key to finish'
-
-
raw_input()
-
If you couldn't tell, subtraction is optional and I commented the code i tried to change to get to work. Any advice on what I could do to fix this.
bvdet 2,851
Recognized Expert Moderator Specialist
Function dec2bin() would be a class method. Check out this thread.
Alright. After it is added together, I need my output to show as " a + b (binary result) (decimal result). How would I make it add them together and have it show that as the result of the two?
bvdet 2,851
Recognized Expert Moderator Specialist
Modify the string returned by __add__ and use string formatting. Untested: - return "%s + %s (%s) (%s)" % (self, other, self.dec2bin((int(self)+int(other))), (int(self)+int(other)))
I am still a little confused. All I need to do is add 2 binary numbers together and have the output be " a + b (binary result) (decimal result) ". The conversion was to just give me the decimal result. So how would I go about adding this all together to get the given output, " a + b (binary result) (decimal result) " ? If you don't understand what I am trying to ask please feel free to tell me.
This was my original code for " __add__" without any additions from me: -
class BinaryNumber:
-
'''A Binary Number Class'''
-
#pass
-
def __init__(self, bitString = ''):
-
'''Constructor'''
-
#pass
-
self._bits = bitString
-
-
def __str__(self):
-
'''string representation'''
-
if self._bits:
-
return self._bits
-
else:
-
return '0'
-
-
def __int__(self):
-
'''conversion'''
-
#pass
-
total = 0
-
for pos in range(len(self._bits)):
-
if self._bits[pos] == '1':
-
total += 2 ** (len(self._bits) - 1 - pos)
-
return total
-
-
def __add__(self, other):
-
'''addition: implementation of the + operator'''
-
pass
-
-
def __subtract__(self, other):
-
'''subtraction: implementation of the - operator''' # Optional
-
pass
-
-
def __lt__(self, other):
-
'''less: implementation of the < operator'''
-
#pass
-
if int(a) <= int(b):
-
return True
-
else:
-
return False
-
-
def __gt__(self, other):
-
'''great: implementation of the > operator'''
-
#pass
-
if int(a) >= int(b):
-
return True
-
else:
-
return False
-
-
def __eq__(self, other):
-
'''equal: implementation of the = operator'''
-
#pass
-
if int(a) == int(b):
-
return True
-
else:
-
return False
-
-
if __name__ == '__main__':
-
a = BinaryNumber('01111001') # binary numbers must start with 0
-
b = BinaryNumber('00110101') # a = 121, b = 53
-
print 'a = ', a, int(a)
-
print 'b = ', b, int(b)
-
-
print 'a + b', a + b, int(a + b)
-
#print 'a - b', a - b, int(a - b) # optional
-
-
print 'a < b', a < b
-
print 'a > b', a > b
-
print 'a == b', a == b
-
-
print 'Press the Enter key to finish'
-
-
raw_input()
-
bvdet 2,851
Recognized Expert Moderator Specialist
See my first post in this thread.
Yes, but even when I put that in, I get an error, "AttributeError: BinaryNumber instance has no attribute 'dec2bin'". How exactly would I have to make this code to look to get it to add the binary numbers together correctly and have it give me the output, "a + b (binary result) (decimal result)" ?
bvdet 2,851
Recognized Expert Moderator Specialist
You must add a BinaryNumber method dec2bin(). The method must return the decimal number converted to binary.
Is this the only way to do it? Or is there another way possible? If not, how would I go about doing this?
bvdet 2,851
Recognized Expert Moderator Specialist
That is the way I would do it, because that's the easiest for me. There are other ways though. You can write the code to do binary addition and subtraction in methods __add__() and __sub__() respectively. Check out this website.
I understand the concepts of binary addition, but I just have trouble putting it into code. How would I write the code for binary addition in the method __add__?
bvdet 2,851
Recognized Expert Moderator Specialist
I am sorry, but I cannot write the code for you. Please show some effort on your own, then we can help. Since you understand the concepts of binary addition, you may know more than me about it.
Even if you do the binary addition, I think the code should go into a separate function.
Glenton 391
Recognized Expert Contributor
Hi
It seems to me that, since you're implementing your own version of this, you might as well do the addition in binary. Your bitString is just a string of 1s and 0s, if I'm not mistaken?
So, I would first implement something that returns a single digit in a given position.
Something like: - def binDigit[self,position]:
-
if position>len(self._bits):
-
return 0
-
else:
-
return self._bits[-position]
if self._bits="101", then position[1] = 1, position[2]=0, position[3]=1 and position[4]=0 etc.
Now create something that does the addition bit by bit (literally!): - def __add__[self,other]:
-
v=max([len(self._bits),len(other._bits)])+1
-
ans=''
-
carry=0
-
for i in range(1,v+1):
-
a=self.position(i)
-
b=self.position(i)
-
t=carry+int(a)+int(b)
-
if t<=1:
-
carry=0
-
else:
-
carry=1
-
if t%2==0:
-
ans='0'+ans
-
else:
-
ans='1'+ans
-
return BinaryNumber(ans)
-
I haven't checked any of this, but it should give you some idea.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Scott Chapman |
last post by:
There seems to be an inconsistency here:
Python 2.3.2 (#1, Oct 3 2003, 19:04:58)
on linux2
>>> 1 == True
True
>>> 3 == True
False
>>> if 1: print "true"
....
|
by: Jimmy Johns |
last post by:
Hi, why hasn't there a version of pyOpenGL for python 2.3.x yet? Currently
the binary installers for windows only work with python 2.2, and will give
an when installing for python 2.3. I can't...
|
by: Shawn Milo |
last post by:
Is anyone doing this? I would like to access a DB2 database (IBM's database)
with Python. I checked "Python in a Nutshell," and it refers to
ftp://people.linuxkorea.co.kr/pub/db2, but I am unable...
|
by: devendra_k |
last post by:
I want to intigrate the PyGame module with my Python exe,
means i DONT want to generate .PYD files separtely rather than that
want to put PyGame "c" src with Python workspace of VC project...
|
by: christopher diggins |
last post by:
Welcome to the first installment of the Diggins Public Domain Posts (PDP).
There is a significant dearth of good public domain C++ code. All of it
seems to come with one kind of a license or...
| |
by: Michael Tobis |
last post by:
Someone asked me to write a brief essay regarding the value-add
proposition for Python in the Fortran community. Slightly modified to
remove a few climatology-related specifics, here it is.
I...
|
by: edcdave |
last post by:
My (gcc 2.95.2) build of Python 2.4.3 is failing with:
gcc -Wl,-Bexport -o python \
Modules/ccpython.o \
libpython2.4.a -lnsl -ldl -lm
Undefined first referenced...
|
by: citronelu |
last post by:
Is it possible to execute a binary string stored within a python script
as executable code ?
The script is run under Windows, and the binary code (a full executable
file) is stored in a variable...
|
by: 7stud |
last post by:
Hi,
I'm using an intel imac which came with python 2.3.5 pre-intstalled on
OS 10.4.7. I was able run a hello world wxPython script in Terminal
by typing:
$pythonw wxPythonTest.py
...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...
| |