获取通过打破一个数字形成的所有可能的完美正方形列表

获取通过打破一个数字形成的完美正方形列表的所有可能排列。


例如:如果 N = 14,则列表为 [1,1,4,4,4], [1,4,9] , [1,1,1,1,1,9] , [1,1,1, 1,1,1,1,1,1,1,1,1,1,1]


输出列表可以是任何顺序


我得到了这个代码,但它只能按顺序给出完美的正方形。


l = []

b = int(input())

for i in range(1,b):

    k = i*i

    l.append(k)

    if sum(l)>b:

        l.pop()

        break

    else:

        pass

print(l)


喵喵时光机
浏览 135回答 2
2回答

Qyouu

以下代码导致 N = 14 的 6 种可能性,而不是发布的 4。代码from itertools import chain, combinationsfrom pprint import pprint# flatten and powerset from#&nbsp; &nbsp;https://docs.python.org/3/library/itertools.html#itertools-recipesdef flatten(list_of_lists):&nbsp; &nbsp; "Flatten one level of nesting"&nbsp; &nbsp; return chain.from_iterable(list_of_lists)def powerset(iterable):&nbsp; &nbsp; "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"&nbsp; &nbsp; s = list(iterable)&nbsp; &nbsp; return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))def solve(n):&nbsp; " Get all possible permutations of list of perfect squares formed by breaking a number "&nbsp; squares = (i*i for i in range(1, int(b**0.5)+1)) # squares that can be used&nbsp; multiples = ([i]*int(b//i) for i in squares)&nbsp; &nbsp; &nbsp;# repetition of squares that can be used&nbsp; numbers = flatten(multiples)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# flatten to single list&nbsp; # Compute set of powerset, and take results which sum to b&nbsp; return [x for x in set(powerset(numbers)) if sum(x) == b]&nbsp;测试b = int(input('input number: '))&nbsp; # Enter 14result = solve(b)pprint(result)输出input number: 14[(1, 1, 1, 1, 1, 1, 4, 4),&nbsp;(1, 1, 1, 1, 1, 9),&nbsp;(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4),&nbsp;(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),&nbsp;(1, 4, 9),&nbsp;(1, 1, 4, 4, 4)]限制最大长度def solve_maxlen(n, maxlen):&nbsp; " Get all possible permutations of list of perfect squares formed by breaking a number "&nbsp; squares = (i*i for i in range(1, int(b**0.5)+1)) # squares that can be used&nbsp; multiples = ([i]*int(b//i) for i in squares)&nbsp; &nbsp; &nbsp;# repetition of squares that can be used&nbsp; numbers = flatten(multiples)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# flatten to single list&nbsp; # Compute set of powerset, and take results which sum to b&nbsp; return [x for x in set(powerset(numbers)) if sum(x) == b and len(x) <= maxlen]&nbsp;pprint(solve_maxlen(14, 6))输出[(1, 1, 1, 1, 1, 9), (1, 4, 9), (1, 1, 4, 4, 4)]

慕尼黑5688855

import itertoolsup_to = int(input())def is_perfect_square(number):&nbsp; squared = pow(number, 0.5)&nbsp; return int(squared) == squaredperfect_squares = filter(is_perfect_square, range(1, up_to))permutations = list(itertools.permutations(perfect_squares))print(permutations)输出是:[(1, 4, 9), (1, 9, 4), (4, 1, 9), (4, 9, 1), (9, 1, 4), (9, 4, 1)]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python