Find the only repetitive element between 1 to n-1 in Python
In this tutorial, we will show you how to find the only repetitive element between 1 and n-1 elements in Python. This tutorial deals with the simple methods that are available and easy to understand.
In this method, we use the sum formula.
The formula for calculating the sum of first n-1 natural numbers is
- ( n-1)*n/2
Compute the sum of elements in an array and subtract the sum of natural numbers from it. The answer which we got from this subtraction is the only repetitive element.
Let’s take a look at the program.
arr=list(map(int,input().split())) sumOfarr=sum(arr) n=len(arr) sum2=(n-1)*n//2 print("The only repetitive element is:",sumOfarr-sum2)
- It splits a string into a list. You can specify the separator as an argument. If no separator is given, it breaks the string by spaces.
- It takes 2 arguments. The first one is the method to apply, the second one is the data to apply to it. In this code, it typecasts every element of the list to an integer.
- It takes sequence types and converts them to lists. It takes a sequence as an argument and returns a list.
- It is used to find the sum of elements in a list. It takes a list as an argument and returns the sum of a list.
1 2 3 4 5 6 7 5
The only repetitive element is: 5
- Get the input from the user as a list.
- Maintain a temporary list.
- Traverse each element in a list.
- If an element is not found in the temporary list, add that element to a temporary list.
- If an element is found in the temporary list, it means that element is repeated and then print that element as the only repetitive element in a list.
arr=list(map(int,input().split())) li= for x in arr: if(x in li): print("The only Repetitive element is:",x) break else: li.append(x)
1 2 3 4 5 6 7 5
The only Repetitive element is: 5
I hope that you learned something useful from this tutorial.