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.
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

```