2014-10-26 99 views
1

这是我家庭作业的一部分,我接近最终答案但还不完全。我需要编写一个函数,将位置1和5之间的奇数写入列表中。 我做这样的事情: -in我写奇数条件的文件域名:在列表中编写奇数python

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]) 

- 和在其他文件中命名用户接口我写的这样的:

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()函数,我打印requirements.Where我错了?

+0

'cmd [:cmd.find(“”)]'如果在'cmd'中找不到''''''会出错。 – khelwood 2014-10-26 14:04:23

回答

3

Python的字符串startswith方法,这里介绍:
https://docs.python.org/2/library/stdtypes.html
指出参数是

some_string.startswith(prefix, beginning, end) #where beginning and end are optional integers 

,你必须提供前缀和空字符串(cmd.startswith( “从奇”, “”))

+0

准确地说,这些不是(仅)整数,而是分片索引,因此是错误消息。 – georg 2014-10-26 14:17:27

+0

谢谢你的回答。 – Boolean 2014-10-26 19:33:55

0

有些事情,我注意到:

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()有用。看看他们。
  • 您的命名方案更紧密一致,也不pythonic。阅读PEP8获取样式指南。
+0

谢谢您的回答。我发现了错误。也感谢提示。 – Boolean 2014-10-26 19:34:59