算法设计实验一 :异序词检测的三种方法 python实现代码

具体所使用的方法可参考Turing的《python数据结构与算法分析》或搜索其他资料文章。

清点法

def anagramSolution(a,b):
    if len(a)!=len(b):
        return False
    else:
        a = a.lower()
        b = b.lower()
        bb = list(b)
        lenth = len(a)
        pos1 = 0
        flag1 = True
        while pos1 < lenth and flag1:
            pos2 = 0
            flag2 = False
            while pos2 < lenth and not flag2:
                if a[pos1] == bb[pos2]:
                    flag2 = True
                    bb[pos2] = None
                else:
                    pos2 = pos2 + 1
            if not flag2:
                flag1 = False
            pos1 = pos1+1
        return flag1

str1 = str(input('please input the first word:'))
str2 = str(input('please input the second word:'))
if anagramSolution(str1, str2):
    print('anagram')
else:
    print('not anagram')

结果截图:

排序法

def anagramSolution2 (a,b):
    #第一个if判断两个字符串是否为0
    if len(a)!=len(b):
        return False
    else:
        #把字符串里面的大写字母转为小写字母
        a = a.lower()
        b = b.lower()
        aa = list(a)
        bb = list(b)

        aa.sort()
        bb.sort()
        lenth = len(a)
        flag1 = True
        pos = 0
        while pos<lenth and flag1:
            if aa[pos] != bb[pos]:
                flag1 = False
            pos = pos + 1
        return flag1
str1 = str(input('please enter the first string: '))
str2 = str(input('please enter the second string: '))

print('anagram is %s' % anagramSolution2(str1, str2))

 

结果截图:

计数法

def anagramSolution3(a,b):
    if len(a)!=len(b):
        return False
    else:
        a = a.lower()
        b = b.lower()
        numa = [0]*26
        numb = [0]*26
        lenth = len(a)
        for i in range(lenth):
            pos = ord(a[i]) - ord('a')
            numa[pos] = numa[pos] + 1
        
        for i in range(lenth):
            pos = ord(b[i]) - ord('a')
            numb[pos] = numb[pos] + 1
        
        pos2 = 0
        flag = True
        while pos2<26 and flag:
            if numa[pos2] != numb[pos2]:
                flag = False
            pos2 = pos2+1
        
        return flag

str1 = str(input('please enter the first string: '))
str2 = str(input('please enter the second string: '))

print('anagram is %s' % anagramSolution3(str1, str2))

 

结果截图:

其中,清点法时间复杂度为O(n^2)。

排序法时间复杂度取决于排序算法,如果用时间复杂度最低的排序算法,其时间复杂度为O(nlogn)。

计数法是以空间换取时间的方法,时间复杂度为O(n)。

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值