Search code examples
pythonfractions

Python - Defining fraction


Using Python define named fraction Defining using function without using import and return with format of a/b Examples

fraction(9,24) result = > 3/8

I'm not really good at English so I don't really know what fraction really is. My school only taught in my country's language.

def fraction(a,b):
    return a ? b ?
fraction(9,24)

Solution

  • Without fraction modules, call factorise(9,24) will return a_ret as 3 and b_ret as 8.

    def prime_factors(n):
        i = 2
        factors = []
        while i * i <= n:
            if n % i:
                i += 1
            else:
                n //= i
                factors.append(i)
        if n > 1:
            factors.append(n)
        return factors
    
    def factorise(a,b):
        a_list = prime_factors(a)
        a1_list = a_list
        b_list = prime_factors(b)
        b1_list = b_list
        for x in a_list:
            if x in b1_list: 
                b1_list.remove(x) 
                a1_list.remove(x)
        for x in b_list:
            if x in a1_list: 
                a1_list.remove(x)
                b1_list.remove(x) 
        a_ret = 1
        b_ret = 1
        for x in a1_list:
            a_ret *= x
        for x in b1_list:
            b_ret *= x
        print(a_ret,b_ret)