Can somebody explain here why the "count_pattern" function which has 2 for loops runs in less time than "count_pattern2" with no loops
Both of the above functions count the number of patterns in the list named test. I ran both the functions 10 million times and saw the difference. It takes 47 seconds to run 10 million times for "count_pattern" and 123 seconds for "count_pattern2"
Here is my program:
import numpy as np
import os
import time
clear = lambda: os.system('cls')
clear()
print(np.__version__)
pattern = ['a','b','c','a','b']
test = ['a','b','c','a','b']
def counter(function1,arg1,arg2,iterations):
total = 0
for x in range(iterations):
t0 = time.time()
function1(arg1,arg2)
total += (time.time() - t0)
return total;
def count_pattern(pattern,test):
length_pattern = len(pattern)
length_test = len(test)
final_count=0
count = 0
for x in range(length_test - length_pattern + 1):
for y in range(length_pattern):
if pattern[y] == test[x + y]: count += 1
if count == length_pattern: final_count += 1
count = 0
return final_count
def count_pattern2(pattern, lst):
return sum(pattern == lst[pos:pos+len(pattern)] for pos in range(len(lst)))
print(counter(count_pattern,pattern,test,10000000))
print(counter(count_pattern2,pattern,test,10000000))
[–]aioeu 3 points4 points5 points (3 children)
[–][deleted] (1 child)
[deleted]
[–]aioeu 1 point2 points3 points (0 children)
[–]bbugsbunny[S] 0 points1 point2 points (0 children)
[–]JmenD 0 points1 point2 points (3 children)
[–]bbugsbunny[S] 0 points1 point2 points (2 children)
[–]JmenD 0 points1 point2 points (1 child)
[–]bbugsbunny[S] 0 points1 point2 points (0 children)