python中如何找出所有加起来等于一定和的子串?

新手上路,请多包涵

假设我有一个数字 3523014 作为字符串。我怎样才能找到以列表形式组合的所有子字符串集,加起来等于某个数字,比如 10。我写了一个代码,但我只给出了几个线性搜索的子字符串的输出。

请修复代码 -

 def find_ten_substring(num_str):
        str1=""
        list1=[]
        a=0
        for i in range(0,len(num_str)):
                a=a+int(num_str[i])
                str1+=str(num_str[i])
                if(a==10):
                        a=0
                        list1.append(str1)
                        str1=""
        return(list1)

num_str="3523014"
print("The number is:",num_str)
result_list=find_ten_substring(num_str)
print(result_list)

结果为 [‘352’]。预期输出应为 [‘5230’, ‘23014’, ‘523’, ‘352’]

原文由 Shashank Bhardwaj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 340
1 个回答

让我从你的代码有什么问题开始..

  • 在 For 循环中,在完成“3”、“5”、“2”作为迭代后,您已将 a 设置为零并将 str 设置为空,但是,“For”循环的下一次迭代是索引 3 处的“3”而不是在索引 1 处为“5”。
  • 从索引 3 开始,如果您将所有值相加,即 3、0、1、4,总和仍然不会为 10。因此,您只有“352”作为子字符串。要解决此问题,您可以使用两个 for 循环。

现在我的解决方案..

 def find_ten_substring(num_str):
    ten_substr=[]         #list to store all substring
    for i in range(len(num_str)):
        sum=0
        sub_str=""
        for j in range(i,len(num_str)):
            sum+=int(num_str[j])
            if sum<10:
                sub_str+=num_str[j]
            elif sum==10:
                sub_str+=num_str[j]
                ten_substr.append(sub_str)
#checks if my current index is not my last index as at avoid index out of bound
#error in next line
                if (j!=len(num_str)-1):
#checks if value at next index is "0". If true, it does not make sum as zero and
#substring as empty, instead continues with same value in next iteration.
                    if (num_str[j+1]=="0"):
                        continue;
                    else:
                        break;
    return ten_substr;

num_str="28353002"
print("The number is:",num_str)
result_list=find_ten_substring(num_str)
print(result_list)

原文由 Anand Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议