python實現兩字符串映射
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() 方法用于修改/更新當前集合/字典,可以添加新的元素或集合到當前集合中,如果添加的元素在集合中已存在,則該元素只會出現一次,重復的會忽略。 # 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中有一個內建函數maketrans()可以對兩個字符串進行字符映射,創(chuàng)建出映射表。
結構如下:
str.maketrans(intab,outtab)
當使用該函數時,將會把intab中的字符串對out字符串中的字符進行一一對應。
而使用translate()函數則可以利用映射表字符對指定字符串的字符進行替換。
結構如下:
str.translate(table)
示例:
str1="abcdefghijklmnopqrstuvwxyz" str2="qwertyuiopasdfghjklzxcvbnm" table=str.maketrans(str1,str2) str="sword art online" print(str.translate(table))#==>lvgkr qkz gfsoft
上面的例子使用了這兩個函數寫了一個簡單的加密程序。其中str1是函數str.maketrans(intab,outtab)中的intab,而str2是str.maketrans(intab,outtab)中的outtab。
不過這種加密方法有一個問題。就是intab與outtab所代表的的字符串的長度必須一致,且各自的字符串中的字符必須唯一,否則解密時容易出錯。
示例:
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
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
error?conda:ProxyError:Conda?cannot?proceed?due?to?an?
這篇文章主要為大家介紹了error conda:ProxyError:Conda cannot proceed due to an error in your proxy configuration解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07python實現socket+threading處理多連接的方法
今天小編就為大家分享一篇python實現socket+threading處理多連接的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07