亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取通過打破一個數字形成的所有可能的完美正方形列表

獲取通過打破一個數字形成的所有可能的完美正方形列表

喵喵時光機 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 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號