我不知道你是否熟悉 P 語言,或者它是否只是在我的國家才知道的東西。基本上,每次在單詞中遇到元音時,都會將元音替換為相同的元音 p 元音。
因此,“家”在 p 語言中將是“hopomepe”。現在我的任務是破譯 p 語言并將用 p 語言撰寫的句子恢復正常。
p = str(input())
for letter in range(1, len(p)):
if p[letter]=='.':
break
if p[letter-1]==p[letter 1] and p[letter]=='p':
p = p[:letter-1] p[letter 1:]
print(p)
到目前為止,這是我的代碼,除了我不知道如何使它適用于雙元音,例如蝎子(scoporpiopion)中的“io”。
此外,當句子以元音開頭時,此代碼不適用于該元音。例如,使用我的代碼將“Apan epelepephapant”變為“Apan大象”。
當我的代碼不以 '.' 結尾時,我的代碼會因字串索引超出范圍而崩潰。但是每次當我沒有它時它都會崩潰,如果是“。” 案件。
TLDR;我怎樣才能更改我的代碼,使其適用于雙元音和我的句子開頭。
編輯:為了澄清,就像在我的例子中一樣,組合元音應該算作 1 個元音。Scorpion 是 Scoporpiopion 而不是 Scoporpipiopon,boat 是 boapoat,boot 是 boopoot,......
uj5u.com熱心網友回復:
您可以使用正則運算式來做到這一點:
import re
def decodePLanguage(p):
return re.subn(r'([aeiou] )p\1', r'\1', p, flags=re.IGNORECASE)[0]
In [1]: decodePLanguage('Apan epelepephapant')
Out[1]: 'An elephant'
In [2]: decodePLanguage('scoporpiopion')
Out[2]: 'scorpion'
這使用re.subn函式來替換所有正則運算式匹配。
在 中r'([aeiou] )p\1',該[aeiou] 部分連續匹配多個元音,并\1確保您在p.
thenr'\1'用于將整個匹配替換為第一個元音組。
uj5u.com熱心網友回復:
編輯:作業代碼
def decipher(p):
result = ''
while len(p) > 2:
# first strip out all the consecutive consonants each iteration
idx = 0
while p[idx].lower() not in 'aeiou' and idx < len(p) - 2:
idx = 1
result = p[:idx]
p = p[idx:]
# if there is any string remaining to process, that starts with a vowel
if len(p) > 2:
idx = 0
# scan forward until 'p'
while p[idx].lower() != 'p':
idx = 1
# sanity check
if len(p) < (idx*2 1) or p[:idx].lower() != p[idx 1:2*idx 1].lower():
raise ValueError
result = p[:idx]
p = p[2*idx 1:]
result = p
return result
在您的示例輸入中'Apan epelepephapant',您比較'A' == 'a'并得到False。看來您要比較'a' == 'a',即str.lower()每個的 。
它也似乎不前,如果字符檢查p,后p是元音; 也就是說,如果您遇到字串hph,如所寫,您的函式會將其解密為簡單的h。
早期版本的代碼如下:
def decipher(p):
while len(p) > 2:
if p[0].lower() in 'aeiou' and p[0].lower() == p[2].lower() and p[1] == 'p':
result = p[0]
p = p[3:]
else:
result = p[0]
p = p[1:]
result = p
return result
稱為例如
p = str(input())
print(decipher(p))
uj5u.com熱心網友回復:
由于@Kolmar 已經給出了正則運算式解決方案,我將添加一個沒有正則運算式的解決方案
為了幫助思考這個問題,我將首先向您展示我將常規字串編碼為 p 語言的解決方案。在這種方法中,我根據字串中的字符是否為元音使用itertools.groupby(). 此函式將具有相同鍵的連續元素分組在同一組中。
def p_encode(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
s_groups = [(k, list(v)) for k, v in itertools.groupby(s, lambda c: c.lower() in vowels)]
# For scorpion, this will look like this:
# [(False, ['s', 'c']),
# (True, ['o']),
# (False, ['r', 'p']),
# (True, ['i', 'o']),
# (False, ['n'])]
p_output = []
# Now, we go over each group and do the encoding for the vowels.
for is_vowel_group, group_chars in s_groups:
p_output.extend(group_chars) # Add these chars to the output
if is_vowel_group: # Special treatment for vowel groups
p_output.append("p")
p_output.extend(c.lower() for c in group_chars)
return "".join(p_output)
我添加了一個串列理解來定義s_groups以向您展示它是如何作業的。可以跳過串列理解,直接迭代for is_vowel_group, group_chars in itertools.groupby(s, lambda c: c.lower() in vowels)
現在,為了解碼它,我們可以反向做一些類似的事情,但這次手動進行分組,因為p當它們位于元音組的中間時,我們需要以不同的方式處理它們。
我建議您在迭代時不要修改字串。充其量,您將撰寫一些難以理解的代碼。在最壞的情況下,您會遇到錯誤,因為回圈將嘗試迭代比實際存在的索引更多的索引。
此外,您迭代1..len(p),然后嘗試訪問p[i 1]. 在最后一次迭代中,這將拋出一個IndexError. 并且因為您希望將重復的元音算作一個單獨的組,所以這行不通。您必須將元音和非元音分開分組,然后將它們連接成一個字串。
def p_decode(p):
vowels = {'a', 'e', 'i', 'o', 'u'}
p_groups = []
current_group = None
for c in p:
if current_group is not None:
# If the 'vowelness' of the current group is the same as this character
# or ( the current group is a vowel group
# and the current character is a 'p'
# and the current group doesn't contain a 'p' already )
if (c.lower() in vowels) == current_group[0] or \
( current_group[0] and
c.lower() == 'p' and
'p' not in current_group[1]):
current_group[1].append(c) # Add c to the current group
else:
current_group = None # Reset the current group to None so you can make it later
if current_group is None:
current_group = (c.lower() in vowels, [c]) # Make the current group
p_groups.append(current_group) # Append it to the list
# For scorpion => scoporpiopion
# p_groups looks like this:
# [(False, ['s', 'c']),
# (True, ['o', 'p', 'o']),
# (False, ['r', 'p']),
# (True, ['i', 'o', 'p', 'i', 'o']),
# (False, ['n'])]
p_output = []
for is_vowel_group, group_chars in p_groups:
if is_vowel_group:
h1 = group_chars[:len(group_chars)//2] # First half of the group
h2 = group_chars[-len(group_chars)//2 1:] # Second half of the group, excluding the p
# Add the first half to the output
p_output.extend(h1)
if h1 != h2:
# The second half of this group is not repeated characters
# so something in the input was wrong!
raise ValueError(f"Invalid input '{p}' to p_decode(): vowels before and after 'p' are not the same in group '{''.join(group_chars)}'")
else:
# Add all chars in non-vowel groups to the output
p_output.extend(group_chars)
return "".join(p_output)
現在,我們有:
words = ["An elephant", "scorpion", "boat", "boot", "Hello World", "stupid"]
for w in words:
p = p_encode(w)
d = p_decode(p)
print(w, p, d, sep=" | ")
這給出了(美化我的):
| 單詞 | 編碼 | 解碼 |
|---|---|---|
| 一頭大象 | Apan epelepephapant | 一頭大象 |
| 蝎 | 蝎子 | 蝎 |
| 船 | 船 | 船 |
| 開機 | 靴子 | 開機 |
| 你好,世界 | 赫佩羅波世界 | 你好,世界 |
| 愚蠢的 | 愚蠢的 | 愚蠢的 |
Also, words that aren't actually encoded correctly (such as "stupid") throw a ValueError
>>> p_decode("stupid")
ValueError: Invalid input 'stupid' to p_decode(): vowels before and after 'p' are not the same in group 'upi'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/336994.html
上一篇:Python字串操作{_teststr[2:12:-1])}
下一篇:lua拆分字串并保存在lua表中
