You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数语法错误求助:实现统计数组中元素值等于索引值的元素个数

Fixing the Syntax Error in Your Element-Index Match Counter Function

Hey there! Let's sort out that syntax error in your Python function first, then we can even make it a bit cleaner.

What's Causing the Syntax Error?

Your function definition uses Java/C-style type annotations (int [] arr, int n) which isn't valid Python syntax. Python has its own approach to type hints, and you don't need to declare parameter types this rigid way to begin with (though proper type hints are optional if you want them).

Corrected Version of Your Code

Here's the fixed function that works exactly as you intended:

def elements_and_indices(arr):
    count = 0
    for i in range(len(arr)):
        if arr[i] == i:
            count += 1
    return count

Let me break down the key changes:

  • Removed the invalid int [] arr, int n parameter syntax—Python doesn't require this kind of type declaration for function parameters.
  • Got rid of the n parameter entirely: we can get the array's length directly with len(arr), so passing n is redundant and could lead to errors if someone passes a mismatched value.
  • Renamed the function to follow Python's snake_case naming convention (this is just a style best practice, not mandatory for functionality).

Even More Concise (and Pythonic) Version

If you want to trim this down to a more idiomatic Python solution, you can use a generator expression with sum():

def elements_and_indices(arr):
    return sum(1 for i, num in enumerate(arr) if num == i)

Here, enumerate(arr) gives us both the index i and the element num directly, so we don't have to index into the array with arr[i]. The generator expression outputs a 1 for every match, and sum() adds those up to get the total count.

Example Usage

Testing this with a sample array to confirm it works:

test_arr = [0, 2, 2, 3, 5]
print(elements_and_indices(test_arr))  # Output: 3 (matches at indices 0, 2, 3)

内容的提问来源于stack exchange,提问作者Saurabh Chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:58:13