![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Interesting Python Implementation for Next Greater Elements
In this article, we will learn about defining and user-defined functions to predict the next greatest element.
Problem statement
We are given an array & we need to print the Next Greater Element for every element present in the array. The Next greater Element for an arbitrary element y is the first greatest element present on the right side of x in array. Elements for which no greatest element exist, return -1 as output.4
Input test case
[12,1,2,3]
Output
12 -> -1 1 -> 3 2 -> 3 3 -> -1
Now let’s observe the source code.
Example
# Function Def elevalue(arr): # Iteration for i in range(0, len(arr)): # slicing max final = max(arr[i:]) # greatest check if (arr[i] == final): print("% d -> % d" % (arr[i], -1)) else: print("% d -> % d" % (arr[i], final)) # Driver program def main(): arr = [12,1,2,3] elevalue(arr) arr = [1,34,2,1] elevalue(arr) if __name__ == '__main__': main()
Output
12 -> -1 1 -> 3 2 -> 3 3 -> -1 1 -> 34 34 -> -1 2 -> -1 1 -> -1
Conclusion
In this article, we learned about interesting python implementation for next greater elements by using a user-defined function.
Advertisements