flatten(), [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

Ron Adam rrr at ronadam.com
Tue Jul 5 22:32:22 EDT 2005


Tom Anderson wrote:

> 
> We really ought to do this benchmark with a bigger list as input - a few 
> thousand elements, at least. But that would mean writing a function to 
> generate random nested lists, and that would mean specifying parameters 
> for the geometry of its nestedness, and that would mean exploring the 
> dependence of the performance of each flatten on each parameter, and 
> that would mean staying up until one, so i'm not going to do that.
> 
> tom
> 

Without getting to picky, would this do?

import random
import time
random.seed(time.time())

def rand_depth_sequence(seq):
     for n in range(len(seq)):
         start = random.randint(0,len(seq)-2)
         end = random.randint(start,start+3)
         seq[start:end]=[seq[start:end]]
     return seq

seq = rand_depth_seq(range(100))
print seq


 >>>
[[[[[0, 1], 2, [3, [4, 5, 6]]], [7], [8, [[9, [], 10]]]], [11, [12]], 
[[[]]]], [[], [13, 14, 15]], [[[16, 17]]], [18], [[[19], 20, [[21, 22, 
[23]], [[24]]]], 25, 26], [], [27, 28], [], 29, [], [30, [31, 32, 33]], 
[34], [[35]], 36, [[37, 38, 39], [[40, 41], [[42]]]], [43, 44], 45, 46, 
[47, []], [[[48, 49], [50], [51]], 52], [[[53], [54, 55, [56, 57, 58]], 
[]], [], []], [[59, 60, 61]], 62, [[63]], [], [64], [[[65]]], [[[66, 67, 
68], [69, 70, [71, 72]], [[73, 74], [75, 76]]], [77, 78]], [], 79, 80, 
[[81], []], 82, [[[83, [[], 84], [85]], 86, [[87, 88]]], [[[89], 90, 
91], [92, [93], [94, 95, 96]]]], [97, [98, 99]]]



More information about the Python-list mailing list