python字典序问题实例

WBOY
发布: 2016-06-06 11:32:45
原创
1688 人浏览过

本文实例讲述了python字典序问题,分享给大家供大家参考。具体如下:

问题描述:

将字母从左向右的次序与字母表中的次序相同,且每个字符最大出现一次..例如:a,b,ab,bc,xyz等都是升序的字符串.现对字母表A产生的所有长度不超过6的升序字符串按照字典充排列并编码如下:

1 2 .. 26 27 28 ...
a b .. z ab ac ..

对一个升序字符串,迅速计算出它在上述字典中的编码。

实现代码如下:

import string
all_letter = string.ascii_lowercase
def gen_dict():
  result = {}
  list_num_one = [ a_letter for a_letter in all_letter ]
  list_num_two = [ i + j for i in all_letter for j in all_letter[all_letter.find(i)+1:]]
  list_num_three = [ i + j + k for i in all_letter 
           for j in all_letter[all_letter.find(i)+1:]
           for k in all_letter[all_letter.find(j)+1:]]
  list_num_four = [ i + j + k + l for i in all_letter 
           for j in all_letter[all_letter.find(i)+1:]
           for k in all_letter[all_letter.find(j)+1:]
           for l in all_letter[all_letter.find(k)+1:]]
  list_num_five = [ i + j + k + l + m for i in all_letter 
           for j in all_letter[all_letter.find(i)+1:]
           for k in all_letter[all_letter.find(j)+1:]
           for l in all_letter[all_letter.find(k)+1:]
           for m in all_letter[all_letter.find(l)+1:]]
  list_num_six = [ i + j + k + l + m + n  for i in all_letter
      for j in all_letter[all_letter.find(i)+1:]
      for k in all_letter[all_letter.find(j)+1:]
      for l in all_letter[all_letter.find(k)+1:]
      for m in all_letter[all_letter.find(l)+1:]
      for n in all_letter[all_letter.find(m)+1:]
      ]
  for key,value in enumerate(list_num_one + list_num_two + list_num_three + list_num_four + list_num_five + list_num_six):
    result.setdefault(key+1,value)
  return result
  
my_dict = gen_dict()
value_to_get = 'abcdef'
for key,value in my_dict.iteritems():
  if value == value_to_get:
    print key

登录后复制

结果:83682  

即abcdef在字典中的编码。

希望本文所述对大家的Python程序设计有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!