【问题标题】:how to represent multiplicty of prime factor in factorization in python如何在python中表示因式分解中的素数多重性
【发布时间】:2021-10-20 15:53:49
【问题描述】:

我编码这个函数分解(n)......如下所示

def factorization(n):
    factor=[]
    for i in range(2,n+1):
        while n % i == 0:
            n = n/i
            factor.append(i)
        print(factor)

如果你写这个 分解(180)= [2,2,3,3,5] 但我想打印这种格式: 180 = 2^2 x 3^2 x 5

但我做不到。 我认为“列表计数”很有用,但我不知道如何正确使用每个因素的数量,并对其进行格式化。

【问题讨论】:

    标签: python python-requests integer format factorization


    【解决方案1】:

    使用 vanilla python 和一些格式:

    def factorization(n):
        factor = []
        for i in range(2, n + 1):
            while n % i == 0:
                n = n / i
                factor.append(i)
        print('*'.join(f'{n}' + (f'^{factor.count(n)}' if factor.count(n) > 1 else '') for n in set(factor)))
    
    
    factorization(180)
    

    打印:

    2^2*3^2*5
    

    【讨论】:

      【解决方案2】:

      您可以使用 collections.Counter:https://docs.python.org/3/library/collections.html#collections.Counter

      from collections import Counter
      
      counts = Counter(factorization(180))
      counts[2]
      counts[3]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-23
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        • 1970-01-01
        • 2013-10-19
        相关资源
        最近更新 更多