[英]writing odd number in a list python
這是我的家庭作業的一部分,我接近最后的答案,但尚未完成。 我需要編寫一個函數,在列表中的位置1和5之間寫入奇數。 我做了類似的事情: - 在文件域中我寫了奇數的條件:
def oddNumber(x):
"""
this instruction help us to write the odd numbers from the positions specificated
input: x-number
output:-True if the number is odd
-False otherwise
"""
if x % 2==1:
return True
else:
return False
然后測試:
def testOdd_Number():
testOdd_Number=[0,1,2,3,4,5,6,7,8]
oddNumber(testOdd_Number,0,6)
assert (testOdd_Number==[1,3,5])
oddNumber(testOdd_Number,0,3)
assert (testOdd_Number==[3])
- 在另一個名為userinterface的文件中我寫這個:
elif(cmd.startswith("odd from ", "")):
try:
cmd=cmd.replace("odd from ", "")
cmd=cmd.replace("to ", "")
i=int(cmd[:cmd.find(" ")])
j=int(cmd[cmd.find(" "):])
if (i>=len(NumberList) or i>j or j>=len(NumberList) or i<0 or j<0):
print("Invalid value(s).")
else:
for m in range(i-1,j):
if oddNumber(NumberList[m]):
print (NumberList[m])
except:
print("Error!")
- 當我運行整個項目時(我有更多要求,但其他一個是好的),並從[pos]寫到[pos]它說我
Traceback (most recent call last):
File "C:\Users\Adina\My Documents\LiClipse Workspace\P1\userinterface.py", line 94, in <module>
run()
File "C:\Users\Adina\My Documents\LiClipse Workspace\P1\userinterface.py", line 77, in run
elif(cmd.startswith("odd from ", "")):
TypeError: slice indices must be integers or None or have an __index__ method
我忘了說我有一個函數main(),我在那里打印需求。我錯在哪里?
Python的字符串以方法開頭,如下所述:
https://docs.python.org/2/library/stdtypes.html
聲明參數是
some_string.startswith(prefix, beginning, end) #where beginning and end are optional integers
並且您提供了前綴和空字符串(cmd.startswith(“odd from”,“”))
我注意到的一些事情:
1)你可以縮短你的oddNumber
函數
def oddNumber(x):
return x%2
2)在測試中,將函數名稱testOdd_Number
重新綁定到某個列表,然后將其傳遞給oddNumber
函數。 是上述相同的功能? 然后它將無法工作,因為此函數需要傳遞一個整數。
不鼓勵使用相同的名稱來指代兩個不同的東西。 實際上,我不知道你的測試代碼做了什么或應該做什么。 您是否傳遞了一個列表並期望oddNumber
將其修改到位?
3)你的自定義命令解析器看起來......奇怪,脆弱。 也許投資一個真正的解析器? 您應該解耦命令解析和實際計算。
正如brainovergrow所指出的,還有你的錯誤,因為.startswith
不接受字符串作為第二個參數。
一些一般提示:
list(range(9))
而不是硬編碼[0,1,2,3,4,5,6,7,8]
filter
來過濾給定列表的奇數: >>> list(filter(oddNumber, range(9)))
得到[1, 3, 5, 7]
。 list comprehensions
: [x for x in range(9) if x%2]
得到相同的結果。 any()
和all()
有用。 看看他們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.