优雅的Python code代表整数分割整数、优雅、代表、code

2023-09-11 01:45:35 作者:断桥烟雨﹌旧人殇

我试着写code,解决了标准的整数划分问题(维基百科)。在code我写的是一个烂摊子。我需要一个优雅的解决方案来解决这个问题,因为我想提高我的编码风格。这不是一个家庭作业的问题。

解决方案

 >>>高清分区(号):
......答案=集()
... answer.add((号码,))
......对于x范围内(1号):
... y的在分区(数字 -  X):
... answer.add(元组(排序((X,)+ Y)))
...返回答案
...
>>>分区(4)
集([(1,3),(2,2),(1,1,2),(1,1,1,1),(4,)])
 

如果你想所有排列(即(1,3)和(3,1))的变化 answer.add(元组(排序((X,)+ Y)) answer.add((X,)+ Y)

I tried to write code to solve the standard Integer Partition problem (Wikipedia). The code I wrote was a mess. I need an elegant solution to solve the problem, because I want to improve my coding style. This is not a homework question.

解决方案 神器 VS Code,超详细Python配置使用指南

>>> def partition(number):
...     answer = set()
...     answer.add((number, ))
...     for x in range(1, number):
...         for y in partition(number - x):
...             answer.add(tuple(sorted((x, ) + y)))
...     return answer
... 
>>> partition(4)
set([(1, 3), (2, 2), (1, 1, 2), (1, 1, 1, 1), (4,)])

If you want all permutations(ie (1, 3) and (3, 1)) change answer.add(tuple(sorted((x, ) + y)) to answer.add((x, ) + y)