You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求编写Python脚本:生成字符串非首尾加句号的所有组合

Solution: Generate All Dot Insertion Combinations for a String

Got it, let's work through how to build this Python script. The core idea here is simple: for any string of length n, there are n-1 gaps between its characters (like "1234" has gaps between 1&2, 2&3, 3&4). Each gap can either have a dot or not—so we need to generate every possible combination of these choices, which gives us 2^(n-1) total combinations.

Step-by-Step Code Implementation

Here's a clean, adaptable function that handles this for any input string:

def generate_dot_combinations(input_str):
    # Handle edge cases upfront
    if not input_str:
        return []
    if len(input_str) == 1:
        return [input_str]
    
    num_gaps = len(input_str) - 1
    combinations = []
    
    # Iterate over all possible gap states (each state represented by a binary number)
    for state in range(2 ** num_gaps):
        # Convert state to binary, pad with leading zeros to match the number of gaps
        gap_flags = bin(state)[2:].zfill(num_gaps)
        current_combination = [input_str[0]]
        
        for idx in range(num_gaps):
            # Add a dot if the current gap flag is set to 1
            if gap_flags[idx] == '1':
                current_combination.append('.')
            # Add the next character from the input string
            current_combination.append(input_str[idx + 1])
        
        combinations.append(''.join(current_combination))
    
    return combinations

How It Works

Let's use your example "1234" to break it down:

  • num_gaps is 3, so we loop from 0 to 7 (since 2^3 = 8 total possible states)
  • Each state gets converted to a 3-digit binary string: 000, 001, 010, ..., 111
  • For each binary string:
    • 000 = no dots → "1234"
    • 001 = dot only after 3 → "123.4"
    • 010 = dot only after 2 → "12.34"
    • 011 = dots after 2 and 3 → "12.3.4"
    • And so on until 111 = dots after every character → "1.2.3.4"

Testing the Function

Try it with your sample input:

result = generate_dot_combinations("1234")
print(result)

You'll get this output (which matches your expected examples):

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

It works seamlessly for any string length too:

  • For "abc" you'll get ['abc', 'ab.c', 'a.bc', 'a.b.c']
  • For a single character like "x" it returns ['x']
  • For an empty string it returns []

内容的提问来源于stack exchange,提问作者Rowan Bradbury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:23:12