I encoded Euler's problem, and I came across a question of what aroused my curiosity. I have two pieces of code. One of them contains lists in which dictionaries are used.
using lists :
n=100000 num=[] suma=0 for i in range(n,1,-1): tmp=tuple(set([n for n in factors(i)])) if len(tmp) != 2: continue if tmp not in num: num.append(tmp) suma+=i
using dictionaries :
n=100000 num={} suma=0 for i in range(n,1,-1): tmp=tuple(set([n for n in factors(i)])) if len(tmp) != 2: continue if tmp not in num: num[tmp]=i suma+=i
My only concern is performance. Why the second example, using dictionaries, is incredibly fast, faster than the first example with lists. the example with dictionaries works almost thirty times faster!
I tested these 2 codes using n = 1,000,000, and the first code started in 1032 seconds and the second only 3.3 seconds ,, amazin '!
performance python dictionary list
froycard
source share