问题:
给定一个字符集合,需要判断在特定字符串内,是否包含该集合的字符.
解决方法:
最简单,直观,效率最高的算法就是使用循环迭代.而且还具有通用性,不仅适用与字符串,也适用与其它序列.
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.)
分享到:
相关推荐
PythonCookbook3高清.pdf
这是 Python Cookbook 英文版的,需要的拿走吧
绍了Python应用在各个领域中的一些使用技巧和方法,从最基本的字符、文件序列、字典和排序,到进阶的面向对象编程、数据库和数据持久化、XML处理和Web编程,再到比较高级和抽象的描述符、装饰器、元类、迭代器和生成...
Modern Python Cookbook
Python Cookbook.pdf
Python Cookbook(第3版)中文版.pdf 极清PDF
Python Cookbook, 2nd Edition, Python Cookbook, 2nd Edition, Python Cookbook, 2nd Edition
python cookbook 3th python cookbook 3th python cookbook 3th python cookbook 3th
PythonCookbook.zip
python cookbook(第3版)高清中文完整版
python cookbook(第3版)高清中文完整版.pdf,作者: David Beazley, Brian K. Jones 译者: 熊能 版本: 第3版 出版社: O’Reilly Media, Inc. 出版日期: 2013年5月08日 Copyright © 2013 David Beazley and ...
Python CookBook 3rd Edition, epub type file
Modern Python Cookbook 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开
python cookbook 英文 python cookbook 英文
这本独特的食谱包含了用Python 3.3编写和测试的实用食谱,适合有经验的Python程序员,他们希望专注于现代工具和习惯用法。
Python Cookbook(第三版)中文,Python Cookbook(第三版)中文,Python Cookbook(第三版)中文
python cookbook 中文版,欢迎python爱好者进行下载,谢谢
《Python Cookbook》第二版英文版的epub格式,可以用移动设备或者kindle等电纸书阅读
python cook book 3th 中文版及英文版。 这本书的目标读者是那些想深入理解 Python 语言机制和最新编程技能的资深程序员。很多讨论都是标准库,框架和应用程序使用到的高级技术。... --- 摘至 python cookbook 3th
Python Cookbook.chm是一本全面的、详尽的Python英文教程。