2013-02-07 2 views
0

나의 임무는 파이썬에서 palindrome 프로그램을 생각해내는 것이었다. 나는 이제 내 강사 Stack의를 사용하여 변환이 원하는 여기스택을 사용하는 Python Palindrom 프로그램

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

print (isPalindrome("maam")) #returns TRUE 
print (isPalindrome("madam")) #returns TRUE 
print (isPalindrome("hello")) #returns FALSE 
print (isPalindrome("macdam")) #returns FALSE 
print (isPalindrome("buffalolaffub")) #returns TRUE 
print (isPalindrome("argentina")) #returns FALSE 

을했다한다. 아무도 이것으로 도울 수 있습니까? 스택들이 자연스럽게 일을 역 밖으로 처음에서 마지막 음부터

class Stack: 

    def __init__(self): 
     self.items = [] 

    def isEmpty(self): 
     return self.items == [] 

    def push(self, item): 
     self.items.append(item) 

    def pop(self): 
     return self.items.pop() 

    def peek(self): 
     return self.items[len(self.items)-1] 

    def size(self): 
     return len(self.items) 

답변

0

:

여기에 내가 가지고있는 Stack 데이터 구조입니다. 당신은 문자열을 반복 할 수 있고, 전반을 누르고 나서 반으로 뛰어 오르고 비교할 수 있습니다.

+0

난 그냥 시작하기에 어려움을 겪고 있어요 .. 내가 익숙하지 오전 python language @cmd – user2052503

+0

@ user2052503이 경우에는 http://docs.python.org/2/tutorial/index.html 튜토리얼을 실행합니다. 그것의 상당히 빠르고 시작하는 중대한 도움. – cmd

2

을 감안할 때 :

tests=["maam", "madam","hello","macdam","buffalolaffub","argentina"] 
이 같은 것 회문되는 문자열에 대한

개성있는 파이썬 검사 :

word==word[::-1] # True or False 

그래서이 같은 회문의 목록을 인쇄 할 수 있습니다

print [word for word in tests if word==word[::-1]]  

스택을 사용하여이 작업을 수행하려면 문자열을 목록으로 변환 한 다음 파이썬 목록/스택 작업으로 변환해야합니다 ons를 사용할 수 있습니다. 여기에 작은 데모는 다음과 같습니다

def stack_cmp(s1,s2): 
    l1=list(s1) 
    l2=list(s2) 
    if len(l1)!=len(l2): return False 
    while True: 
     try: 
      if l1.pop()!=l2.pop(): return False 
     except IndexError: 
      return True 

print [word for word in tests if stack_cmp(word, word[::-1])] 

예외를 사용하지 않는 stack_cmp의 대체 버전 :

def stack_cmp(s1,s2): 
    l1=list(s1) 
    l2=list(s2) 
    while l1 and l2: 
     if l1.pop()!=l2.pop(): return False 
    if l1 or l2: return False 
    return True 

다음이 wway 작동합니다

>>> stack_cmp('mmmm','mmmm') 
True 
>>> stack_cmp('mmmm','mmmmm') 
False 

선생님이 반대 수를 목록을 뒤집기 위해 조각을 사용; 즉, revered_list=orig_list[::-1]. 이런 경우, 당신은이를 사용할 수 있습니다

reversed_list=[] 
orig_list_copy=orig_list[:] 
while orig_list_copy: 
    reversed_list.append(orig_list_copy.pop()) # this reverses the list 

을 이것은 palidrome 검사기와 스택 클래스로 작동합니다

class Stack(object): 
    def __init__(self,items): 
     self.items=[] 
     for e in items: 
      self.push(e) 

    def push(self,item): 
     self.items.append(item) 

    def pop(self): 
     return self.items.pop() 

    def __repr__(self): 
     return str(self.items) 

    def isPalindrome(self): 
     tr=Stack([]) 
     t=Stack(self.items) 
     while t.items: 
      tr.push(t.pop()) 
     t=Stack(self.items)  
     while t.items and tr.items: 
      c1=t.pop() 
      c2=tr.pop() 
      print c1,c2 
      if c1!=c2: return False 
     return True  
+0

아래 라인은 '인쇄를 나에게 잘못된 구문 오류를 제공 @the_wolf [테스트에서 단어에 대한 단어를 stack_cmp 경우 (워드, 워드 [:: - 1])]' – user2052503

+0

@the_wolf 내가 그 선을 가지고가는 경우 , 테스트 결과에 & then 테스트 단어를 쓰지 않으면 내 인쇄 결과가 정확하지 않습니다. Heres는 코드 stackDS에서 ... 는' '데프 isPalindrome (단어 1, word2)'스택을 가져옵니다! L1 = 목록 (단어 1) L2 = 목록 (word2) 렌 경우 (L1) = LEN (l2) : False를 반환 참 : 시도 : if l1.pop()! = 12.팝업() : IndexError 제외하고 거짓 을 반환 : 참 수익을' '인쇄 (isPalindrome ("MAAM", "MAAM")) #Expected 출력 : TRUE 인쇄 (isPalindrome ("안녕하세요", "올레")) # 예상 출력 : FALSE' – user2052503

+0

이 문제를 해결하는 데 실패합니다. 스택 클래스를 사용하여 문장 검색을하지 않습니다. – cmd