有人能解释这条巨蟒排列code? [英] Could someone explain this python permutation code?

查看:125
本文介绍了有人能解释这条巨蟒排列code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了code一些帖子上这里排列,但我还没有真正能够找到一个很好的一步一步走通过什么是真正回事。如果有人可以只解释了什么是真正发生在这个code我真的AP preciate它的每一步。我不能完全似乎环绕它我的头。在code,我看到的是在Python,距离 HTTP://snippets.dzone .COM /职位/显示/ 753

 高清all_perms(STR):
    如果len(STR)< = 1:
        产量海峡
    其他:
        用于烫发的all_perms(STR [1:]):
            因为我在范围内(LEN(烫)+1):
                产量烫发[我] + STR [0:1] +烫发[我:]


对于p在all_perms(['一','B','C']):
    打印p
 

解决方案

首先,参数 STR 的名称是一个不错的选择。这可能是由于这样的事实,它适用于各种序列类型的植酮,但它应该是序列或一件让意图明显。

  1. 如果列表的长度为< = 1(空或一个元素)返回列表(存在对这种情况下只有一个溶液)

  2. 对于所有其他情况:

    a)创建海峡的所有排列[1:] (即不只是头部元素列表)

    B)将在中创建的每个排列每个位置的头部元素)并返回结果

收益率的工作原理有点像返回;主要的区别是,当前值被返回,并且当功能被再次调用,它继续与收率之后的指令

通过这种方式,可以很容易地组装的结果。

例如:

'A''A'(微不足道)。 'AB'头的第一个印章('A'),然后创建 B (只有一个:'B'本身)。现在,头插在每个位置上,所以我们最终'AB'(头​​+列表)和BA(列表+头)。

等。

I've seen some postings of code for permutations on here but I haven't really been able to find a good step-by-step walk through of what is actually going on. If someone could just explain what is actually happening in each step of this code I would really appreciate it. I can't quite seem to wrap my head around it. The code I'm looking at is in Python and is from http://snippets.dzone.com/posts/show/753.

def all_perms(str):
    if len(str) <=1:
        yield str
    else:
        for perm in all_perms(str[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + str[0:1] + perm[i:]


for p in all_perms(['a','b','c']):
    print p

解决方案

First of all, the name of the parameter str is a bad choice. It's probably due to the fact that it works for all kinds of sequence types in Phyton but it should be seq or something to make the intention clear.

  1. If the length of the list is <= 1 (empty or one element) return the list (there is just one solution for this case).

  2. For all other cases:

    a) Create all permutations of str[1:] (i.e. the list just without the head element).

    b) Insert the head element at each position in each permutation created in a) and return the result

yield works a bit like return; the main difference is that the current value is returned and, when the function is called again, it continues with the instruction after the yield.

This way, it's easy to assemble the result.

Example:

'a' gives 'a' (trivial). 'ab' first chops of the head ('a'), then creates all permutations of b (there is just one: 'b' itself). Now the head is inserted at every position, so we end up with 'ab' (head+list) and 'ba' (list+head).

etc.

这篇关于有人能解释这条巨蟒排列code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆