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: 
Numpy can do this as well, quite effeciently! Using the lookup table from Peter Wood's answer we can write for the x-direction:

```
x0 = 100
directions = np.cumsum(2 - dragon) % 4
dx = np.take([0, -1, 0, 1], directions)
x = np.cumsum(np.r_[x0, dx])

```

The `2 - dragon` is to get rid of negative values before taking the modulus.
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

```