简体   繁体   中英

faster way of finding combinations?

I'm trying to find all possible sub-intervals between np.linspace(0,n,n*10+1) where the sub-intervals are greater than width (say width=0.5)

so I tried this with using itertools by

import itertools
ranges=np.linspace(0,n,n*10+1)
#find all combinations
combinations=list(itertools.combinations(ranges,2))
#using for-loops to calculate width of each intervals
#and append to new list if the width is greater than 0.5
save=[]
for i in range(len(combinations)):
    if combinations[i][1]-combinations[i][0]>0.5:
        save.append(combinations[i]) 

but this takes too many times especially when n gets bigger especially it costs huge ram usage

So I'm wondering whether if I can modify the function faster or set constraint when I collect combinations

itertools.combinations(...) returns a generator, that means the returned object produces its values when needed instead of calculating everything at once and storing the result in memory. You force immediate calculation and storing by converting it to a list, but this is unnecessary. Simply iterate over the combinations object instead of making a list of it and iterating over the indexes (which should not be done anyway):

import itertools
ranges=np.linspace(0,n,n*10+1)  # alternatively 'range(100)' or so to test
combinations=itertools.combinations(ranges,2)
save=[]

for c in combinations:
    if c[1] - c[0] > 0.5:
        save.append(c) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM