发布于 2015-03-06 21:56:58 | 176 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python多线程编程,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


本文实例讲述了Python查找相似单词的方法。分享给大家供大家参考。具体分析如下:

问题:

给你一个单词a,如果通过交换单词中字母的顺序可以得到另外的单词b,那么定义b是a的兄弟单词。现在给你一个字典,用户输入一个单词,让你根据字典找出这个单词有多少个兄弟单词。

Python代码如下:

from itertools import tee,izip
from collections import defaultdict
def pairwise(iterable):
  a, b = tee(iterable)
  for elem in b:
    break
  return izip(a, b)
buf_array=[]
buf_no={}
key_from_id=0
def add_to_buf(word):
  global key_from_id,buf_array
  if len(word)==1:
    pass
    #TODO
  for pos,pair in enumerate(pairwise(word)):
    if len(buf_array)<pos+1:
      buf_array.append(defaultdict(set))
    pos_dict=buf_array[pos]
    key=list(pair)
    key.sort()
    key="".join(key)
    if key not in buf_no:
      buf_no[key]=key_from_id
      key_from_id+=1
    key=buf_no[key]
    pos_dict[key].add(word)
def find_in_buf(word):
  global key_from_id,buf_array
  if len(word)==1:
    pass
    #TODO
  exist = []
  for pos,pair in enumerate(pairwise(word)):
    if len(buf_array)<pos+1:
      return  
    pos_dict=buf_array[pos]
    key=list(pair)
    key.sort()
    key="".join(key)
    if key not in buf_no:
      continue
    key=buf_no[key]
    if key not in pos_dict:
      continue
    exist.append(pos_dict[key])
  count_dict=defaultdict(int)
  for i_set in exist:
    for i in i_set:
      count_dict[i]+=1
  result=[]
  min_match = len(word)-3
  for k,v in count_dict.iteritems():
    if v>=min_match:
      result.append(k)
  return result
add_to_buf("1234")
add_to_buf("ABCD")
add_to_buf("CABD")
print find_in_buf("ACBD")


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务