Python脚本将字符串和放置字符的每个组合组合在一起



我正在寻找创建一个脚本以在第一个和最后一个位置添加到字符串的脚本的帮助,使用尽可能多的时期来创建尽可能多的组合:

字符串1234的输出将是:

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

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

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

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']

无递归的简洁解决方案:使用二进制组合(想想011011等(来确定在哪里插入点。

在每个字母之间,在此索引处有1时放置一个点,当有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']

最新更新