<p>或者另一个解决方案,你从一本字典开始
定义您的食谱:</p>
<pre><code>import math
recipes = {
'bed': (
('wool', 3),
('plank', 3),
),
'wool': (
('string', 4),
),
'plank': (
('wood', 0.25),
),
'wood': (),
'string': (),
}
</code></pre>
<p>然后使用递归函数将项解析为
组成成分:</p>
<pre><code>def _resolve(thing, count=1):
recipe = []
if not recipes[thing]:
recipe.append((thing, count))
else:
for comp, req in recipes[thing]:
recipe.extend(_resolve(comp, req*count))
return recipe
def resolve(thing):
'''This is a convenience function that takes carea of rounding
up fractional amounts to integer values (so if your recipe
only takes 0.75 wood, this will transform that to 1 wood,
because you can't use fractional amounts of things).'''
return [(item, int(math.ceil(count)))
for item, count in _resolve(thing, 1)]
</code></pre>
<p>函数的行为如下:</p>
<pre><code>>>> resolve('string')
[('string', 1)]
>>> resolve('wood')
[('wood', 1)]
>>> resolve('plank')
[('wood', 1)]
>>> resolve('wool')
[('string', 4)]
>>> resolve('bed')
[('string', 12), ('wood', 1)]
</code></pre>
<p>打印内容:</p>
<pre><code>>>> for item, count in resolve('bed'):
... print('{} = {}'.format(item, count))
...
string = 12
wood = 1
>>>
</code></pre>