简体   繁体   English

Python代码用于将大数的相邻数字相乘并找到最大可能乘积,而不给出期望的结果

[英]Python code for multiplying adjacent digits of a big number and finding maximum possible product, not giving desired result

Here is a Python code for finding maximum product we can get from 13 adjacent digits of a number. 这是一个Python代码,用于查找可以从一个数字的13个相邻数字获得的最大乘积。 There is no error message, but this program is not giving the desired output. 没有错误信息,但是该程序没有提供所需的输出。 I am getting(in repl.it) 1 everytime, though it is clear that the answer is not 1 . 我每次都得到(repl.it) 1 ,尽管很明显答案不是1 I am new to programming. 我是编程新手。

My attempt 我的尝试

I have converted the number into an string and stored it into a array to get element by element. 我已经将数字转换为字符串,并将其存储到数组中以逐元素获取。 The outer for loop traversing over all the numbers(last time when i have value len(n)-12 , i+j will reach the last entry of the array. (Though the array stores the number in a reverse order, I haven't reversed it because, we don't need to). 遍历所有数字的外部for循环(最后一次当i值是len(n)-12i+j将到达数组的最后一个条目。(尽管数组以相反的顺序存储数字,但我没有t可以将其逆转,因为我们不需要这样做。

n = "123899778978978787888787778788767677667"
arr = []
for i in range(len(n)):
  arr.append(int(n)%10)
  n = str(int(n)//10)

mul = 1
max_mult = 1
for i in range(len(n)-12):
  for j in range(13):
    mul = mul * int(arr[i+j]) 

  if(max_mult<mul):
    max_mult = mul
print(max_mult)

Can anyone tell me where I am going wrong? 谁能告诉我我要去哪里错了? Any help will be appreciated. 任何帮助将不胜感激。

Your logic can be simplified somewhat using zip : 您可以使用zip简化您的逻辑:

n_list = list(map(int, list(n)))
res = max(i * j for i, j in zip(n_list, n_list[1:]))  # 81

If you insist on using a for loop: 如果您坚持使用for循环:

n_list = list(map(int, list(n)))
max_mult = 0

for i, j in zip(n_list, n_list[1:]):
    mult = i * j
    if mult > max_mult:
        max_mult = mult

print(max_mult)  # 81

Note you can modify your existing range -based iteration, but this is not considered Pythonic: 请注意,您可以修改现有的基于range的迭代,但这不被视为Pythonic:

for i in range(len(n_list) - 1):
    mult = n_list[i] * n_list[i+1]
    if mult > max_mult:
        max_mult = mult

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM