Your code works just fine:
>>> from collections import defaultdict
>>> def next(s):
... x = defaultdict(set)
... for i in range(len(s)-1):
... x[i].add(s[i+1])
... return x
...
>>> next('hello')
defaultdict(<type 'set'>, {0: set(['e']), 1: set(['l']), 2: set(['l']), 3: set(['o'])})
Perhaps your running code uses defaultdict(str)
by accident?
You want to use s[i]
as the key though:
def next(s):
x = defaultdict(set)
for i in range(len(s)-1):
x[s[i]].add(s[i+1])
return x
This produces the desired output:
>>> def next(s):
... x = defaultdict(set)
... for i in range(len(s)-1):
... x[s[i]].add(s[i+1])
... return x
...
>>> next('hello')
defaultdict(<type 'set'>, {'h': set(['e']), 'e': set(['l']), 'l': set(['l', 'o'])})
You can also loop over the string as an iterator, 'remembering' the previous character:
def next_dict(s):
x = defaultdict(set)
prev = s[0]
for char in s[1:]:
x[prev].add(char)
prev = char
return x
It is much easier to track the previous value(s), looking behind, than it is to look ahead; you already passed over the previous values, after all.