优雅的Python code代表整数分割 [英] Elegant Python code for Integer Partitioning

查看:108
本文介绍了优雅的Python code代表整数分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写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.

解决方案

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

这篇关于优雅的Python code代表整数分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆