python實(shí)現(xiàn)兩字符串映射
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è)簡單的加密程序。其中str1是函數(shù)str.maketrans(intab,outtab)中的intab,而str2是str.maketrans(intab,outtab)中的outtab。
不過這種加密方法有一個(gè)問題。就是intab與outtab所代表的的字符串的長度必須一致,且各自的字符串中的字符必須唯一,否則解密時(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
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python 實(shí)現(xiàn)Flask中返回圖片流給前端展示
今天小編就為大家分享一篇python 實(shí)現(xiàn)Flask中返回圖片流給前端展示,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python數(shù)據(jù)處理-導(dǎo)入導(dǎo)出excel數(shù)據(jù)
這篇文章主要介紹了Python數(shù)據(jù)處理-導(dǎo)入導(dǎo)出excel數(shù)據(jù),Python的一大應(yīng)用就是數(shù)據(jù)分析了,而數(shù)據(jù)分析中,經(jīng)常碰到需要處理Excel數(shù)據(jù)的情況。這里做一個(gè)Python處理Excel數(shù)據(jù)的總結(jié),需要的小伙伴可以參考一下2022-01-01
error?conda:ProxyError:Conda?cannot?proceed?due?to?an?
這篇文章主要為大家介紹了error conda:ProxyError:Conda cannot proceed due to an error in your proxy configuration解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
python實(shí)現(xiàn)socket+threading處理多連接的方法
今天小編就為大家分享一篇python實(shí)現(xiàn)socket+threading處理多連接的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07

