2017-09-25 17 views
0

我創建一個單一的鏈接列表,返回給定範圍內的奇數,而不是返回1,3,5等,它返回1,None,3,None,5等我想使它停止返回None和只有奇數。鏈接列表返回時沒有指定不是

class Odds: 
    def __init__(self,end): 
     self.__start = 1 
     self.__end = end 

    def __iter__(self): 
     return OddsIterator(self.__end) 

class OddsIterator: 
    def __init__(self,finish): 
     self.__current = 0 
     self.__step = 1 
     self.__end = finish 

    def __next__(self): 
     x = None 
     if self.__current > self.__end: 
      raise StopIteration 
     else: 
      self.__current += self.__step 
      if (self.__current - self.__step + 1) % 2 != 0: 
       x = self.__current - self.__step + 1 
     if x != None: 
      return x 
+0

採用雙層名稱壓延 –

回答

1

原因None正在返回的是,可以在沒有return語句的情況下到達__next__的末尾,在這種情況下,任何Python函數都會返回None。這裏的解決方案是在初始化時設置self.__step = 2self.__current = 1。您也可以刪除if x != None:,因爲它什麼都不做。爲了適應self.__current這個新定義,我還做了一些其他小改動。目前下面的代碼將不包含最終值,如果您希望它隨後將self.__current >= self.__end更改爲self.__current > self.__end

class Odds: 
    def __init__(self,end): 
     self.__start = 1 
     self.__end = end 

    def __iter__(self): 
     return OddsIterator(self.__end) 

class OddsIterator: 
    def __init__(self,finish): 
     self.__current = 1 
     self.__step = 2 
     self.__end = finish 

    def __next__(self): 
     x = None 
     if self.__current >= self.__end: 
      raise StopIteration 
     else: 
      return_value = self.__current 
      self.__current += self.__step 
      return return_value 

odds = Odds(21) 
print(list(odds)) 
+0

改變步驟到2的變化意味着如果一個奇數用於結束,那麼它將返回比它應該多一個,即「賠率(22 )'最後會有23個 – BadUserName

+0

好抓!我現在已經解決了這個問題,希望能夠使邏輯更加清晰。 –

+0

謝謝,如果輸入了奇數,我在'__init__'函數的'if'語句中添加了從結束值減1的值,歡呼! – BadUserName

0

你違反了規則蟒禪宗之一:簡單比複雜(https://www.python.org/dev/peps/pep-0020/#id3

而實際上你的代碼可以通過更好地解決:

>>> odds = range(1, 51, 2) # Here you specify the start, stop and step values 
>>> iterator = iter(odds) # Here you make it work with next keyword 
>>> next(iterator) 
1 
>>> next(iterator) 
3 
>>> [x for x in iterator] 
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49] 
+1

有可能停止(可能?)這是一個任務,並提問者需要使用一個鏈表。 –

+0

@JeremyMcGibbon:正是我的想法! – Unni

+0

我在這裏使用一個鏈表,所以這是不可能的 – BadUserName