我创建了一个程序,它将返回所选索引的值和字符串“number”旁边的5下一个索引。由于字符串非常大,大多数计算机都需要很长时间才能完成工作。我需要优化代码。我在某处读过lamda函数可以帮助我。在这里有人可以建议我制作字符串的其他方法或制作程序的其他方法。
number = ""
for num in range(2,999999):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
number = number + str(num)
print(number[n:n+5])
PS =我做了这个,这个肯定会更加优化
def answer(n):
number = "2357"
i = 9
while(i<999999):
prime = True
if (i%5==0):
i=i+2
prime = False
continue
if (i%3==0 | i%7==0):
i=i+2
prime = False
continue
if prime:
number = number + str(i)
i=i+2
continue
print(number[n:n+5])
答案 0 :(得分:0)
下面的代码更加优化
number = ""
for num in range(2,999999):
prime = True
for i in range(2,num/2):
if (num%i==0):
prime = False
break
if prime:
number = number + str(num)
print(number[n:n+5])
1)一旦你发现数字不是素数,你应该打破循环而不是继续循环。 2)没有必要去n-1来检查它是否是素数。你可以通过n / 2
来检查它答案 1 :(得分:0)
lambda不会帮助你,但你的代码可能会有点优化
import math
number = ""
for num in range(2,999999):
prime = True
for i in range(2, int(math.sqrt(num))):
if (num%i==0):
prime = False
break
if prime:
number = number + str(num)
print(number[n:n+5])
答案 2 :(得分:0)
有许多更快的素数生成算法,例如:
下面的代码示例使用Eli Bendersky answer中的Eratosthenes筛选
字符串是Python中的不可变对象,因此使用plus运算符的字符串连接效率不高,特别是对于长字符串,我假设运行时行为为O(n 2 )。可以在Efficient String Concatenation in Python中找到字符串连接方法的比较。
以下代码将join
与生成器一起使用。此外,没有必要计算超出 n + 5的整个字符串。
了解发电机的链接:
代码:
import math
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
def gen_primes_limited_by_total_length(length):
total = 0
for prime in gen_primes():
yield prime
total += len(str(prime))
if total > length:
return
def my_func(n):
return ''.join(
str(prime)
for prime in gen_primes_limited_by_total_length(n + 5)
)[n:n + 5]
print(my_func(0))
print(my_func(10))
print(my_func(10000))
print(my_func(1234567))
结果:
23571
19232
02192
81258
我不知道,my_func
会多久使用一次。因此,另一种方法是计算内存中的整个字符串。但是,如果对大量素数进行处理,字符串生成可能是浪费时间,但只使用 n 的小值。
my_func
的一个小优化是通过不使用对于 n 而言太小的素数来限制字符串长度。它节省了内存,但运行时间
受影响不大,因为素数的产生大部分时间都是成本。
def my_func(n):
total = 0
s = ''
for prime in gen_primes():
p = str(prime)
lp = len(p)
if lp <= n:
n -= lp
elif n > 0:
s = p[n:]
n = 0
else:
s += p
ls = len(s)
if ls >= 5:
return s[0:5]