我正在撰寫一個程式來列印出短語中最小的單詞。輸出應該給我單詞“I”,但它卻列印出單詞“am”。我怎樣才能解決這個問題?請幫忙,我是 Python 新手
#Given a string 'phrase' consisting of some words separated
# by some number of spaces, return the
# smallest word in the string.
def word_length(phrase):
splitphrase = phrase.split(" ")
min_word = ''
for i, element in enumerate(splitphrase):
if i < len(splitphrase)-1 and (len(element) <= len((splitphrase[i 1]))):
min_word = element
print(min_word)
word_length("hello I am Sam and am tall")
uj5u.com熱心網友回復:
我將把我的代碼放在下面,然后解釋我所做的更改:
def word_length(phrase):
splitphrase = phrase.split(" ")
min_word = splitphrase[0] #setting default value as first word
for element in (splitphrase): #for each word in the list
if len(element) < len(min_word): #if the word is shorter than our current min_word
min_word = element #redefine min_word if the current word is shorter
print(min_word)
word_length("hello I am Sam and am tall")
輸出:
I
與您的代碼類似,我們首先使用該split()函式將句子分解為串列中的單詞。
要開始尋找最小的單詞,我們可以將我們定義min_word為最初是splitphrase[0]我們的默認值。
為了確定串列中的其他單詞是否是min_word,在遍歷串列中的每個單詞時,如果我們在串列中迭代的單詞的長度小于 current 的長度min_word,我們重新定義min_word為當前元素。
我希望這有幫助!如果您需要任何進一步的幫助或澄清,請告訴我!
uj5u.com熱心網友回復:
- 可能的最大字長是句子的長度
- 我檢查每個單詞是否小于最大長度
- 如果它更小,我重新分配 min_word 和 min_word_length 的值
def word_length(phrase):
splitphrase = phrase.split(" ")
max_word_lenght = len(phrase)
for el in splitphrase:
if len(el) <= max_word_lenght:
max_word_lenght = len(el)
min_word = el
print(min_word)
word_length("hello I am Sam and am tall")
如果您是 python 新手,我建議您學習一個除錯工具,以便您更好地了解程式的流程。如果您使用命令列,則可能是 PDB ( https://realpython.com/python-debugging-pdb/ )。
如果你使用 IDE(Spyder、VS、PyTorch),它們應該有一個內置的除錯器
uj5u.com熱心網友回復:
像這樣怎么樣:
def word_length(phrase):
sw = (words := phrase.split())[0]
for word in words[1:]:
if len(word) < len(sw):
sw = word
return sw
print(word_length("hello I am Sam and am tall"))
筆記:
如果短語是空字串或無,這將失敗。您還需要 Python 3.8
uj5u.com熱心網友回復:
試試這個簡單的解決方案,我唯一更改的代碼是檢查每個單詞。此代碼檢查,
- 如果 min_word 變數尚未設定,則意味著我們正在使用第一個單詞
- 或者如果當前單詞比前一個 min_word 短
def word_length(phrase):
splitphrase = phrase.split(" ") # split the phrase into each individual word
min_word = '' # store the shortest word we've found yet
for _, element in enumerate(splitphrase): # enumerate over each individual ord
if min_word == '' or len(element) < len(min_word): # check if we haven't already set the min_word or this word is smaller than the current min_word
min_word = element
print(min_word)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/432285.html
