【问题标题】:How to find the product of the odd-indexed values in a list如何在列表中找到奇数索引值的乘积
【发布时间】:2020-05-20 00:25:46
【问题描述】:

我能够在“偶数”部分解决这个问题,但我陷入了奇数部分。

您将获得一组n 数字。您的任务是首先反转数组(第一个数字变为最后一个,第二个数字从最后一个变为第二个,依此类推),然后打印偶数索引处的数字总和,并打印奇数索引处的数字的乘积。

输入

第一行包含单个整数 N:元素数 后跟N个不同的整数,用空格隔开

输出

两个空格分隔的整数,表示偶数位数字的和与奇数位数字的乘积。

到目前为止我的代码:

n = int(input())
arr = [int(x) for x in input().split()]
arr.reverse()

for ele in arr:
    print(ele, end=" ")
print()

sum = 0
count = 1
while count <= n:
    if count % 2 == 0:
        sum += count
    count += 1
print(sum)

【问题讨论】:

  • 我将我的代码附加到偶数索引 #####n=int(input()) arr=[int(x) for x in input().split()] arr.reverse( ) for ele in arr: print(ele, end="") print() sum=0 count=1 while count
  • 请不要在 cmets 中发布代码。将其添加到问题中。

标签: python arrays list reverse


【解决方案1】:

您提供的代码中有几个问题,我将首先解决:

首先,您需要清楚奇数和偶数索引的含义。例如,在某些语言(Matlab)中,数组的第一个元素是索引位置 1。在 Python 和 Java 中,它是 0,因此,虽然您的示例假定为 1,但除非另有说明,否则它可能应该为 0。

其次,在您的sum+=count 行中,您是对索引位置求和,而不是对索引值求和,所以这不是您的问题所要求的。

代码的最后一点是您使用了sum 作为变量名。虽然这有效,但sum 也是一个 Python 关键字,您应该避免将它们用作变量名,就像您以后要使用 sum 函数一样,您将收到错误 TypeError: 'int' object is not callable,因为您重新定义了 @987654327 @函数是一个整数。

回答:

考虑到上述情况,这通过修复您的代码提供了第 1 部分的答案:

total = 0
count = 0
while count < n:
    if count % 2 == 0:
        total += arr[count]
    count += 1
print(total)

值得注意的是,当您在寻找偶数时,您最好将其写为:

total = 0
count = 0
while count < n:
    total += arr[count]
    count += 2
print(total)

但是,还有更简单的方法可以用更少的代码做到这一点,它们涉及列表切片。您可以通过指定[start: end: step] 对列表进行切片,因此arr[::2] 指定位置0 的开始(默认值),列表末尾的默认值)和步长2。这意味着如果arr包含[1,2,3,4,5,6],那么arr[::2] 将是[1,3,5](即所有偶数索引处的值),或者如果您指定1 即arr[1::2] 的起始位置,您将得到[2,4,6](即值在所有偶数索引上)。

所以,宁可使用 while 循环。您可以在偶数值上使用 for 循环:

total = 0
for even_val in arr[::2]:
    total += even_val
print(total)

但是对于sum,您可以更轻松地编写为列表切片上的简单sum 命令:

print(sum(arr[::2]))

在 Python 3.8 之前,对于 product 没有简单的 sum 等价物,因此如果您使用的是较低版本,您可以重复使用上述方法,因为您需要使用第一个值,然后与下一个相乘,即:

total = arr[1]
count = 3
while count < n:
    total *= arr[count]
    count += 2
print(total)

或使用for 循环:

total = arr[1]
for odd_val in arr[3::2]:
    total *= odd_val
print(total)

但从 Python 3.8(文档 here)开始,您现在可以从 math 库中导入 prod,其工作方式与 sum 相同:

from math import prod
print(prod(arr[1::2]))

[感谢@HeapOverflow 的推动]

由于这是一个问题集,它可能不是问题,因为所有示例的数组长度都可能是N > 2,但上面的示例确实假设arr 中至少有两个条目。如果不是这种情况,您应该在尝试访问 arr[1] 之前进行一些验证

【讨论】:

    【解决方案2】:

    这是一个可爱的小递归函数(假设基于一个的索引):

    # def prodSum(increment,multiplier=1,*rest): if zero based indices
    
    def prodSum(multiplier,increment=0,*rest):  
        if not rest: return multiplier,increment
        product,total = prodSum(*rest)
        return (product * multiplier, total + increment)
    
    x = [1,2,3,4,5]
    print(prodSum(*reversed(x))) # 15,6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多