获取相加等于某个值的集合

import time,dis
import random
import tracemalloc
nums = [random.randint(-109, 109) for i in range(2,1000)]
target = random.randint(-109, 109)
answer1 = []
answer2 = []


time0 = time.time()
def a():
b = []
for k1, val1 in enumerate(nums):
a = target - val1
for k2, val2 in enumerate(b):
if a == val2:
answer1.append([(val1, k1), (val2, k2)])
else:
b.append(val1)

#tracemalloc.start()
a()
# current, peak = tracemalloc.get_traced_memory()
# print(f"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB")
# tracemalloc.stop()
time1 = time.time()
def b():
val2 = []
for k1, val1 in enumerate(nums):
try:
k2 = 0
a = target - val1
while True:
k2 = val2.index(a, k2)
answer2.append([(val1, k1), (val2[k2], k2)])
k2 += 1
except ValueError:
val2.append(val1)
#tracemalloc.start()
b()
# current, peak = tracemalloc.get_traced_memory()
# print(f"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB")
# tracemalloc.stop()
time2 = time.time()
print(f"target: {target}")
print(f", spendtime: {time1 - time0}, len: {len(answer1)}")
print(f", spendtime: {time2 - time1}, len: {len(answer2)}")

 

上一篇:软件总结


下一篇:java 一个函数如何返回多个值