MST
星途 面试题库

面试题:Python列表索引与循环结合应用

有一个列表 `nums = [1, 4, 9, 16, 25]`,请利用列表索引和循环,编写一个函数 `square_index_sum`,该函数接收一个整数 `n` 作为参数,计算并返回列表中前 `n` 个元素的索引值与其平方值乘积的总和。例如,当 `n = 3` 时,计算 `0*1 + 1*4 + 2*9` 的结果并返回。如果 `n` 大于列表长度,返回所有元素的计算总和。
45.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
nums = [1, 4, 9, 16, 25]


def square_index_sum(n):
    total = 0
    length = len(nums)
    end = n if n <= length else length
    for i in range(end):
        total += i * nums[i]
    return total