简体   繁体   中英

python loops instead of recursion

I am a newbie in python . Guys I have written one function which checks that the list is palindrome or not but I wanted to replace it with pure looping statements .Do u have any solution or do I have to use recursive function compulsorily .

import json

def reverse(x):
    if isinstance(x, list):
        return [reverse(x) for x in x[::-1]]
    return x

def palindrome(x):
    return x == reverse(x)

st=raw_input("Enter List : ")

lst=json.loads(st)
print palindrome(lst)

check this...

>>> def palindrome(n):
     return n == n[::-1]

>>> palindrome('chk')
False
>>> palindrome('chc')
True
>>> 

Check this out:

def is_palindrome(lst):
    n = len(lst)
    p, q = 0, n - 1
    while p <= q:
        pitem, qitem = lst[p], lst[q]
        if isinstance(pitem, list) and isinstance(qitem, list):
            if len(pitem) != len(qitem):
                return False
            if p == q:
                lst[p:p+1] = pitem
                q = p + len(pitem) - 1
            else:
                lst[p:p+1] = pitem
                q += len(pitem) - 1
                lst[q:q+1] = qitem
                q += len(qitem) - 1
            continue
        elif pitem != qitem:
            return False
        p += 1;
        q -= 1
    return True

Above code also passes for nested list:

assert is_palindrome([1, 2, 3, 2, 1])
assert not is_palindrome([[0, 1]])
assert not is_palindrome([[0, 1, 1]])
assert is_palindrome([[0, 1, 0]])
assert is_palindrome([1, [1, 2], 3, [2, 1], 1])

You can do it with a simple loop:

def is_palindrome(s):
   n = len(s)
   for i in range(n / 2):
      if s[i] != s[n - 1 - i]:
         return False
   return True

It's worth to mention, that above function uses only n / 2 comparisons and the below solution uses n comparisons:

def is_palindrome(s):
   return s == s[::-1]
def palindrome(x):
    q = [x]
    while q:
        x = q.pop()
        if isinstance(x, list) and x:
            if isinstance(x[0], list) and isinstance(x[-1], list):
                q.append(x[0] + x[-1])
            elif x[0] != x[-1]:
                return False
            q.append(x[1:-1])
        elif isinstance(x, str):
            q.append(list(x))
    return True

def palindrome(x):
    q = [x]
    while q:
        x = q.pop()
        if isinstance(x, (str, list)):
            for i in range(len(x) + 1 // 2):
                if isinstance(x[i], list) and isinstance(x[-i-1], list):
                    q.append(x[i] + x[-i-1])
                elif x[i] != x[-i-1]:
                    return False
    return True

>>> palindrome('cat')
False
>>> palindrome('yay')
True
>>> palindrome([1, 2,3,[2],1])
False
>>> palindrome([1, [2,3,[4]],[[4],3,2],1])
True
>>> palindrome([[2,3], [2,3]])
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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