用于整数分区的优雅 Python 代码 [英] Elegant Python code for Integer Partitioning

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

问题描述

我尝试编写代码来解决标准的整数分区问题(维基百科).我写的代码一团糟.我需要一个优雅的解决方案来解决问题,因为我想改进我的编码风格.这不是作业问题.

解决方案

虽然这个答案很好,但我还是推荐 skovorodkin 的答案如下:

<预><代码>>>>定义分区(编号):... 答案 = 设置()... answer.add((number, ))... 对于范围内的 x(1, number):... 对于分区中的 y(数字 - x):... answer.add(tuple(sorted((x, ) + y)))...返回答案...>>>分区(4)set([(1, 3), (2, 2), (1, 1, 2), (1, 1, 1, 1), (4,)])

如果您想要所有排列(即 (1, 3) 和 (3, 1)),请将 answer.add(tuple(sorted((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.

解决方案

While this answer is fine, I'd recommend skovorodkin's answer below:

>>> 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 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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