我正在尝试在python中实现eratosthenes的筛子,但是当试图找到所有素数达到sqare根时,例如779695003923747564589111193840021我得到一个错误,说range()的结果有太多的项目.我的问题是,我如何避免这个问题,如果我用while循环实例化列表,我会得到一个错误,说我使用了太多的内存(在它开始使用页面文件之前),下面列出了两个:
使用范围()
maxnum = 39312312323123123
primes = []
seq = []
i = 0
seq = range(2,maxnum)
for i in seq:
mul = i * seq
for j in mul:
try:
seq.remove(j)
except:
pass
primes.append(i)
print primes
Run Code Online (Sandbox Code Playgroud)
使用while:
maxnum = 39312312323123123
primes = []
seq = []
i = 0
while i < maxnum:
seq.append(i)
i+=1
for i in seq:
mul = i * seq
for j in mul:
try:
seq.remove(j)
except:
pass
primes.append(i) …Run Code Online (Sandbox Code Playgroud) 我被要求反转a以head为参数,其中head是一个链表,例如:1 - > 2 - > 3,它是从已定义的函数返回的,我试图用这种方式实现函数reverse_linked_list:
def reverse_linked_list(head):
temp = head
head = None
temp1 = temp.next
temp2 = temp1.next
temp1.next = None
temp2.next = temp1
temp1.next = temp
return temp2
pass
class Node(object):
def __init__(self,value=None):
self.value = value
self.next = None
def to_linked_list(plist):
head = None
prev = None
for element in plist:
node = Node(element)
if not head:
head = node
else:
prev.next = node
prev = node
return head
def from_linked_list(head):
result = []
counter = …Run Code Online (Sandbox Code Playgroud) 我正在尝试计算天际线的面积(具有相同基线的重叠矩形)
building_count = int(input())
items = {} # dictionary, location on x axis is the key, height is the value
count = 0 # total area
for j in range(building_count):
line = input().split(' ')
H = int(line[0]) # height
L = int(line[1]) # left point (start of the building)
R = int(line[2]) # right point (end of the building)
for k in range(R - L):
if not (L+k in items): # if it's not there, add it
items[L+k] = H …Run Code Online (Sandbox Code Playgroud)