递归倒置字符数组

描述:

样例输入: 
5 abcde
样例输出:
ebcda 
edcba 

edcba 

分析:

重点是找规律,我们以 9 abcdefghi为例:length=9
 i的序号   交换的序号   交换后i的值 
 i=9      0<--->8      i=7 
 i=7      1<--->7      i=5 
 i=5      2<--->6      i=3 
 i=3      3<--->5      i=1 
 i=1      判断返回
 由此可见,我们要交换的数组序号的普遍计算方法:
 (length-i)/2 <----> length-1-(length-i)/2
 不要问我怎么来的,根据上表找到的规律

代码:

def trans(st,i=None,):   
     if i==None:         
         i=len(st)       
     if i==1 or i==0:#考虑到奇数个或者偶数个
         print()
         for echo in st:
             print(echo,end='')
         return
     length=len(st)     #虽然st长度不变,但下次递归没传此参数
     st[length-1-int((length-i)/2)],st[int((length-i)/2)]=st[int((length-i)/2)],st[length-1-int((length-i)/2)]
     for echo in st:
         print(echo,end='')
     print()
     trans(st,i-2)
 command=input().split()     
 trans(list(command[1]))    
原文地址:https://www.cnblogs.com/thgpddl/p/12368463.html