最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Python生成所有非递减序列

SEO心得admin53浏览0评论
本文介绍了Python生成所有非递减序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很难找到一种以Python方式进行此操作的方法.我想我可以以某种方式使用itertools,因为我之前做过类似的事情,但不记得自己做了什么.

I am having trouble finding a way to do this in a Pythonic way. I assume I can use itertools somehow because I've done something similar before but can't remember what I did.

我正在尝试生成长度为L的所有非递减列表,其中每个元素可以取1到N之间的值.例如,如果L = 3和N = 3,则[1,1,1],[1 ,1,2],[1,1,3],[1,2,2],[1,2,3]等

I am trying to generate all non-decreasing lists of length L where each element can take on a value between 1 and N. For example if L=3 and N=3 then [1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3], etc.

推荐答案

您可以使用 itertoolsbinations_with_replacement :

You can do this using itertoolsbinations_with_replacement:

>>> L, N = 3,3 >>> cc = combinations_with_replacement(range(1, N+1), L) >>> for c in cc: print(c) (1, 1, 1) (1, 1, 2) (1, 1, 3) (1, 2, 2) (1, 2, 3) (1, 3, 3) (2, 2, 2) (2, 2, 3) (2, 3, 3) (3, 3, 3)

之所以可行,是因为c_w_r保留了输入的顺序,并且由于我们传入了一个非递减的序列,所以我们只会得到非递减的元组.

This works because c_w_r preserves the order of the input, and since we're passing a nondecreasing sequence in, we only get nondecreasing tuples out.

(如果您确实需要列表而不是元组,则很容易转换为列表.)

(It's easy to convert to lists if you really need those as opposed to tuples.)

发布评论

评论列表(0)

  1. 暂无评论