slow script trying to find unique values in list
<p>I've got a problem in Python:
I want to find how many UNIQUE <code>a**b</code> values exist if:<br>
&nbsp;&nbsp;&nbsp;&nbsp;<code>2 â¤ a â¤ 100</code>and <code>2 â¤ b â¤ 100</code>?</p>

<p>I wrote the following script, but it's too slow on my laptop (and doesnt even produce the results):</p>

<pre><code>List=[]
a = 2
b = 2
c = pow(a, b)
while b != 101:
    while a != 101:
        if List.count(c) == 0:
            List.append(c) 
            a += 1
    b += 1
print len(List)
</code></pre>

<p>Is it good? Why is it slow?</p>

<p>This code doesn't work; it's an infinite loop because of the way you don't increment <code>a</code> on every iteration of the loop.  After you fix that, you still won't get the right answer because you never reset <code>a</code> to 2 when <code>b</code> reaches <code>101</code>. </p>

<p>Then, <code>List</code> will ever contain only <code>4</code> because you set <code>c</code> outside the loop to <code>2 ** 2</code> and never change it inside the loop. And when you fix <em>that</em> it'll still be slower than it really needs to be because you are reading the entire list each time through to get the count, and as it gets longer, that takes more and more time. </p>

<p>You generally should use <code>in</code> rather than <code>count</code> if you just need to know if an item is in a list, since it will stop as soon as it finds the the item, but in this specific instance you should be using a <code>set</code> anyway, since you are looking for unique values. You can just <code>add</code> to the set without checking to see whether the item is already in it.</p>

<p>Finally, using <code>for</code> loops is more readable than using <code>while</code> loops.</p>

<pre><code>result = set()
for a in xrange(2, 101):
    for b in xrange(2, 101):
        result.add(a ** b)
print len(result)
</code></pre>

<p>This takes less than a second on my machine.</p>

python