I have overloaded the basic addition operator, adding 2 fractions, but now I'm having trouble adding a fraction with a non fraction, ie: 3/4 + 1.
Here is part of my program: -
def gcd(a, b):
-
while b:
-
a, b = b, a%b
-
return abs(a)
-
-
class Rational:
-
"""
-
function to initialize variables
-
"""
-
def __init__(self, num, den = 1):
-
assert den != 0 #make sure denominator isn't 0
-
self.n = num
-
self.d = den
-
reduced = gcd(num, den) # reduce fraction
-
self.n = num/reduced
-
self.d= den/reduced
-
"""
-
function to print answer as a string, strips trailing L on longs)
-
"""
-
def __repr__(self):
-
return '(%d/%d)' % (self.n, self.d)
-
"""
-
function to overload addition operator to add 2 fractions
-
"""
-
def __add__(self, terms):
-
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
-
-
This is the error I get:
Traceback (most recent call last):
File "C:\Python25\Rational.py", line 87, in <module>
print " a + 1:", a + 1
File "C:\Python25\Rational.py", line 38, in __add__
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
AttributeError: 'int' object has no attribute 'd'
So, I figured what I need to do is give the whole number a denominator, and that didn't work. Can anyone walk me through this?
Thank you !
TMS
12 2268
I have overloaded the basic addition operator, adding 2 fractions, but now I'm having trouble adding a fraction with a non fraction, ie: 3/4 + 1.
This is the error I get:
Traceback (most recent call last):
File "C:\Python25\Rational.py", line 87, in <module>
print " a + 1:", a + 1
File "C:\Python25\Rational.py", line 38, in __add__
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
AttributeError: 'int' object has no attribute 'd'
So, I figured what I need to do is give the whole number a denominator, and that didn't work. Can anyone walk me through this?
Thank you !
TMS
What you need to do is check the type of the argument in question and either add differently if it's not isinstance(arg, Rational) or convert it to a Rational type object before you add. The former is probably the way to go. -
def gcd(a, b):
-
while b:
-
a, b = b, a%b
-
return abs(a)
-
-
class Rational:
-
def __init__(self, num, den = 1):
-
"""
-
function to initialize variables
-
"""
-
assert den != 0 #make sure denominator isn't 0
-
self.n = num
-
self.d = den
-
reduced = gcd(num, den) # reduce fraction
-
self.n = num/reduced
-
self.d= den/reduced
-
def __repr__(self):
-
"""
-
function to print answer as a string, strips trailing L on longs)
-
"""
-
return '(%d/%d)' % (self.n, self.d)
-
def __add__(self, terms):
-
"""
-
function to overload addition operator to add 2 fractions
-
"""
-
if isinstance(terms, Rational):
-
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
-
else:
-
pass # replace with your code
Also, put the docstrings inside the def so that python's documentation features can find them.
OK, cool. I will work on that. TY
[font=Verdana][size=2]THANK you! I was working on that and couldn't figure it out. The instance thing helped because it stopped it from going back through the __init__.... Hadn't heard of the instance thing. Thanks![/size][/font]
OK, cool. I will work on that. TY
Ya know what's really cool? When you post back with working code so others can make use of the knowledge that you have gained.
kk, lol, here it is: -
def __add__(self, terms):
-
"""
-
function to overload addition operator to add 2 fractions or a fraction
-
and a whole number
-
"""
-
if isinstance(terms, Rational):
-
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
-
else:
-
terms = Rational(terms, 1)
-
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
-
works great.
I have another question regarding floats. If I pass a float, I get an error (obviously), so I tried to fix it by defining a float function: -
def __float__(self):
-
return float(self.n)
-
Silly me, thought I could get away that easy. But no, I get an error that looks like this when I try to pass Rational(1.3) with a default denominator of 1:
Traceback (most recent call last):
File "C:\Python25\Rational.py", line 106, in <module>
print " c:", c
File "C:\Python25\Rational.py", line 34, in __repr__
return '(%d/%d)' % (self.n, self.d)
TypeError: int argument required
Any hints?
I have another question regarding floats. If I pass a float, I get an error (obviously), so I tried to fix it by defining a float function: -
def __float__(self):
-
return float(self.n)
-
Silly me, thought I could get away that easy. But no, I get an error that looks like this when I try to pass Rational(1.3) with a default denominator of 1:
Traceback (most recent call last):
File "C:\Python25\Rational.py", line 106, in <module>
print " c:", c
File "C:\Python25\Rational.py", line 34, in __repr__
return '(%d/%d)' % (self.n, self.d)
TypeError: int argument required
Any hints?
The hint is in the error msg:
"return '(%d/%d)' % (self.n, self.d)
TypeError: int argument required"
To format floats you need - >>> a = 10.0
-
>>> floatStr = '%.3f' %a
-
>>> print floatStr
-
10.000
-
>>>
bvdet 2,851
Expert Mod 2GB
kk, lol, here it is: -
def __add__(self, terms):
-
"""
-
function to overload addition operator to add 2 fractions or a fraction
-
and a whole number
-
"""
-
if isinstance(terms, Rational):
-
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
-
else:
-
terms = Rational(terms, 1)
-
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
-
works great.
I have another question regarding floats. If I pass a float, I get an error (obviously), so I tried to fix it by defining a float function: -
def __float__(self):
-
return float(self.n)
-
Silly me, thought I could get away that easy. But no, I get an error that looks like this when I try to pass Rational(1.3) with a default denominator of 1:
Traceback (most recent call last):
File "C:\Python25\Rational.py", line 106, in <module>
print " c:", c
File "C:\Python25\Rational.py", line 34, in __repr__
return '(%d/%d)' % (self.n, self.d)
TypeError: int argument required
Any hints?
If you want to enable the input of floats, this will work for floats up to 4 decimal places: - def __init__(self, num, den=1):
-
if isinstance(num, float) or isinstance(den, float):
-
num, den = map(lambda x: x * 1000, [num, den])
-
num, den = map(int, [num, den])
-
-
assert den != 0
-
reduced = gcd(num, den)
-
self.n = num/reduced
-
self.d = den/reduced
-
-
>>> a = Rational(1.33, 5.13)
-
>>> print a
-
(7/27)
-
>>>
bvdet 2,851
Expert Mod 2GB
TMS,
Sometimes I create __str__ and __repr__ methods for classes. The __str__ method will execute when the instance is printed. The __repr__ method will recreate the object when passed to eval(). Your project: - >>> a = Rational(3,4)
-
>>> a
-
Rational(3, 4)
-
>>> print a
-
(3/4)
-
>>> z = repr(a)
-
>>> z
-
'Rational(3, 4)'
-
>>> z = eval(repr(a))
-
>>> z
-
Rational(3, 4)
-
>>> print z
-
(3/4)
bvdet 2,851
Expert Mod 2GB
TMS,
You can eliminate duplicate code in your __add__ method this way: - def __add__(self, other):
-
if not isinstance(other, Rational):
-
other = Rational(other)
-
return Rational(self.n * other.d + other.n * self.d, self.d * other.d)
bvdet 2,851
Expert Mod 2GB
TMS,
A couple more suggestions and I'm done.
1. If you are overloading multiple operators in your class definition, you may want to add a __coerce__ method: - def __add__(self, other):
-
other = self.__coerce__(other)
-
return Rational(self.n * other.d + other.n * self.d, self.d * other.d)
-
-
def __coerce__(self, other):
-
if isinstance(other, Rational):
-
return other
-
try:
-
return Rational(other)
-
except:
-
raise ValueError, 'Invalid operand'
2. The assert statement is mostly used for debugging. I would prefer to test for 0 like this: - if den != 0:
-
...... do stuff ......
-
else:
-
raise ValueError, 'The denominator must not be 0'
There may be better ways.
HTH :)
TMS,
A couple more suggestions and I'm done.
1. If you are overloading multiple operators in your class definition, you may want to add a __coerce__ method: - def __add__(self, other):
-
other = self.__coerce__(other)
-
return Rational(self.n * other.d + other.n * self.d, self.d * other.d)
-
-
def __coerce__(self, other):
-
if isinstance(other, Rational):
-
return other
-
try:
-
return Rational(other)
-
except:
-
raise ValueError, 'Invalid operand'
2. The assert statement is mostly used for debugging. I would prefer to test for 0 like this: - if den != 0:
-
...... do stuff ......
-
else:
-
raise ValueError, 'The denominator must not be 0'
There may be better ways.
HTH :)
Great suggestions BV. You are the man!
Honestly!! Thank you! Those are great suggestions. We are just starting the unit on Exceptions so the "Try" ... will be great because I can start practicing with it. Thank you very much!
TMS
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Mike Meyer |
last post by:
PEP: XXX
Title: A rational number module for Python
Version: $Revision: 1.4 $
Last-Modified: $Date: 2003/09/22 04:51:50 $
Author: Mike Meyer <mwm@mired.org>
Status: Draft
Type: Staqndards...
|
by: Mike Meyer |
last post by:
This version includes the input from various and sundry people. Thanks
to everyone who contributed.
<mike
PEP: XXX
Title: A rational number module for Python
Version: $Revision: 1.4 $...
|
by: Zenon |
last post by:
Folks,
I am having a terrible time overloading operators. I have tried what
I thought was the correct way, I tried the cheating (friend
declarations), all to no avail. Sorry for posting tons of...
|
by: Brian van den Broek |
last post by:
Hi all,
I guess it is more of a maths question than a programming one, but it
involves use of the decimal module, so here goes:
As a self-directed learning exercise I've been working on a...
|
by: uday |
last post by:
Does C supports overloading. I am thinking no. But some people are
saying yes. If yes how. Please answer with examples.
Also in c++ size of empty class is one. why. and what are the
default...
|
by: andrew browning |
last post by:
I am getting an istream overloading error that looks like this:
error: no match for 'operator>>' in 'ins >>
target->abrowning_rational::Rational::numerator'
Below is the .h file:
#ifndef...
|
by: penny |
last post by:
In this assignment we shall look at a possible representation of rational numbers in java using objects. The java language represents rational numbers using the same representation used for other...
|
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= |
last post by:
Operator overloads are just like any other member function, you
can make them do whatever you want. However, of course, we might
expect them to behave in a certain way. The ++ operator should...
|
by: anumliaqat |
last post by:
hello!!
i hav a problem.my program is giving correct outputs for some inputs but wrong results for others.
for example if u give (4 2 2)&(2 1 2) to it,it shows all results correct....
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
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: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
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,...
| |