2016-04-07 12 views
-6

我從codewars.com有這個問題:前n個Primes數字。 雖然我沒有定義類Primes()和Primes.first(n1)的問題,但我需要在表單Primes.first(n1).last(n2)下找到最後的素數。而且我不知道如何定義最後(n2)而不會出現錯誤。Python - Class.function()。function()

import math 
    class Primes(): 
     def first(self): 
      primes = [] 
      count = 1 
      prime = True 
      while len(primes) != self: 
       for i in range(2, int(math.sqrt(count)) + 1): 
        if count % i == 0: 
        prime = False 
        break 
      if prime: 
       primes.append(count) 
      prime = True 
      count += 1 
      return primes 

     def last(self): 
      pass 

,如果我嘗試Primes.first(5)。去年(3)我得到:AttributeError的: '名單' 對象有沒有屬性 '最後'。

+0

請發佈您嘗試過的代碼和您收到的錯誤。謝謝。 – lrnzcig

+1

我用代碼更新了我的任務。 –

+1

你的代碼沒有意義,除了self以外,沒有任何參數可以用於'first'。所以,Primes()。first(3)並不代表什麼 –

回答

0

...首先返回一個list.last()試圖調用名爲last的函數在列表中。列表沒有稱爲last的函數。

我想你想要這個。

class Primes(list): 
    def first(self, amount): 
     count = 1 
     while len(self) < amount: 
      prime = True 
      for i in range(2, int(math.sqrt(count)) + 1): 
       if count % i == 0: 
        prime = False 
        break 
      if prime: 
       self.append(count) 
      count += 1 
     return self # Note: self is Primes object which has a last method. 

    def last(self, amount): 
     ... 
     return self 

p = Primes() 
p.first(5) 
p.last(3) 
# same as p = Primes().first(5).last(3) because it returns self 
# Primes now inherits from list, so it works like a list but has a last method 

我修復了代碼中的tab。

從它的外觀你根本不需要最後的方法。如果您只想獲取最後5個值,請使用[-5:]。

# Your old way edited 
class Primes(): 
    @staticmethod 
    def first(amount): 
     primes = [] 
     count = 1 
     while len(primes) < amount: 
      prime = True 
      for i in range(2, int(math.sqrt(count)) + 1): 
       if count % i == 0: 
        prime = False 
        break 
      if prime: 
       primes.append(count) 
      count += 1 
     return primes 

p = Primes.first(20) 
print(p) 
print(p[-5:]) # This will give you the last 5 
+0

感謝您的答覆和您的時間。 –

+0

你的代碼有一些不正確的標籤。你不需要最後的方法。只需使用括號即可獲取最後5個值。 – HashSplat

相關問題