python求任意一个字符串的指定长度的所有排列

本文介绍了一种算法,用于从给定的字符串中生成指定长度的所有可能组合,并通过Python代码实现。该算法首先对字符串进行排序和去重,然后递归地生成所有组合,最后输出结果。此外,还提供了一种使用Python标准库itertools的简化实现。

题目要求
任意给定一个字符串str,生成数的位数n,有序输出位数为n的所有组合

样例输入

321234
3

样例输出

123
124
132
134
142
143
213
214
231
234
241
243
312
314
321
324
341
342
412
413
421
423
431
432

代码实现

def perm(ori, a, b, m):
    if a == m:
        print("".join(ori[:m]))
    for i in range(a, b):
        ori[i], ori[a] = ori[a], ori[i]
       	# 必须使用列表ori的拷贝,否则会出现重复
        perm(ori[:], a + 1, b, m)


if __name__ == '__main__':
    # 输入一个字符串、生成位数
    ss = list(input())
    n = int(input())
    # set实现去重
    st = set()
    # 去重
    ss = [c for c in ss if c not in st and not st.add(c)]
    # 要求 n<=len(ss)
    perm(sorted(ss),0,len(ss),n);

其他方法

# 使用库实现更简便
from itertools import combinations, permutations
s1 = input()
s2 = set(s1)
s3 = list(s2)
s3.sort(reverse=True)
for i in permutations(s3,len(s3)):
    print("".join(i))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值