Python生成所有非递减序列

编程入门 行业动态 更新时间:2024-10-10 08:22:40
本文介绍了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.)

更多推荐

Python生成所有非递减序列

本文发布于:2023-11-30 07:24:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!