2007-06-14

 

Python Cook 1.8 判断字符串内是否包含指定集合的字符

需求:

给定一个字符集合,需要判断在特定字符串内,是否包含该集合的字符.

讨论:

最简单,直观,效率最高的算法就是使用循环迭代.而且还具有通用性,不仅适用与字符串,也适用与其它序列.
 def containsAny(seq, aset):
""" Check whether sequence seq contains ANY of the items in aset. """
for c in seq:
if c in aset: return True
return False

当然,也可以使用更高级的办法,用Python提供的迭代工具:

import itertools
def containsAny(seq, aset):
for item in itertools.ifilter(aset._ _contains_ _, seq):
return True
return False

另:对于和集合相关的问题,都可以使用集合来解决.对于我们需求,可以使用下面的方式来实现:

def containsAny(seq, aset):
return bool(set(aset).intersection(seq))

这个方法返回了两个集合的交集,也就是说,两个集合中所有的元素都进行了判断,从效率上讲,没有上面提供的两种方法好.
然而,如果需求是需要判断集合内的字符是否都包含在字符串内,使用集合提供的方法会更方便一些:

def containsAll(seq, aset):
""" Check whether sequence seq contains ALL the items in aset. """
return not set(aset).difference(seq)

如果需求是判读字符串内是否只包含集合内的字符,可以用下面的算法:

def containsOnly(seq, aset):
""" Check whether sequence seq contains ONLY items in aset. """
for c in seq:
if c not in aset: return False
return True
相关说明:

intersection(...)
    Return the intersection of two sets as a new set.
   
    (i.e. all elements that are in both sets.)

difference(...)
    Return the difference of two sets as a new set.
   
    (i.e. all elements that are in this set but not the other.)

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?