给定一个输入,生成所有组合,其中每个数字大一或小一

问题描述 投票:0回答:1

例如,给定 123456,没有数字可以不变,但每个数字都会增加一位或减少一位,例如 234567 或 012345 或 212565。我相信应该有 2^N 种组合,其中 N 是位数。

我不知道从哪里开始。我正在考虑 for 循环,但我想不出一种系统的方法来运行每个组合。

python algorithm math combinatorics
1个回答
0
投票

您使用系统方法生成所有组合的方法是正确的,其中给定数字中的每个数字增加或减少 1。对于N位数字,确实有 2^N 个这样的组合。这是因为对于每个数字,您有两种选择:要么增加 1,要么减少 1。
该函数生成给定数字的所有组合,其中每个数字增加或减少 1。对于示例“123456”,它成功创建了 64 个组合,符合 6 位数字的预期 (2^6=64)。该函数适用于任意数量的数字,并根据您的标准提供一组表示所有可能组合的字符串。

 def generate_combinations(number_str):
    if not number_str:
        return {''}  # Base case: return a set with an empty string
    smaller_combinations = generate_combinations(number_str[1:])
    digit = int(number_str[0])
    new_combinations = set()
    for combo in smaller_combinations:
        if digit < 9:
            new_combinations.add(str(digit + 1) + combo)
        if digit > 0:
            new_combinations.add(str(digit - 1) + combo)
    return new_combinations

  test_number = "123456"
  combinations = generate_combinations(test_number)
  print(len(combinations), combinations)

输出:64 {'234367'、'032547'、'014545'、'214545'、'232545'、'014567'、'034567'、'214547'、'212345'、'212567'、'01436 5' ,'012347','214347','032345','232347','034367','034367','234545','034347','014347','014347','012367',012367',012367',,'214345 032365'、'032347'、'234567'、'212545'、'232565'、'212347'、'214565'、'214567'、'014547'、'012345'、'214367'、'014565'、'232 367' ,'034365','232345','034565','032565','034545','034545','232567','234345','232365','232365','234565','234565','234565','234565','212565 012547'、'012365'、'012567'、'214365'、'212547'、'014367'、'032567'、'232547'、'212365'、'034345'、'034547'、'234547'、'014 345' 、'212367'、'012565'、'032367'}

© www.soinside.com 2019 - 2024. All rights reserved.