-2

Below is my code and I'm getting a snytax error at def. Please can anyone help with answer?

def ElementsandIndices(int [] arr, int n):
    count = 0
    for i in range(0, n):
        if arr[i] == i:
            count += 1
    return count
rioV8
  • 24,506
  • 3
  • 32
  • 49

3 Answers3

1

Python is not a strong-typed language, and you have your definitions a little mixed up. Since, by default, variables do not have a type, here's the normal way to define this function:

def ElementsandIndices(arr, n):
    count = 0
    for i in range(0, n):
        if arr[i] == i:
            count += 1
    return count

However, recently typing has become optional, as an additional context assistant to whatever IDE you're using. So if you want to see the types, you can define it like so in Python 3.7+

from typing import List

def ElementsandIndices(arr:List[int], n:int):
    count = 0
    for i in range(0, n):
        if arr[i] == i:
            count += 1
    return count

If your Python version is Python 3.9+, you can use list instead of typing.List:

def ElementsandIndices(arr:list[int], n:int):
    count = 0
    for i in range(0, n):
        if arr[i] == i:
            count += 1
    return count
Alan Bagel
  • 818
  • 5
  • 24
David Culbreth
  • 2,610
  • 16
  • 26
0

int [] arr and int n are both not valid python syntax. Just use arr and n instead. If you want to specify the argument's type, use type hints.

Alan Bagel
  • 818
  • 5
  • 24
-1

It can be done in 1 line

def ElementsandIndices(arr):
    return sum(1 for i,v in enumerate(arr) if v == i)

rioV8
  • 24,506
  • 3
  • 32
  • 49