当前位置:Gxlcms > Python > Python针对给定字符串求解所有子序列是否为回文序列的方法

Python针对给定字符串求解所有子序列是否为回文序列的方法

时间:2021-07-01 10:21:17 帮助过:17人阅读

这篇文章主要介绍了Python针对给定字符串求解所有子序列是否为回文序列的方法,涉及Python针对字符串的遍历、判断、运算相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python针对给定字符串求解所有子序列是否为回文序列的方法。分享给大家供大家参考,具体如下:

问题:

给定一个字符串,得到所有的子序列,判断是否为回文序列

思路:

对字符串遍历切片即可

下面是具体实现:

  1. #!usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. '''''
  4. __AUthor__:沂水寒城
  5. 功能:对指定字符串寻找所有回文子序列
  6. '''
  7. def is_huiwen(one_str_list):
  8. '''''
  9. 输入一个字符串列表,判断是否为回文序列
  10. '''
  11. if len(one_str_list)==1:
  12. return True
  13. else:
  14. half=len(one_str_list)/2
  15. if len(one_str_list)%2==0:
  16. first_list=one_str_list[:half]
  17. second_list=one_str_list[half:]
  18. else:
  19. first_list=one_str_list[:half]
  20. second_list=one_str_list[half+1:]
  21. if first_list==second_list[::-1]:
  22. return True
  23. else:
  24. return False
  25. def get_list_all_sub_list(num_list):
  26. '''
  27. 输入一个列表,返回该列表所有的子列表,这里定义的空列表不属于子列表,故:子列表最小长度为1
  28. '''
  29. if len(num_list)==1:
  30. return [num_list]
  31. sub_list=get_list_all_sub_list(num_list[:-1])
  32. extra=num_list[-1:]
  33. temp_list=[]
  34. for one in sub_list:
  35. temp_list.append(one+extra)
  36. return sub_list+temp_list
  37. def slice_func(one_str):
  38. '''''
  39. '''
  40. result_list=[]
  41. for i in range(1,len(one_str)):
  42. result_list.append(one_str[:i])
  43. result_list.append(one_str[i:])
  44. result_list+=list(one_str)
  45. result_list.append(one_str)
  46. return list(set(result_list))
  47. def main_func2():
  48. '''''
  49. 主调用函数
  50. '''
  51. str_list=['abdc','abba']
  52. for one_str in str_list:
  53. result_list=slice_func(one_str)
  54. print '-----------------------------------------------'
  55. for one in result_list:
  56. if is_huiwen(list(one)):
  57. print one+'是回文序列'
  58. def main_func1():
  59. '''''
  60. 主调用函数
  61. '''
  62. str_list=['abdc','abba']
  63. for one_str in str_list:
  64. one_str_list=list(one_str)
  65. one_all_sub_list=get_list_all_sub_list(one_str_list)
  66. print '------------------------------------------------'
  67. print one_all_sub_list
  68. for one in one_all_sub_list:
  69. if is_huiwen(one):
  70. print ''.join(one)+'是回文序列'
  71. if __name__ == '__main__':
  72. print "脚本之家测试结果:"
  73. main_func2()

结果如下:

相关推荐:

python字符串如何转为二维数组

以上就是Python针对给定字符串求解所有子序列是否为回文序列的方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行