1

私は新しいプログラミングで、この割り当てに少し困惑しています。2 つの分数のユーザー入力を取得して、積または商を取得することになっています。私たちは関数の定義を検討し、それらを完了しましたが、それらをユーザー入力に参照する方法とその逆の方法に困惑しています。ポインタや手がかりをいただければ幸いです。ある種のひらめきが必要だと思います。これが私の恥ずかしいコードです:

import fractions

def gcd(m,n):

    while m%n != 0: #finds the GCD (global definition)
        oldm = m
        oldn = n

        m = oldn
        n = oldm%oldn
    return n

class Fraction:

    def __init__(self,top,bottom): #constructor; creating fraction

        self.num = top      #methods to go about placing numerator and denominator
        self.den = bottom

    def __str__(self): #calling the fraction from methods above
        return str(self.num)+"/"+str(self.den) #Returns the value of fraction


    def __add__(self,otherfraction): #For addition of fractions (self = first fraction, otherfraction = second fraction)

        newnum = self.num*otherfraction.den + self.den*otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum,newden)

        return Fraction(newnum//common,newden//common) #Returns the new fraction with reduced answer.


    def __mul__(self,otherfraction): #For multiplication of fractions

        newnum = self.num*otherfraction.num
        newden = self.den*otherfraction.den
        common = gcd(newnum,newden)

        return Fraction(newnum//common,newden//common)


    def __floordiv__(self,otherfraction): #For division of fractions; use // not /

        newnum = self.num*otherfraction.den #Use multiplication of the reciprocal
        newden = self.den*otherfraction.num
        common = gcd(newnum,newden)

        return Fraction(newnum//common,newden//common)


    def __sub__(self,otherfraction): #For subtraction of fractions

        newnum = self.num*otherfraction.den - self.den*otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum,newden)

        return Fraction(newnum//common,newden//common)
4

2 に答える 2

0

これが役立つかどうかはわかりません(そうでない場合はお知らせください。回答を削除します)また、あなたの質問に対する直接の回答ではありませんが、役立つかもしれません(可能性があります)

この例には 2 つの部分があります。1 つは、ユーザーが入力した文字列のキャプチャです。その後、正規表現を使用してユーザー入力を「解析」します。

>>> import re
>>> re_fraction=re.compile(r"(?P<top>\d+)/(?P<bottom>\d+)$")
>>> fraction_str = raw_input()
3/4
>>> groups = re_fraction.match(fraction_str).groupdict()
>>> groups
{'top': '3', 'bottom': '4'}
>>> f = Fraction(groups['top'], groups['bottom'])

これが何をしているのかを理解するには、次を確認してください。

  1. 端末でユーザー入力をキャプチャする方法: raw_input

  2. 一般的な re モジュール: re (1)

  3. 正規表現と一致: re module (2)

  4. オンライン正規表現テスター

于 2013-09-16T21:14:39.620 に答える