我被要求:
撰寫一個函式odds(data),它接受一個整數串列,資料作為引數,并回傳一個新串列,其中只包含資料中的奇數元素,即那些不能被2整除的元素。您的代碼不得使用 for 或 while,也不得匯入任何內容。
這是我當前的代碼:
def odds(data):
"""Returns a new list that contains just the odd elements from the data"""
odd_nums = []
if len(data) == 1:
return []
if data[0] % 2 != 0:
odd_nums.append(data[0])
return odds(data[1:])
測驗代碼:
print(odds(\[0, 1, 12, 13, 14, 9, -11, -20\]))
---\> \[1, 13, 9, -11\]
我不確定如何遞回地繼續添加到odd_nums 串列中。
uj5u.com熱心網友回復:
def odds(data):
if not data:
return []
head = [ data[0] ] if data[0]%2==1 else []
if len(data)>1:
return head odds (data[1:])
else:
return head
print(odds([0, 1, 12, 13, 14, 9, -11, -20]))
你幾乎擁有它。只需合并串列即可。潛在的空串列很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452120.html
上一篇:將CSV轉換為字典字典
