简体   繁体   English

python中的递归函数不会自行调用

[英]Recursive function in python does not call itself out

The problem is formulated as follows: 问题的表述如下:

Write a recursive function that, given a string, checks if the string is formed by two halves equal to each other (ie s = s1 + s2, with s1 = s2), imposing the constraint that the equality operator == can only be applied to strings of length ≤1. 编写一个递归函数,给定一个字符串,检查字符串是否由彼此相等的两半组成(即s = s1 + s2,s1 = s2),强加等式运算符==的约束只能应用到长度≤1的字符串。 If the length of the string is odd, return an error. 如果字符串的长度为奇数,则返回错误。

I wrote this code in Python 2.7 that is correct (it gives me the right answer every time) but does not enter that recursive loop at all. 我在Python 2.7中编写了这个代码是正确的(它每次都给我正确的答案),但根本不进入那个递归循环。 So can I omit that call here? 那我可以在这里省略这个电话吗?

def recursiveHalfString(s):
#@param s: string
#@return bool

 if (len(s))%2==0:     #verify if the rest of the division by 2 = 0 (even number)

  if len(s)<=1:        # case in which I can use the == operator
   if s[0]==s[1]:
    return True
   else:
    return False

  if len(s)>1:                           
   if s[0:len(s)/2] != s[len(s)/2:len(s)]:     # here I used != instead of ==
    if s!=0:
     return False
    else:
     return recursiveHalfString(s[0:(len(s)/2)-1]+s[(len(s)/2)+1:len(s)])    # broken call    
   return True

 else:
   return "Error: odd string"

The expected results are True if the string is like "abbaabba" or False when it's like anything else not similat to the pattern ("wordword") 如果字符串像“abbaabba”那样预期结果为True,或者当它与其他模式(“wordword”)不相似时为False

This is a much simplified recursive version that actually uses the single char comparison to reduce the problem size: 这是一个非常简化的递归版本,它实际上使用单个char比较来减少问题大小:

def rhs(s):
    half, rest = divmod(len(s), 2)
    if rest:  # odd length
        raise ValueError  # return 'error'
    if half == 0:  # simplest base case: empty string
        return True
    return s[0] == s[half] and rhs(s[1:half] + s[half+1:])

It has to be said though that, algorithmically, this problem does not lend itself well to a recursive approach, given the constraints. 必须要说的是,在算法上,考虑到约束,这个问题不适合递归方法。

Here is another recursive solution. 这是另一种递归解决方案。 A good rule of thumb when taking a recursive approach is to first think about your base case . 采用递归方法时,一个好的经验法则是首先考虑你的基本情况

def recursiveHalfString(s):
    # base case, if string is empty
    if s == '':
        return True

    if (len(s))%2==0:
        if s[0] != s[(len(s)/2)]:
            return False
        else:
            left = s[1:len(s)/2]  # the left half of the string without first char
            right = s[(len(s)/2)+1: len(s)] # the right half without first char
            return recursiveHalfString(left + right)
    else:
        return "Error: odd string"

print(recursiveHalfString('abbaabba'))   # True
print(recursiveHalfString('fail'))       # False
print(recursiveHalfString('oddstring'))  # Error: odd string

This function will split the string into two halves, compare the first characters and recursively call itself with the two halves concatenated together without the leading characters. 此函数将字符串分成两半,比较第一个字符并递归调用自身,两个连接在一起而没有前导字符。

However like stated in another answer, recursion is not necessarily an efficient solution in this case. 但是,如另一个答案中所述,递归在这种情况下不一定是有效的解决方案。 This approach creates a lot of new strings and is in no way an optimal way to do this. 这种方法创建了许多新字符串,绝不是最佳方法。 It is for demonstration purposes only. 它仅用于演示目的。

Another recursive solution that doesn't involve creating a bunch of new strings might look like: 另一个不涉及创建一堆新字符串的递归解决方案可能如下所示:

def recursiveHalfString(s, offset=0):
    half, odd = divmod(len(s), 2)
    assert(not odd)
    if not s or offset > half:
        return True
    if s[offset] != s[half + offset]:
        return False
    return recursiveHalfString(s, offset + 1)

However, as @schwobaseggl suggested, a recursive approach here is a bit clunkier than a simple iterative approach: 但是,正如@schwobaseggl所建议的那样,这里的递归方法比简单的迭代方法有点笨拙:

def recursiveHalfString(s, offset=0):
    half, odd = divmod(len(s), 2)
    assert(not odd)
    for offset in range(half):
        if s[offset] != s[half + offset]:
            return False
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM