Exploring Lists and Dicts in Python¶

Let's do some timing tests to explore using lists and dicts.

First, let's import some timing code:

In :
import time

And you can use it like this:

In :
time.time()
Out:
1392049686.71137

So, time.time() returns a number representing the current time.

We could use it to see how long something takes:

In :
time.time() - time.time()
Out:
-6.103515625E-05
Let's write a function to see how long something takes:
In :
def timeit(f):
start = time.time()
f()
print(time.time() - start)

We can use it like so:

In :
L = []
for i in range(10000000):
L.append(i)

1.65251922607

We can use some advanced features of Python to make it so that we can pass values to the function $f$ that we are timing.

In :
def timeit(f, *args, **kwargs):
start = time.time()
f(*args, **kwargs)
print(time.time() - start)
In :
L = []
for i in range(count):
L.append(i)

0.00413513183594
In :
0.000480651855469
In :
0.000282287597656

Does the list L contain 523? Yes, because we know it contains all numbers between 0 and 999 inclusive. In fact a good name for addem might be range because it does the same thing.

In :
import random
In :
random.random()
Out:
0.201483504940515
In :
random.randint(0, 3)
Out:
3

What does random.randint(start, stop) do?

Let's change addem so that it adds a certain number of random numbers, between 0 and maxint:

In :
L = []
for i in range(count):
L.append(random.randint(0, maxint))
return L
In :
Out:
[6, 4, 5, 8, 8, 1, 4, 7, 10, 4, 10, 2, 3, 0, 1, 5, 9, 2, 5, 7, 3, 3, 8, 7, 2, 5, 2, 2, 8, 3, 0, 8, 4, 9, 7, 7, 3, 9, 2, 7, 9, 10, 4, 4, 3, 6, 3, 9, 3, 7, 9, 7, 10, 9, 8, 8, 10, 6, 1, 1, 8, 5, 5, 2, 5, 10, 9, 9, 7, 6, 1, 10, 10, 9, 8, 6, 4, 9, 10, 5, 5, 6, 1, 7, 6, 5, 3, 1, 4, 7, 9, 5, 2, 7, 6, 9, 0, 6, 7, 8]

Now, let's write a function that will search for a number:

In :
def find(list, item):
count = 0
for i in list:
if item == i:
return count
count += 1
return -1
In :
def f1():
print("hi")

def f2():
return "hi"
In :
print(f2())
hi
In :
f1()
hi
In :
list = addem(1000, 1000)
In :
x = 10000
list = addem(x, x)
total = 0
for i in range(x):
if find(list, i) >= 0:
total += 1
print(total/x)
0.6312

How long does it take to find if something is in a list? in a dict?

Designing your own Classes¶

How does something like list and dict come about?

In [ ]: