简体   繁体   中英

For loop or Lambda function?

I have this two code, they both (only the first right now) should return me the lenght of sequence that is repeated (13, 6, 6, 14, 6 AND 13, 6, 6, 14, 6):

l = [13, 6, 6, 14, 6, 13, 6, 6, 14, 6]

def count_period(l): 
    
    l_max = int((len(l)/2)+1)

    for i in range(2, l_max):
        interval1 = l[0:i] 
        intervallo2 = l[i:2*i]
        if interval1 == interval2:
            return i

And:

l = [13, 6, 6, 14, 6, 13, 6, 6, 14, 6]

l_max = int((len(l)/2)+1)
period_value= next(filter(lambda x: [l[0:x] == l[x:2*x] in range(2, l_max)], l), None)

Why the first code return the right value (5) while the second return me 13? What I'm doing wrong? About this topic: since I'm newbie to Python from a general point of view (and not about this case), how I can know which path should i follow to get a good code (with low execution time and low cyclomatic complexity)? For example in this case (let us assume that I haven't written anything yet), which of this two way (or another) should I follow? Thank you!

You should be filtering range(2, l_max) not l to translate your code from the top into a filter. Right now for each value in l you are creating a list in the predicate lamdba you define filter to use. If that list has items in it it returns true , only the empty list would return false . Filter then decides to keep the value x if it passes the predicate or discards it if it does not. So therefore it keeps all items in the original list and next on that list is 13. You should do this instead:

l = [13, 6, 6, 14, 6, 13, 6, 6, 14, 6]

l_max = int((len(l)/2)+1)
period_value= next(filter(lambda x: l[0:x] == l[x:2*x], range(2, l_max)), None)

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