I want to make a function that returns a tuple of adjacent positions. But I'm having trouble returning the dictionary values.
My code:
def creat_position(c,r):
if isinstance(c, str) and c in ('a', 'b', 'c') and isinstance(r, str) and l in ('1', '2', '3'):
return c, r
def position_to_str(pos):
c = str(obtain_pos_c(pos))
r = str(obtain_pos_r(pos))
if its_position(pos):
return c + r
def obtain_adjacent_positions(pos):
"""
obtain_adjacent_positions: position -> tuple of positions
"""
p = position_to_str(pos)
#'b''2' -> 'b2'
adj = {'a1': ('b1', 'a2'),
'b1': ('a1', 'b2', 'c1'),
'c1': ('b1', 'c2'),
'a2': ('a1', 'b2', 'a3'),
'b2': ('b1', 'a2', 'c2', 'b3'),
'c2': ('c1', 'b2', 'c3'),
'a3': ('a2', 'b3'),
'b3': ('b2', 'a3', 'c3'),
'c3': ('c2', 'b3')
}
adjacents = adj[p]
return adjacent
The output should be:
>>>p1 = creat_positon('c', '1')
>>>p2 = creat_positon('b', '3')
>>>position_to_str(p2)
'b3'
>>>tuple(position_to_str(p) for p in obtain_adjacent_positions(p1))
('b1', 'c2')
>>>tuple(position_to_str(p) for p in obtain_adjacent_positions(p2))
('b2', 'a3', 'c3')
The problem is when I run my function this happens:
>>>tuple(position_to_str(p) for p in obtain_adjacent_positions(p2))
(None, None, None)
Instead of my key values.
The keys in the dictionary are strings, but your code tries to look up a "position", which I assume is an object.
You could either pass it to the function as a string:
tuple(position_to_str(p) for p in obtain_adjacent_positions(position_to_str(p2)))
Or have the function do it itself:
adjacents = adj[position_to_str(p)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.