所以我给了一小部分,必须确定分母是否是实际数字。实用数字的描述: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。
答案 0 :(得分:3)
看起来你完成了所有繁重的工作,只需要检查一下:
def is_practical(n):
s = set(sumsOfSublists(factorFinder(n)))
return all(i in s for i in range(1, n))
您是否有任何理由将总和分类为list
? set
查找起来要快得多。见https://wiki.python.org/moin/TimeComplexity
答案 1 :(得分:1)
我重新制定你的维基文章并希望它对你有帮助 - 因为正如AChampion所说 - 你已经完成了所有繁重的工作;)
n是一个实用的数字,如果:
例如n = 12是实际数字,因为:
相反,n = 3不是实际数字,因为:
这也是我的解释的直接实现(但你也可以保持你已经完成的好工作!):</ 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]))