Home > Enterprise >  how to reverse returned valuve
how to reverse returned valuve

Time:06-16

write a function named longestCommonSuffix to find the longest common suffix among numbers in a non-empty list of numbers, nums. If there is no common suffix, return “Not found”. Suffix here means the part to the left from the end of the numbers. For example, 123 has 3 suffixes: 3, 23, and 123 Example 1: Input: nums = [123, 43123, 523] Output: 23

I have used the following code but i always get none as the output please help!

def longestCommonSuffix(nums):
a = []
for j in nums:
    a.append(str(j))
print(a)
b = a[::-1]
print(b)
for i in range(len(a[0])):
    if b[1] == b[0]:
        if b[::i][0] in b[0:len(b[0][::i])][1]:
            print(b[::i][1])

CodePudding user response:

Please change the question title to be matched with the content.

Here I post a simple code without error handling.
You can check below two questions to understand the logic of the code.

How to find length of digits in an integer?
Find common elements in list of lists

import math

def calc_suffixes(num):
    digits = int(math.log10(num)) 1
    return [num % 10**(ii 1) for ii in range(digits)]

def find_largest_common_suffix(list_num):
    list_list_suffixes = [calc_suffixes(num) for num in list_num]
    set_common_suffixes = set.intersection(*map(set, list_list_suffixes))
    return max(set_common_suffixes)

find_largest_common_suffix([123, 43123, 523])

CodePudding user response:

def function(nums):
    #making every element into string data type and reversing it
    nums = [str(i)[::-1] for i in nums]
    count = 0
    #finding the min length of the element in entire array, because it will be the maximum length possible
    min_length = min([len(i) for i in nums])
    ans = -1
    for i in range(min_length):
        count = 0
        for j in range(len(nums)-1):
            if(nums[j][:i]!=nums[j 1][:i]):
                count =1
                break
        if(count):
            break
    if(ans==-1):
        return "No"
    return nums[0][:i][::-1]

Time Complexity = O(min length of the array element * length of the array) = O(m * n)

Please let me know if an easier solution or if any test case is showing the wrong output.

Vote for the solution, if you find it useful.

  • Related