質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

3021閲覧

pythonでfractionモジュールを使わず分数と整数の加算をしたい

Rio_

総合スコア15

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2018/10/23 10:07

編集2018/10/23 11:16

前提・実現したいこと

python でfractionモジュールを使わずに設定した分数(Rat(1,2), Rat(1,3))と整数の計算をしようとしています。
その中で、整数 + 分数の形、(例えば 1 + Rat(1,2))
ができないです。
1(整数)を分数に書き換えられればできると思うのですが、方法がわかりません。

発生している問題・エラーメッセージ

TypeError Traceback (most recent call last) <ipython-input-25-13d4444e2a57> in <module>() ----> 1 1 + Rat(1,2) TypeError: unsupported operand type(s) for +: 'int' and 'instance'

該当のソースコード

python

1class Rat: 2 n = 0 3 d = 1 4 5 def __init__(self, n, d=1): 6 self.n = n 7 self.d = d 8 9 def __repr__(self): 10 return '{}/{}'.format(self.n, self.d) 11 12 def __add__(self,other): 13 if isinstance(other,Rat) == False: 14 other= Rat(other,1) 15 else: 16 pass 17 return Rat((self.n * other.d) + (other.n * self.d), self.d * other.d) 18 19 def __sub__(self,other): 20 return Rat((self.n * other.d) - (other.n * self.d), self.d * other.d) 21 if isinstance(other,Rat) == False: 22 other= Rat(other,1) 23 else: 24 pass 25 26 def __mul__(self,other): 27 return Rat(self.n * other.n, self.d * other.d) 28 if isinstance(other,Rat) == False: 29 other= Rat(other,1) 30 else: 31 pass 32 def __div__(self,other): 33 return Rat(self.n * other.d, self.d * other.n) 34 if isinstance(other,Rat) == False: 35 other= Rat(other,1) 36 else: 37 pass 38

試したこと

Rat(1,2) + 1
Rat(1,2) + Rat(1)
Rat(1) + Rat(1,2)
はできるのですが、
1 + Rat(1,2)
ができないです。

type(Rat(1,2))
instance
となっています

##追記
無事、加算については解決いたしました。ありがとうございました。

追加の質問なのですが、減算、乗算については同様に行えたのですが、除算が以下のようになってしまいます。解決方法がございましたら、教えていただけると幸いです。

発生している問題・エラーメッセージ(追記)

2 / one_half --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-47-5bb4201c0f77> in <module>() ----> 1 2 / one_half 47 48 def __rdiv__(self,other): ---> 49 return 1 / (self / other) RuntimeError: maximum recursion depth exceeded while calling a Python object

該当のソースコード(追記)

python

1class Rat: 2 n = 0 3 d = 0 4 5 def __init__(self, n, d=1): 6 self.n = n 7 self.d = d 8 9 def __repr__(self): 10 return '{}/{}'.format(self.n, self.d) 11 12 def __add__(self,other): 13 if isinstance(other,Rat) == False: 14 other= Rat(other,1) 15 else: 16 pass 17 return Rat((self.n * other.d) + (other.n * self.d), self.d * other.d) 18 19 def __radd__(self,other): 20 return self + other 21 22 def __sub__(self,other): 23 if isinstance(other,Rat) == False: 24 other= Rat(other,1) 25 else: 26 pass 27 return Rat((self.n * other.d) - (other.n * self.d), self.d * other.d) 28 29 def __rsub__(self,other): 30 return (self - other) * (-1) 31 32 def __mul__(self,other): 33 if isinstance(other,Rat) == False: 34 other= Rat(other,1) 35 else: 36 pass 37 return Rat(self.n * other.n, self.d * other.d) 38 def __rmul__(self,other): 39 return self * other 40 41 def __div__(self,other): 42 if isinstance(other,Rat) == False: 43 other= Rat(other,1) 44 else: 45 pass 46 return Rat(self.n * other.d, self.d * other.n) 47 48 def __rdiv__(self,other): 49 a = self / other 50 return 1 / a

補足情報(FW/ツールのバージョンなど)

anaconda-4.0.0

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

__radd__を定義してあげてください。

Python

1class MyClass: 2 def __add__(self, other): 3 print('add') 4 5 def __radd__(self, other): 6 print('radd') 7 return self + other 8 9 10inst = MyClass() 11 12inst + 1 13print('-' * 42) 141 + inst

実行結果 Wandbox

plain

1add 2------------------------------------------ 3radd 4add

有理数の加法は可換なので、__add__に投げれば問題ないでしょう。

質問追記を受けて

減算、乗算については同様に行えたのですが、除算が以下のようになってしまいます。

逆数を取得するメソッド乃至プロパティを用意し、被除数 * 除数の逆数 に持っていくのが簡単かと。

投稿2018/10/23 10:19

編集2018/10/23 11:44
LouiS0616

総合スコア35660

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Rio_

2018/10/23 10:54

早速のご回答、誠にありがとうございます。無事解決しました。
Rio_

2018/10/23 12:03

LouiS0616様、追記も回答していただきありがとうございました。発想自体も思いつかなかったので、アプローチを知れて嬉しく思います。本当にありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問