Find a Fixed Point in a given array in Python
In this lesson, we will understand how to find a fixed point in a given array in Python and also we will take a easy code to understand it much better.
Explanation
Array is a special variable, which can hold more than one value at a time
The following code is written to explain that how we can find a fixed point from a given array.
In a fixed point array one element is donated as if the value is same as it`s index. The program will only return a value only if any value is present otherwise it will return -1. In this, we have an array of x distinct integers that are arranged in an ascending order. In the following code we write a function which returns a fixed point integer and if there is no fixed point integer it returns -1.The fixed point index is an index i such that array[i] is equal to i.
In the below Python code an array is given and x is equal to the length of the array . Since there is no fixed point in the given array so the output we get is -1.
- First we take a search function which searches from an array and x elements.
- Then we check the range that whether i is in range or not.
- If i is in the range then it returns i otherwise it return -1 as an output.
Below is our Python code that will able to find a fixed point in a given array.
def Search(array, x): for i in range(x): if array[i] is i: return i return -1 array = [-30, -15, 1, 5, 15, 17, 33, 52, 101] x = len(array) print(" The Fixed Point in Array is " + str(Search(array,x)))
Output
After we run the code we can get the output given below:
The Fixed Point in Array is -1
Leave a Reply