将函数应用于列表递归的每个元素

时间:2017-01-05 22:12:11

标签: python recursion

我有一个函数,它将关键字作为输入并返回相关关键字的列表。 我需要的是一个函数,它将获取相关的关键字,然后再次对返回列表中的每个关键字运行,依此类推定义的次数。

def find_related(kw):

#magic happens

return related_kws

'''
Example:

>>>find_related('eat')
{
    'base_kw': 'eat'
    'related_kws': ['eat pasta', 'eat meat', 'eat fish']
}
'''

我需要的是这样的事情:

def difficult_function(kw, cycles):

#cycles determines number of times to run recursion
#magic beyond my league happens...

return more_related_keywords

'''
EXAMPLE #1

>>>difficult_function('eat', 2)
{
    'base_kw': 'eat'
    'related_kws': {
        'eat pasta': ['eat cold pasta', 'eat italian pasta', 'eat instant pasta'],
        'eat meat': ['eat raw meat', 'eat cow meat', 'eat roasted meat'],
        'eat fish': ['eat raw fish', 'eat rotten fish', 'eat fresh fish']
    }
}

'''

'''
EXAMPLE #2

>>>difficult_function('eat', 3)
{
    'base_kw': 'eat'
    'related_kws': {
        'eat pasta': {
            'eat cold pasta': [
                'eat cold pasta with sauce',
                'eat cold pasta and wine',
                'eat cold pasta at night'
            ],
            'eat italian pasta': [
                'eat italian cheap pasta',
                'eat best italian pasta',
                'eat italian pasta and pesto'
            ],
            'eat instant pasta': [
                'eat instant pasta snack',
                'eat instant cheese pasta',
                'eat healthy instant pasta'
            ]
        },
        'eat meat': {
            'eat raw meat': [
                'eat raw meat dangerous',
                'eat raw chicken meat',
                'eat raw meat with lemon'
            ],
            'eat cow meat': [
                'eat cow meat and salad',
                'eat cow meat and rice,
                'eat cow meat benefits'
            ],
            'eat roasted meat': [
                'eat roasted meat sandwich',
                'eat cold roasted meat',
                'don\'t eat roasted meat'
            ]
        },
        'eat fish': {
            'eat raw fish': [
                'eat raw fish sushi',
                'eat raw fish health', 'eat raw fish japanese'],
            'eat rotten fish': [
                'eat rotten fish bacteria',
                'eat rotten fish death',
                'eat rotten fish stomach'
            ],
            'eat fresh fish': [
                'eat fresh fish restaurant',
                'eat fresh fish with lemon',
                'eat fresh fish at home']
        }
    }
}
'''

我知道我应该在这里分享我已经尝试过的东西,但事实是我甚至不知道从哪里开始。有什么想法吗?

编辑:

下面的函数模拟find_related(kw)的功能。如果问题没有以适当的方式呈现,我很抱歉,我是一个完全的菜鸟

import string
import random

def find_related(kw):
    # A lot of magic happens, the list comprehension
    # below simulates the magic
    related_kws = [
        kw + ' ' + ''.join(
            random.choice(string.ascii_lowercase) for 
            _ in range(4)) for i in range(3)
    ]

    results = {
        'base_kw': kw,
        'related_kws': related_kws
    }

    return results  

匹配给定示例的模拟函数。

def find_related(kw):
    '''mock function'''
    # A lot of magic happens, this simulates the magic
    d = {'eat': ['eat pasta', 'eat meat', 'eat fish'],
         'eat pasta': ['eat cold pasta', 'eat italian pasta', 'eat instant pasta'],
         'eat meat': ['eat raw meat', 'eat cow meat', 'eat roasted meat'],
         'eat fish': ['eat raw fish', 'eat rotten fish', 'eat fresh fish'],
         'eat cold pasta': ['eat cold pasta with sauce', 'eat cold pasta and wine', 'eat cold pasta at night'],
         'eat italian pasta': ['eat italian cheap pasta', 'eat best italian pasta', 'eat italian pasta and pesto'],
         'eat instant pasta': ['eat instant pasta snack', 'eat instant cheese pasta', 'eat healthy instant pasta'],
         'eat raw meat': ['eat raw meat dangerous', 'eat raw chicken meat', 'eat raw meat with lemon'],
         'eat cow meat': ['eat cow meat and salad', 'eat cow meat and rice', 'eat cow meat benefits'],
         'eat roasted meat': ['eat roasted meat sandwich', 'eat cold roasted meat', 'don\'t eat roasted meat'],
         'eat raw fish': ['eat raw fish sushi', 'eat raw fish health', 'eat raw fish japanese'],
         'eat rotten fish': ['eat rotten fish bacteria', 'eat rotten fish death', 'eat rotten fish stomach'],
         'eat fresh fish': ['eat fresh fish restaurant', 'eat fresh fish with lemon', 'eat fresh fish at home']

         }


    results = {
        'base_kw': kw,
        'related_kws': d[kw]
        }

2 个答案:

答案 0 :(得分:1)

以下是有人正在寻找类似内容的答案。如果提出的问题很少,我再次道歉。

import pprint
import string
import random

def find_related(kw):
    # A lot of magic happens, the list comprehension
    # below simulates the magic
    related_kws = [
        kw + ' ' + ''.join(
            random.choice(string.ascii_lowercase) for 
            _ in range(4)) for i in range(3)
    ]
    results = {
        'base_kw': kw,
        'related_kws': related_kws
    }
    return results

def difficult_function(kw, cycles):    
    return {
        'base_kw': kw,
        'related_kws': rec_kw(kw, cycles)
    }

def rec_kw(kw, cycles):
    if cycles == 1:
        return find_related(kw)
    else:
        result = {}
        for k in find_related(kw)['related_kws']:
            result[k] = rec_kw(k, cycles-1)
        return result

pprint.pprint(difficult_function('eat', 3))

答案 1 :(得分:0)

此代码可以满足您的需求。为了看到结果,我写了它与全球列表INP一起工作,但是原则对你有用。

INP = ["Lorem", "Ipsum", "dolor", "atea"]

def recursive (kw, max, ref=None):

    ret = None
    if ref is None:
        ret = {'base_kw' : kw, 'related_kws' : {}}
        ref = ret ['related_kws']

    if max != 1:
        words = [' '.join (INP [0: len (INP) - max + 1]), ]
        for kw in words:
            ref [kw] = {}
            ref = ref [kw]
            recursive (kw, max -1, ref)
    else:
        ref [kw] = [' '.join (INP)]

    return ret

print (recursive ("Lorem", 3))

这是输出:

{'related_kws': {'Lorem Ipsum': {'Lorem Ipsum dolor': {'Lorem Ipsum dolor': ['Lorem Ipsum dolor atea']}}}, 'base_kw': 'Lorem'}