[英]Find prime numbers with list comprehension
我試圖編寫代碼到 select 列表中的素數。 用戶給出一個極限,程序顯示從 2 到極限的所有素數。 我試圖盡可能減少行數,但對一些我無法理解的情況感到驚訝。 如果你能幫助我,我將不勝感激。
我寫了這段代碼:
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
lista = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in lista if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
它按我的預期運行,但是當我嘗試刪除第一個列表分配行並將范圍 function 直接包含到理解中時,它不起作用。 為什么?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in [*range(2, limit + 1)] if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
其他問題。 由於范圍行不是列表,我修復它只是為了改進代碼,但是當我將值的名稱從“lista”更改為另一個名稱時,我發現它也不起作用。 為什么?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
nums = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in nums if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
感謝您的關注。
這個單線完美地工作:
def primes(val):
return [x for x in range(2, val) if all(x % y != 0 for y in range(2, x))]
print(primes(10))
感謝您的關注。我喜歡我們的朋友 Yash Makan 的回答,但是當我嘗試更大的數字時,比如 100000,它從來沒有讓我得到結果(或者我沒有耐心等待)。 所以我繼續思考這個問題並得到以下是計算這個問題的最快方法,我可以通過列表理解實現。 請注意計算數百萬個數字的速度。
# returns all integers from 2 to a limit given by the user.
def primes(limit):
l = [i for i in range(2, limit + 1) if all(i % j != 0 for j in [2, 3, 5])]
lista = []
return [2, 3, 5] + [lista.append(i) or i for i in l if all( i % j != 0 for j in lista[:int((len(lista) ** .5) + 1)])]
def main():
l = int(input("Enter the limit: "))
return print(primes(l))
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.