Find the Longest Palindrome in an Array using Python

longest palindrome in array

Longest Palindrome in an Array

Here, in this page we will discuss the program to find the longest palindrome in an array in python programming language, we will discuss two different methods to find the longest palindromic element in the given array.

 

Here in this page we will discuss the following methods to find the longest palindromic number.

  • Method 1 : Using Naive Approach
  • Method 2 : Using Sorting

Method 1 :

  • Create a function ispalindrome(int n), it will return 1 if the passing number is palindrome otherwise return 0.
  • Inside the main function, create a variable say res = -1, that hold the maximum palindrome number.
  • Run a loop from [0, n),  and check if(ispalindrome(arr[i]) && res<arr[i]), then set res = arr[i].
  • Print the value of res.
Longest Palindrome in an array

Method 1 : Code in Python

Run
# Function to check if n is palindrome
def isPalindrome(n):

   divisor = 1
   while (int(n / divisor) >= 10):
      divisor *= 10

   while (n != 0):
      leading = int(n / divisor)
      trailing = n % 10
  
      if (leading != trailing):
        return False

      n = int((n % divisor) / 10)

      divisor = int(divisor / 100)
   return True

# Function to find the largest palindromic element
def largestPalindrome(arr, n):
   currentMax = -1

   for i in range(0, n, 1):
      if (arr[i] > currentMax and isPalindrome(arr[i])):
         currentMax = arr[i]

   return currentMax

# Driver Code

arr = [1, 232, 5545455, 909090, 161]
n = len(arr)

# print required answer
print(largestPalindrome(arr, n))

Output

5545455

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Method 2 :

In this method we first sort the array and then start traversing the array from end, and return the element that satisfy the condition, that it is palindrome.

  • Sort the array using inbuilt sort() function.
  • Start traversing from end of the array,
  • Print the element if it is palindrome.
  • If no element found then print -1.

Method 2 : Code in Python

Run
# Function to check if n is palindrome
def isPalindrome(n):

   divisor = 1
   while (int(n / divisor) >= 10):
      divisor *= 10

   while (n != 0):
      leading = int(n / divisor)
      trailing = n % 10
  
      if (leading != trailing):
        return False

      n = int((n % divisor) / 10)

      divisor = int(divisor / 100)
   return True

# Function to find the largest palindromic element
def largestPalindrome(A, n) :
    # Sort the array
    A.sort()

    for i in range(n - 1, -1, -1) :
        # If number is palindrome
        if (isPalindrome(A[i])) :
            return A[i]    

    # If no palindromic number found
    return -1

# Driver Code 
arr = [1, 232, 5545455, 909090, 161]
n = len(arr) 
# print required answer 
print(largestPalindrome(arr, n))

Output

5545455

37 comments on “Find the Longest Palindrome in an Array using Python”


  • azathmasha

    arr=[33,44,2002,9823,8930,3980,3]
    temp=[]
    for i in range(len(arr)):
    if str(arr[i])==str(arr[i])[::-1]:
    k=len(str(arr[i]))
    temp+=[int(k)]
    print(max(temp))


  • 20-CSE-011-

    def longpali(n,l):
    out = []
    for i in l:
    if str(i) == str(i)[::-1]:
    out.append(i)
    out.sort()
    return [out[-1]]
    print(longpali(4,[1, 232, 5545455, 909090, 161]))


  • majumdermoumita.ece

    arr=list(map(int,input().split(‘,’)))
    p=[]
    for num in arr:
    if str(num)[::-1]== str(num):
    p.append(str(num))
    if p:
    longest_palindrome= max(p)
    print(longest_palindrome)
    else:
    print(‘No Palindrome found.’)


  • amitpatil1825

    lis = [101,121,3231]
    lis2= []
    for i in lis:
    rev = 0
    temp = i
    while i>0:
    rem = i%10
    i//=10
    rev = rev*10+rem
    if temp == rev:
    lis2.append(rev)

    print(max(lis2))


  • sangramdhurve96

    less time consuming code
    arr = [1, 232, 5545455, 909090, 161]
    def isPali(number):
    flag=le=i=0
    c_n = number
    orignal = c_n
    # print(c_n)
    while(c_n>0):
    num = c_n%10
    i =i*10+num
    c_n=c_n//10
    le+=1
    if i==orignal:
    flag=1
    else:
    flag=0
    return flag, le
    length=long_n=0
    for i in range(0, len(arr)):
    flag=isPali(arr[i])
    if flag[0]==1 and flag[1]>length:
    length=flag[1]
    long_n+=arr[i]
    print(long_n)


  • naveen23122k

    def checking(i,rem=0,sum=0):
    save=i
    while i!=0:
    rem=i%10
    sum=sum*10+rem
    i=i//10
    if save==sum:
    return save
    else:
    return 0

    palin=[]
    arr = [1, 232, 5545455, 909090, 161]
    for i in (arr):
    palin.append(checking(i))
    max=palin[0]
    for i in range(1,len(palin)):
    for j in range(i+1):
    if palin[j]>palin[i]:
    max=palin[j]
    print(max)


  • yugander9010

    ls=[1, 232, 5545455, 909090, 161]
    ls2=[]
    for num in ls:
    temp=str(num)
    check=”
    if len(str(num))==1:
    ls2.append(str(num))
    else:
    while num > 0:
    rem = int(num)%10
    check+=str(rem)
    num = int(num)//10
    if check==temp:
    ls2.append(check)
    print(f”Filtered List:{ls2}”)
    print(max(ls2,key=len))


  • yeshuroy48

    def is_palindrome(s):
    n = len(s)
    for i in range(n/2):
    if s[i] != s[n-i-1]:
    return False
    return True
    def find_longest_palindrome(arr):
    longest_palindrome = []
    for number in arr:
    num_arr = [int(digit) for digit in str(number)]
    if is_palindrome and len(num_arr) > len(longest_palindrome):
    longest_palindrome = num_arr
    return int(”.join(map(str,longest_palindrome)))
    arr = [121, 12321, 45654, 67876, 987789, 22, 999]
    longest_palindrome = find_longest_palindrome(arr)
    print(f”longest palindrome :{longest_palindrome}”)


  • prajapatishivamp06

    simple method
    logic : use slice method here
    code:
    a =[123,1121211,2002,731,4000]
    b =[]
    for num in a:
    c=int(str(num)[: :-1])
    if num == c:
    b.append(len(str(num)))

    if b:
    print(max(b))
    else:
    print(‘palidrome is not found’)


  • Harshadip Kamble

    def is_int_value_palendrom(num):
    original=num
    reversed=0
    while num>0:
    last_digit=num%10
    reversed=reversed*10+last_digit
    num=num//10
    return original==reversed
    print(is_int_value_palendrom(121))
    print(is_int_value_palendrom(12321))
    print(is_int_value_palendrom(12345))
    print(is_int_value_palendrom(-121))
    print(is_int_value_palendrom(555554444411111))


  • Harshadip Kamble

    def is_palendrom(num):
    num=str(num)
    i=0
    j=len(num)-1
    while i<=j:
    if num[i]==num[j]:
    i+=1
    j-=1
    else:
    return False
    return True
    def longest_palendrom(array):
    ans=dict()
    for i in array:
    if is_palendrom(i):
    ans[i]=len(str(i))
    my_sorted_dict=dict(sorted(ans.items(), key=lambda item: item[1], reverse=True))
    longest_palindrome_number = list(my_sorted_dict.keys())[0]
    return longest_palindrome_number
    ans=longest_palendrom([1, 232, 5545455, 909090, 161])
    print(ans)