longest python code code example

Example 1: python lcs length

def lcs(X, Y):
  
    n = len(Y)
    m = len(X)
    
    L = [[None]*(n + 1) for i in range(m + 1)]
    for i in range(m + 1): 
        for j in range(n + 1): 
            if i == 0 or j == 0 : 
                L[i][j] = 0
            elif X[i-1] == Y[j-1]: 
                L[i][j] = L[i-1][j-1]+1
            else: 
                L[i][j] = max(L[i-1][j], L[i][j-1])
                
    return L[m][n]

Example 2: how to find the longest string python

max(a_list, key=len)

Example 3: Write a python program to find the longest words.

def longestword(filename):
	with open(filename,'r+') as f:
		words = f.read().split()
		max_len_word = max(words,key=len)
		max_len = len(max(words,key=len))		
		print('maximum lenth word in file :',max_len_word)
		print('lenth is : ',max_len)

longestword('file1.txt')

or 

def longest_word(filename):
    with open(filename, 'r') as infile:
              words = infile.read().split()
    max_len = len(max(words, key=len))
    return [word for word in words if len(word) == max_len]

print(longest_word('file1.txt'))