确定实际数字

时间:2016-11-28 22:08:24

标签: python

所以我给了一小部分,必须确定分母是否是实际数字。实用数字的描述:What is a practical number?

我已经有一个函数返回数字的所有因子:

def factorFinder(x):
    #Pre: Valid Integer for students
    #Post: Returns list of factors for that number
    #Takes the number of students as argument and returns all factors for that number
    lst = []
    for i in range(1, x+1):
        if x % i == 0:
            lst.append(i)
    return(lst)

并且给出作为参数的因子列表的函数返回其所有子列表的总和列表:

import itertools
def sumsOfSublists(lst):
    # Pre: a non-empty list
    # Post: returns a list of sums of all possible list sublists of length >= 2
    # given a list, returns a sorted list containing sums of
    # all combinations of sublists of length 2..list_length
    sumList = []
    for i in range(2, len(lst)+1):
       zlist = list(itertools.combinations(lst,i))
       for el in zlist:
           sumList.append(sum(el))
    return sorted(sumList)

如果数字是否合适,我不知道如何进行测试。即使在多个网站上阅读之后,我也不太了解“实用数字”的概念。所以我想,如果有的话,这更像是一个数学问题。

还有两个号码,我需要打印出埃及分数。 (即)给定7/8应打印以下内容:(1/2)+(1/4)+(1/8)。所有分子必须为1。

2 个答案:

答案 0 :(得分:3)

看起来你完成了所有繁重的工作,只需要检查一下:

def is_practical(n):
    s = set(sumsOfSublists(factorFinder(n)))
    return all(i in s for i in range(1, n))

您是否有任何理由将总和分类为listset查找起来要快得多。见https://wiki.python.org/moin/TimeComplexity

答案 1 :(得分:1)

我重新制定你的维基文章并希望它对你有帮助 - 因为正如AChampion所说 - 你已经完成了所有繁重的工作;)

n是一个实用的数字,如果:

  • l = [1,2,... n-1] //所有小于n的数字
  • divs = [i for i in range(1,n)if n%i == 0] //所有n的除数(我关联一个因子是术语分解的主要原因一个数字,所以你可能应该在你的问题中将因子改为除数)
  • 现在您必须将 l 的所有数字写为 divs 中的数字总和,您可以在其中使用所有数量的 div 一个或零次

例如n = 12是实际数字,因为:

  • l = [1,2,3,4,5,6,7,8,9,10,11]
  • divs = [1,2,3,4,6]
  • l [0] = divs [0],l [1] = divs [1],...,l [10] = divs [0] + divs [3] + divs [4] = 1 + 4 + 6 = 11 // l [1] = divs [0] + divs [0]是不允许的,因为你只能使用每个div的数量

相反,n = 3不是实际数字,因为:

  • l = [1,2]
  • divs = [1]
  • l [0] = divs [0],l [1] =mööööp

这也是我的解释的直接实现(但你也可以保持你已经完成的好工作!):<​​/ p>

from itertools import combinations

def isPracticalNumber(n):
    l = [i for i in range(1, n)]
    divs = [i for i in range(1, n) if n % i == 0]
    possibleSums = set()
    for i in range(1, len(divs)+1):
        combinationsOfLengthI = combinations(divs, i)
        for combi in combinationsOfLengthI:
            possibleSums.add(sum(combi))

    return all([i in possibleSums for i in l])

if __name__ == '__main__':
    print(isPracticalNumber(12)) # True
    print(isPracticalNumber(3)) # False

    practicalNumbers = [1, 2, 4, 6, 8, 12, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, 56, 60, 64, 66, 72, 78, 80, 84, 88, 90, 96, 100, 104, 108, 112, 120, 126, 128, 132, 140, 144, 150]
    calculatedPracticalNumbers = [i for i in range(1, 151) if isPracticalNumber(i)]
    print(len(calculatedPracticalNumbers) == len(practicalNumbers) and all([i in practicalNumbers for i in calculatedPracticalNumbers]))
相关问题