我的程序的目的是确定一定数量的连续数字的最大乘积。例如,程序提示用户输入一串数字(例如255969406)和连续数字的大小(3),因此我的程序将确定提供的数字中连续3位数的最大乘积,我的程序编译和运行但返回的产品不正确。
def Pro(dig,snum):
number = 1
pr = 0
for x in xrange(0,dig-1):
pr = int(snum[x])
number = pr*number
return number
def Product(dig,indx,snum):
number = 1
pr = 0
for x in xrange(1,dig):
pr = int(snum[indx+x])
number = pr*number
return number
def Main():
num = raw_input("Enter a string of digits")
dig = input("Input number of digits in group")
x = 1
val = Pro(dig,num)
grps = int(len(num)/ dig)
while x<grps:
val2= Product(dig,x,num)
if val2>val:
val = val2
x +=1
print("The max product of " + str(dig) +" consecutive digits in " + num + " is " + str(val))
if __name__ == "__main__":
Main()
答案 0 :(得分:1)
你可以尝试一下:
x = '134214257248'
m = 0
for i in range(len(x) - 2):
m = max(m, int(x[i])*int(x[i+1])*int(x[i+2]))
print m
# 2*5*7 = 70
70
编辑:接受任何数量(n)的连续数字
import numpy as np
x = '134214257248'
m = 0
n = 3
for i in range(len(x) - n + 1):
m = max(m, np.prod(list(int(l) for l in x[i:i + n])))
print m
70