日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python實(shí)現(xiàn)兩字符串映射_python

作者:AII派森 ? 更新時(shí)間: 2022-12-05 編程語言

python兩字符串映射

題目:

pattern = "abba",s="dog cat cat dog"---->True

pattern = "abba",s="dog cat cat fish"----->False

class Solution:
    def is_pattern_matched(self, pattern:str,s: str) -> bool:
        pattern = list(''.join(pattern))
        s = s.split(" ")
        a = {}
        for i in range(len(pattern)):
            a.update({pattern[i]:s[i]})#update() 方法用于修改/更新當(dāng)前集合/字典,可以添加新的元素或集合到當(dāng)前集合中,如果添加的元素在集合中已存在,則該元素只會(huì)出現(xiàn)一次,重復(fù)的會(huì)忽略。
        # a = zip(pattern,s)
        # a = dict(a)
        for j in range(len(pattern)):
            if s[j] != a[pattern[j]]:
                return False
            else:
                return True
 
pattern = "abba"
s = "dog cat cat dog"
S = Solution()
result = S.is_pattern_matched(pattern,s)
print(result)

python字符映射表和字符替換

python中有一個(gè)內(nèi)建函數(shù)maketrans()可以對(duì)兩個(gè)字符串進(jìn)行字符映射,創(chuàng)建出映射表。

結(jié)構(gòu)如下:

str.maketrans(intab,outtab)

當(dāng)使用該函數(shù)時(shí),將會(huì)把intab中的字符串對(duì)out字符串中的字符進(jìn)行一一對(duì)應(yīng)。

而使用translate()函數(shù)則可以利用映射表字符對(duì)指定字符串的字符進(jìn)行替換。

結(jié)構(gòu)如下:

str.translate(table)

示例:

str1="abcdefghijklmnopqrstuvwxyz"
str2="qwertyuiopasdfghjklzxcvbnm"
table=str.maketrans(str1,str2)
str="sword art online"
print(str.translate(table))#==>lvgkr qkz gfsoft

上面的例子使用了這兩個(gè)函數(shù)寫了一個(gè)簡(jiǎn)單的加密程序。其中str1是函數(shù)str.maketrans(intab,outtab)中的intab,而str2是str.maketrans(intab,outtab)中的outtab。

不過這種加密方法有一個(gè)問題。就是intab與outtab所代表的的字符串的長(zhǎng)度必須一致,且各自的字符串中的字符必須唯一,否則解密時(shí)容易出錯(cuò)。

示例:

str1="abcdefghijklmnopqrstuvwxyz"
str2="qwertyuiopasdfghjklzxcvbnm"
table1=str.maketrans(str1,str2)
table1_1=str.maketrans(str2,str1)
str="sword art online"
jiami=str.translate(table1)
jiemi=jiami.translate(table1_1)
print(jiami)#==>lvgkr qkz gfsoft
print(jiemi)#==>sword art online

原文鏈接:https://blog.csdn.net/weixin_42698464/article/details/122661481

欄目分類
最近更新