迭代字符串的问题

时间:2014-08-21 12:51:53

标签: python string integer iteration multiplication

我有一串我想要迭代的数字。例如,字符串是20个字符长,我试图找到前5个数字的乘积,然后是第二个5,第三个,依此类推。

到目前为止,我已将数字转换为字符串,然后使用迭代索引生成我想要找到字符串乘积的数字。

然后我将数字串分成一个字符数组,然后将字符转换为整数。然后我使用函数来查找这些数字的乘积,然后将其添加到数组中。

我的想法是,一旦我拥有完整的阵列,我就可以找到最大的产品。

我遇到的问题是,在第一次迭代之后,产品将返回0 ,此时它应该更高。

我的代码如下所示:

def product(list):
    p = 1
    for i in list: 
        p *= i
    return p

products = []
count = 1

testno = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290
startno = 0
endno = 13

end = (len(str(testno)))-1
print("the end is",end)
while count < 4:
    teststring = (str(testno))[startno:endno]
    print("teststring is", teststring)
    strlist = (list(teststring))
    print("strlist is", strlist)
    numlist = list(map(int, strlist))
    print("numlist is",numlist)
    listproduct = (product(numlist))
    print("listproduct is",listproduct)
    products.append(listproduct)
    print("products is now",products)
    startno = startno + 1
    endno = endno + 1
    print("startno is now", startno)
    print("endno is now", endno)
    count += 1

print("the list of products is", products)
print("the biggest product is", max(products))

我没有像我想的那样优雅地做到这一点,也许是因为我没有正确理解这个问题。

我得到的违规输出看起来像这样:

the end is 999
teststring is 7316717653133
strlist is ['7', '3', '1', '6', '7', '1', '7', '6', '5', '3', '1', '3', '3']
numlist is [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3]
listproduct is 5000940
products is now [5000940]
startno is now 1
endno is now 14
teststring is 3167176531330
strlist is ['3', '1', '6', '7', '1', '7', '6', '5', '3', '1', '3', '3', '0']
numlist is [3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0]
listproduct is 0
products is now [5000940, 0]
startno is now 2
endno is now 15
teststring is 1671765313306
strlist is ['1', '6', '7', '1', '7', '6', '5', '3', '1', '3', '3', '0', '6']
numlist is [1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6]
listproduct is 0
products is now [5000940, 0, 0]
startno is now 3
endno is now 16
the list of products is [5000940, 0, 0]
the biggest product is 5000940

如果有人可以向我解释出现了什么问题,如何纠正它,以及是否有更优雅的方法可以解决这个问题,我将不胜感激。

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

@Axtract,只需将您的product功能修改为以下。

def product(list):
    p = 1
    for i in list:
        if i == 0: # Just use this if check here
            pass
        else:
            p *= i
    return p

答案 1 :(得分:0)

零和任何数字的乘积始终为零。

请注意,当numlist为零时,产品为零。

您的第一次迭代没有零,这就是您拥有非零产品的原因。

答案 2 :(得分:0)

您的产品中有0个零。第一个发生的不是零,而是其他所有。

因此,您的功能正常工作 - 只是输入数据的问题。

相关问题