This article example describes how Python solves whether all subsequences are palindromes for a given string. Shared for your reference, as follows:
Question:
Given a string, get all the subsequences and determine whether they are palindromes or not
Thoughts:
Just iterate over the string and slice it
Here are the specific implementations:
#!usr/bin/env python # -*- coding:utf-8 -*- ''''' __AUthor__:Yishui Cold City Function: Finds all palindromic subsequences for a given string ''' def is_huiwen(one_str_list): ''''' Input a list of strings to determine if they are palindromic sequences ''' if len(one_str_list)==1: return True else: half=len(one_str_list)/2 if len(one_str_list)%2==0: first_list=one_str_list[:half] second_list=one_str_list[half:] else: first_list=one_str_list[:half] second_list=one_str_list[half+1:] if first_list==second_list[::-1]: return True else: return False def get_list_all_sub_list(num_list): ''' Input a list, return all the sub-lists of the list, the empty list defined here does not belong to the sub-list, so: the minimum length of the sub-list is 1 ''' if len(num_list)==1: return [num_list] sub_list=get_list_all_sub_list(num_list[:-1]) extra=num_list[-1:] temp_list=[] for one in sub_list: temp_list.append(one+extra) return sub_list+temp_list def slice_func(one_str): ''''' ''' result_list=[] for i in range(1,len(one_str)): result_list.append(one_str[:i]) result_list.append(one_str[i:]) result_list+=list(one_str) result_list.append(one_str) return list(set(result_list)) def main_func2(): ''''' Main Calling Functions ''' str_list=['abdc','abba'] for one_str in str_list: result_list=slice_func(one_str) print '-----------------------------------------------' for one in result_list: if is_huiwen(list(one)): print one+'It's a palindrome sequence' def main_func1(): ''''' Main Calling Functions ''' str_list=['abdc','abba'] for one_str in str_list: one_str_list=list(one_str) one_all_sub_list=get_list_all_sub_list(one_str_list) print '------------------------------------------------' print one_all_sub_list for one in one_all_sub_list: if is_huiwen(one): print ''.join(one)+'It's a palindrome sequence' if __name__ == '__main__': print "I test results:" main_func2()
The results are as follows:
Readers interested in more Python related content can check out this site's topic: theSummary of Python function usage tips》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques》
I hope that what I have said in this article will help you in Python programming.