
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count number of elements present in a set of elements with recursive indexing in Python
Suppose we have a list of numbers called A and another number k, we have to make a new set of possible elements {A[k], A[A[k]], A[A[A[k]]], ... } stopping before it's out of index. We have to find the size of this set, otherwise -1 when there is a cycle.
So, if the input is like A = [1,2,3,4,5,6,7], k = 1, then the output will be 6 as A[1] = 2, A[2] = 3, A[3] = 4, A[4] = 5, A[5] = 6, A[6] = 7, So the set is {2,3,4,5,6,7}, size of set is 6.
To solve this, we will follow these steps −
- seen := a new set
- while k < size of A, do
- if A[k] in seen, then
- return -1
- insert A[k] into seen
- k := A[k]
- if A[k] in seen, then
- return size of seen
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, A, k): seen = set() while k < len(A): if A[k] in seen: return -1 seen.add(A[k]) k = A[k] return len(seen) ob = Solution() print(ob.solve([1,2,3,4,5,6,7], 1))
Input
[1,2,3,4,5,6,7], 1
Output
6
- Related Articles
- Program to count number of sublists with exactly k unique elements in Python
- Program to count number of elements in a list that contains odd number of digits in Python
- Program to count number of elements are placed at correct position in Python
- Python program to count number of substring present in string
- Count number of elements in an array with MongoDB?
- Python Program to Count number of lines present in the file
- Count Elements x and x+1 Present in List in Python
- Count number of elements between two given elements in array in C++
- Count the number of elements in a HashSet in Java
- Python program to count number of vowels using set in a given string
- Python Program to Extract Elements from a List in a Set
- Count occurrences of the average of array elements with a given number in C++
- Count of matrices (of different orders) with given number of elements in C++
- Count the number of masked elements in Numpy
- Total number of elements present in an array in C#

Advertisements