我需要撰寫一個根據以下條件回傳 True/False 的程式:
- 如果字串中的小寫 'g' 相鄰有另一個 'g',則它是“happy”,例如“gg”。然后,
True如果給定字串中的所有 g 都滿意,則回傳。 - 否則,回傳
False
所需的輸出是:
string: xggt
output: True
string: abgsx
output: False
string: xxggygxx
output: False
我對這個問題有點迷茫,正在努力解決這個問題。誰能幫助我并解釋如何達到預期的結果?
我當前的代碼是:
s=input("Enter string: ")
happy = true
sad = false
while s <='g':
print ("Happy?",sad)
elif s <='gg':
print("Happy?", happy)
uj5u.com熱心網友回復:
在查找字串中的模式時,使用re庫非常有用。因此,在這種情況下,您需要搜索以下模式之一:
- “G”
- “……Xg”
- “gX……”
- “……XgX……”
其中 X 是除“g”之外的任何東西。因此,使用 re 庫將是:
import re
s=input("Enter string: ")
res = bool(re.search(r"(^g$|[^g]g$|^g[^g]|[^g]g[^g])", s))
print("Happy?", res)
uj5u.com熱心網友回復:
執行此操作的經典方法是使用正則運算式,但我將展示如何使用itertools.groupby:
>>> from itertools import groupby
>>> def is_happy(s):
... """Returns whether all 'g's are next to at least one other 'g'."""
... return all(sum(1 for _ in x) > 1 for g, x in groupby(s, "g".__eq__) if g)
...
>>> is_happy("xggt")
True
>>> is_happy("abgsx")
False
>>> is_happy("xxggygxx")
False
讓我們分解各個部分:
for g, x in groupby(s, "g".__eq__)
groupbys基于分組函式將可迭代(在本例中)轉換為“組”。
g在此迭代中是 的結果"g".__eq__,即該組是否屬于gs。 x是實際組(即 的子串s)。
if g
最后if g的意思是我們將跳過任何為假的g, x對g(即任何不只是gs 的組)。
sum(1 for _ in x) > 1
這告訴我們該組是否有多個元素。如果x是一個字串,我們可以只使用它len,但它_grouper是一個沒有實作的一次性可迭代物件__len__,所以我們使用sum它來迭代它并為每個字符計數 1。
all(...)
告訴我們迭代中的所有元素是否都為真——所有組都g長于 1 個元素嗎?
uj5u.com熱心網友回復:
使用正則運算式可能有點難以閱讀和理解,但效率更高。這是一種搜索字母實體g然后查找前面或后面的實作g。如果沒有找到,則回傳不滿意的結果:
s = input("Enter string: ")
happy = True
for ctr, letter in enumerate(s):
if letter == "g":
if ctr > 0 and s[ctr - 1] == "g":
pass
elif ctr < (len(s) - 1) and s[ctr 1] == "g":
pass
else:
# unhappy
happy = False
break
print(s, happy)
uj5u.com熱心網友回復:
這是一種通過檢查單詞中每個“g”之前和之后的索引的方法。
my_inputs = ["xggt", "abgsx", "xxggygxx"]
for _input in my_inputs:
state = False
for i, char in enumerate(_input):
if char == "g":
if i > 0 and _input[i-1] == "g" or i < len(_input)-1 and _input[i 1] == "g":
state = True
else:
state = False
print(f"string: {_input}\noutput: {state}\n")
輸出:
string: xggt
output: True
string: abgsx
output: False
string: xxggygxx
output: False
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466211.html
標籤:Python python-3.x
下一篇:日期時間的格式字串無效
