为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喵时光机 2022-11-09 16:32:53
获取通过打破一个数字形成的完美正方形列表的所有可能排列。例如:如果 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:        passprint(l)
查看完整描述

2 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

以下代码导致 N = 14 的 6 种可能性,而不是发布的 4。


代码


from itertools import chain, combinations

from pprint import pprint


# flatten and powerset from

#   https://docs.python.org/3/library/itertools.html#itertools-recipes

def flatten(list_of_lists):

    "Flatten one level of nesting"

    return chain.from_iterable(list_of_lists)


def powerset(iterable):

    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"

    s = list(iterable)

    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))


def solve(n):

  " Get all possible permutations of list of perfect squares formed by breaking a number "

  squares = (i*i for i in range(1, int(b**0.5)+1)) # squares that can be used

  multiples = ([i]*int(b//i) for i in squares)     # repetition of squares that can be used

  numbers = flatten(multiples)                     # flatten to single list


  # Compute set of powerset, and take results which sum to b

  return [x for x in set(powerset(numbers)) if sum(x) == b] 

测试


b = int(input('input number: '))  # Enter 14

result = solve(b)

pprint(result)

输出


input number: 14

[(1, 1, 1, 1, 1, 1, 4, 4),

 (1, 1, 1, 1, 1, 9),

 (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4),

 (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),

 (1, 4, 9),

 (1, 1, 4, 4, 4)]

限制最大长度


def solve_maxlen(n, maxlen):

  " Get all possible permutations of list of perfect squares formed by breaking a number "

  squares = (i*i for i in range(1, int(b**0.5)+1)) # squares that can be used

  multiples = ([i]*int(b//i) for i in squares)     # repetition of squares that can be used

  numbers = flatten(multiples)                     # flatten to single list


  # Compute set of powerset, and take results which sum to b

  return [x for x in set(powerset(numbers)) if sum(x) == b and len(x) <= maxlen] 


pprint(solve_maxlen(14, 6))

输出


[(1, 1, 1, 1, 1, 9), (1, 4, 9), (1, 1, 4, 4, 4)]


查看完整回答
反对 回复 2022-11-09
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

import itertools


up_to = int(input())


def is_perfect_square(number):

  squared = pow(number, 0.5)

  return int(squared) == squared


perfect_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)]


查看完整回答
反对 回复 2022-11-09
  • 2 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号