Question: I've been trying to create a script that searches for a pattern in a text file, counts the number of times it occurs and then inserts this as a key-value pair into a dictionary.

Here's the code:

```
fname = raw_input("File name: ")
import re
vars = dict()
lst= list()
count = 0

try:
    fhand = open(fname, "r+")
except:
    print "File not found"
quit()  

for line in fhand:
    line.rstrip()
    if re.search(pattern , line):
        x = re.findall(pattern , line)
        lst.append(x)
    else:
        continue
    for x in lst:
        count += 1

```

What would be the best way to extract text from the regex method and insert it into a dictionary to make it look like this:

```
{'pattern' : count, 'pattern' : count, 'pattern' : count}

```

Answer: 
As the results of `sin` and `cos` are zero, one, or minus one, and cyclic, you can look them up, modulo four:

```
pos = [100, 100]
direction = 0

east_west_lookup = [0, -1, 0, 1]
north_south_lookup = [1, 0, -1, 0]

for i in dragon + [0]:
    east_west_step = east_west_lookup[direction % 4]
    north_south_step = north_south_lookup[direction % 4]
    pos.extend([pos[-2] + east_west_step,
                pos[-1] + north_south_step])
    direction += i

```
A small improvement, but that saves 10-15% time on my system, is to not calculate `math.pi/2` every time. It is not as fast as Peter Wood's solution, but might be useful in case you decide to open the `dragon` list to values other than 0, 1, and -1.

```
pos = [100, 100]
ang = math.pi/2
turn = ang
for i in dragon + [0]:
    pos.extend([pos[-2]+math.cos(ang), pos[-1]+math.sin(ang)])
    ang += i*turn

```