【python】判断两个字符串的包含关系?

Python016

【python】判断两个字符串的包含关系?,第1张

题目:给定由字母组成的字符串s1和s2,其中,s2中字母的个数少于s1,如何判断s1是否包含s2?

分析:哈希法。

code:

str1 = 'aaaabbce'

str2 = 'abcbbaaad'

list1 = list(str1)

list2 = list(str2)

i = 0

hashTable1 = dict()

while i <len(str1):

    if list1[i] not in hashTable1:

        hashTable1[list1[i]] = 0

    i += 1

i = 0

hashTable2 = dict()

while i <len(str2):

    if list2[i] not in hashTable2:

        hashTable2[list2[i]] = 0

    i += 1

count = 0

for k, v in hashTable1.items():

    if k in hashTable2:

        count += 1

    else:

        print("不包含")

        break

程序运行结果:

不包含

python中,缩进表达每个模块,或者语句作用范围,也就是你所谓的所属关系。最短的缩进对较长的有包含关系,缩进前后没有要求,但是每个脚本应具有相同的缩进长度(TAB或者相同个数的空格)。缩进就是模块的表示,不用任何符号。

用C来对比:C中模块是用{}表示的,python缩进就代替了{}。

一般的,python模块有以下格式:

fuction1:[缩进]函数1作用范围......fuction_2:[缩进]函数2作用范围...... # 定义函数def fuction():[缩进]函数内容......