Python脚本,用于将字符串的每个组合与放置的字符组合在一起

时间:2018-04-25 12:46:31

标签: python string random combinations permutation

我正在寻找帮助来创建一个脚本,以便在每个地方为字符串添加句点,但首先和最后,使用尽可能多的句点来创建尽可能多的组合:

字符串1234的输出为:

["1234", "1.234", "12.34", "123.4", "1.2.34", "1.23.4" etc. ]

显然这需要适用于所有长度的字符串。

2 个答案:

答案 0 :(得分:2)

你应该自己解决这类问题,这些是操作数据的简单算法,你应该知道如何提出。 但是,这是解决方案(更长清晰度版本):

my_str = "1234"         # original string

# recursive function for constructing dots
def construct_dot(s, t):
    # s - the string to put dots
    # t - number of dots to put

    # zero dots will return the original string in a list (stop criteria)
    if t==0: return [s]

    # allocation for results list
    new_list = []

    # iterate the next dot location, considering the remaining dots.
    for p in range(1,len(s) - t + 1):

        new_str = str(s[:p]) + '.' # put the dot in the location
        res_str = str(s[p:]) # crop the string frot the dot to the end

        sub_list = construct_dot(res_str, t-1) # make a list with t-1 dots (recursive)

        # append concatenated strings
        for sl in sub_list:
            new_list.append(new_str + sl)

    # we result with a list of the string with the dots.
    return new_list

# now we will iterate the number of the dots that we want to put in the string.
# 0 dots will return the original string, and we can put maximum of len(string) -1 dots.
all_list = []
for n_dots in range(len(my_str)):
    all_list.extend(construct_dot(my_str,n_dots))

# and see the results
print(all_list)

输出是:

['1234', '1.234', '12.34', '123.4', '1.2.34', '1.23.4', '12.3.4', '1.2.3.4']

答案 1 :(得分:1)

没有递归的简洁解决方案:使用二进制组合(考虑110111等)来确定插入点的位置。< / p>

在每个字母之间,当此索引处有一个0时会加一个点,而当your_string = "1234" def dot_combinations(string): i = 0 combinations = [] # Iter while the binary representation length is smaller than the string size while i.bit_length() < len(string): current_word = [] for index, letter in enumerate(string): current_word.append(letter) # Append a dot if there's a 1 in this position if (1 << index) & i: current_word.append(".") i+=1 combinations.append("".join(current_word)) return combinations print dot_combinations(your_string) 有一个空字符串时。

['1234', '1.234', '12.34', '1.2.34', '123.4', '1.23.4', '12.3.4', '1.2.3.4']

输出:

    function myFunction() {
  var folder = DriveApp.getFolderById("0B9EI2E_9Cj9rT1JmVk5ESnhVbjA");
  var contents = DriveApp.getFileById("18cmOQXdAaW1lmYLvDhpi4BrYFI5LWMh2");



   var Body = contents.getAs('text/plain');
   var bytes = Utilities.base64Decode(Body, Utilities.Charset.UTF_8);



   folder.createFile(bytes);


 Logger.log(folder);
}