如何在制作配方(python)中找到最基本的材料?

2024-05-18 10:53:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在网上搜索,试图帮助与上述问题,但我似乎找不到一个来源,以帮助我完成这个项目。你知道吗

基本上,我想取一个我指定的项目(比如),然后让代码找到制作项目所需的最基本的材料。一张床需要3块羊毛和3块木板。每根羊毛需要4根细绳(一种基本材料),每4块木板可以由1根木材(另一种基本材料)制成。因此,代码将返回:

12弦1木工艺所需。你知道吗

我以为我可以让类来组织项目,但发现我无法访问其他类的食谱列表:

class bed:

    class wool:
        id=1
        def getId(self):
            print(self.id)
        name="wool"
        def getName(self):
            print(self.name)
        recipe= [{"amt":4,"items":"string"}]
        def getRecipe(self):
            print(str(self.recipe[0]["amt"])+" of "+str(self.recipe[0]["items"]))

每样东西都是这样的。我知道我需要做一个object来实际使用这些东西,但是我不知道如何追溯到配方,直到我得到绝对的基本材料。你知道吗

我还试着做了一本小字典:

items=[{"uid":0,"name":"bed","recipe":}]

但是我在想怎么说3块木板时遇到了问题。接下来的问题是再次尝试寻找最基本的材料。你知道吗

一般来说,我对python/代码还比较陌生,我一直在通过做一些突然出现在我脑海中的随机项目来自学,如果我的方法或逻辑看起来很奇怪,那么很抱歉。任何帮助都将不胜感激!你知道吗

编辑:抱歉之前没有缩进,这是我的第一篇帖子


Tags: 项目代码nameselfiddefrecipeitems
3条回答

对于由其他项组合而成的项,最好有一个字典:

recipes = {
    "bed": {
        "plank": 3,
        "wool": 3
    },
    "wool": {
        "string": 4
    }
}

还有另一本字典,里面的条目可以分解成其他条目:

yields = {
    "wood": {
        "plank": 4
    }
}

一个好的开始可能是从一个非常基本的item类中派生子类,并保持其他类非常简单。以下是您可能会想到的一个原型:

class Item():
    def __init__(self):
        self.RECIPE = {}

    def get_complete_recipe(self):
        if not self.RECIPE:
            return

        print '\nA {} requires:'.format(self)
        for item, count in self.RECIPE.iteritems():
            print '[ {} {} ] '.format(count, item),
            item.get_complete_recipe()

class String(Item):
    def __init__(self):
        self.RECIPE = {}

    def __str__(cls):
        return 'String'

class Wool(Item):
    def __init__(self):
        self.RECIPE = {String(): 4}

    def __str__(cls):
        return 'Wool'

class Wood(Item):
    def __init__(self):
        self.RECIPE = {}

    def __str__(cls):
        return 'Wood'

class Plank(Item):
    def __init__(self):
        self.RECIPE = {Wood(): .25}

    def __str__(cls):
        return 'Plank'

class Bed(Item):
    def __init__(self):
        self.RECIPE = {Wool(): 3, Plank(): 3}

    def __repr__(cls):
        return 'Bed'


b = Bed()

b.get_complete_recipe()

我们可以通过这种方式得到任何一种食物的完整配方。__str__让我们根据自己的喜好打印出类的实际名称。在这里你可以看到,当我们得到床的完整配方时,它会分解成这样:

A Bed requires:
[ 3 Wool ]  
A Wool requires:
[ 4 String ]  [ 3 Plank ]  
A Plank requires:
[ 0.25 Wood ] 

你可以增加一些逻辑,积累基本资料。这是完全可行的,因为基本材料没有配方对象的项目。希望这有帮助:)

或者另一个解决方案,你从一本字典开始 定义您的食谱:

import math

recipes = {
    'bed': (
        ('wool', 3),
        ('plank', 3),
    ),
    'wool': (
        ('string', 4),
    ),
    'plank': (
        ('wood', 0.25),
    ),
    'wood': (),
    'string': (),
}

然后使用递归函数将项解析为 组成成分:

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)]

函数的行为如下:

>>> resolve('string')
[('string', 1)]
>>> resolve('wood')
[('wood', 1)]
>>> resolve('plank')
[('wood', 1)]
>>> resolve('wool')
[('string', 4)]
>>> resolve('bed')
[('string', 12), ('wood', 1)]

打印内容:

>>> for item, count in resolve('bed'):
...     print('{} = {}'.format(item, count))
...
string = 12
wood = 1
>>>

相关问题 更多 >