将字符串输入随机化为所有可能性 [英] Randomize a string input into all possibilities

查看:40
本文介绍了将字符串输入随机化为所有可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助制作一个使用 args 获取字符串并将其随机化为各种可能性的程序.然后,程序的结果将保存到用户在执行程序时提供的文本文件中.

解决方案

如果您需要以随机顺序所有可能的排列,那么我建议先构建然后重新排列列表:

from itertools 导入排列从随机导入随机播放def shuffled_permutations(s):perms = list(permutations(s)) # 创建所有排列shuffle(perms) # 随机打乱列表return ["".join(p) for p in perms] # 重建字符串并返回

应用此功能:

<预><代码>>>>shuffled_permutations("ABC")['BCA', 'CBA', 'BAC', 'ABC', 'ACB', 'CAB']

如果你真的不需要随机排列的排列(即你只想知道它们都是什么),直接使用 permutations 会更有效率,例如

for p in permutations(s):

注意,对于字符串len(s) == n,所有排列的长度为n!(例如对于n == 5, (5 * 4 * 3 * 2 * 1) == 120);这很快就会变长(例如,我的用户名有 3,628,800 个排列).

I need help making a program that takes a string using args and randomizes it into every possibility. The program's results would then be saved into a text file provided by the user when executing the program.

解决方案

If you need all of the possible permutations in a random order, then I would suggest building then shuffling a list:

from itertools import permutations
from random import shuffle

def shuffled_permutations(s):
    perms = list(permutations(s)) # create all permutations
    shuffle(perms) # shuffle the list randomly
    return ["".join(p) for p in perms] # rebuild strings and return

Applying this function:

>>> shuffled_permutations("ABC")
['BCA', 'CBA', 'BAC', 'ABC', 'ACB', 'CAB']

If you don't really need the permutations in a random order (i.e. you just want to know what they all are), it is much more efficient to use permutations directly, e.g.

for p in permutations(s):

Note that, for a string len(s) == n, the length of all permutations is n! (e.g. for n == 5, (5 * 4 * 3 * 2 * 1) == 120); this gets long pretty fast (there are 3,628,800 permutations of my user name, for example).

这篇关于将字符串输入随机化为所有可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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