python中的递归
递归是什么意思呢,我的理解就是函数内部调用自己本身。比如阶乘f(n) = n! = 1 x 2 x 3 x 4 x (n-1) x n = (n-1)! x n = f(n-1) x n,像f(7)=7xf(6)=7x6xf(5)=7x6x5xf(4)=7x6x5x4xf(3)=7x6x5x4x3xf(2)=7x6x5x4x3x2xf(1),如下图
#打印7的阶乘
def fn(num):
if num==1:
return 1
return (num*fn(num-1))
fn(7)
#从10开始一次递减打印数字,到1结束
def print_num(num):
print num
if num==1:
return
print_num(num-1)A
print_num(10)
maya中python的递归
我们可以用它找给定物体的子物体,思路就是判断给定的“父物体”层级下面有没有“子物体”,有的话把“子物体”当做“父物体”调用自身函数继续找,直到没有“子物体”为止。值得注意的是,创建骨骼的话如果不取消选择,骨骼会成为选定物体的子物体。
import pymel.core as pm
import maya.cmds as pc
#创建一条骨骼链
for i in range(10):
pm.joint().setTranslation((5,0,0))
#创建十个球,并依次成为父子关系
a=[]
for i in range(10):
a.append(pm.polySphere(ch=0)[0])
a[i-1].translateX.set(5)
if(len(a)>1):
a[i].setParent(a[i-1])
#递归求所有的子物体
def getChild(sel,child):
for item in sel:
child.append(item)
Children=pm.listRelatives(item,c=1)
if (len(Children)>0):
getChild(Children,child)
sel=pm.ls(sl=1)
b=[]
getChild(sel,b)
mel中的递归
mel我一直以为没有递归,又是自己的无知,和python思路差不多。
global proc getChild(string $parent[],string $child[])
{
for ($item in $parent)
{
$child[size($child)] = $item;
string $Children[] = `listRelatives -c $item`;
if (size($Children)>0)
{
getChild($Children,$child);
}
}
}
string $child[];
clear $child;
string $parent[]=`ls -sl`;
getChild($parent,$child);
print $child;