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
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
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
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.
It can be done in 1 line
def ElementsandIndices(arr):
return sum(1 for i,v in enumerate(arr) if v == i)