__str__ 메서드가 실행이 안되고 attribute error가 발생합니다..

조회수 716회
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 28 20:54:55 2021

@author: Salieli
"""

class State:
    def __init__(self, board, goal, moves=0):
        self.board = board
        self.moves = moves
        self.goal = goal

        # i1과 i2를 교환하여 새로운 상태를 반환함
        def get_new_board(self, i1, i2, moves):
            new_board = self.board[:]
            new_board[i1], new_board[i2] = new_board[i2], new_board[i1]

            return State(new_board, self.goal, moves)

        # 자식 노드를 확장하여 리스트에 저장하여 반환하기
        def expand(self, moves):
            result = []
            i = self.board.index(0)
            if not i in [0,1,2]:# up
                    result.append(self.get_new_board(i,i-3,moves))          
                    if not i in [0,3,6]:# LEFT
                       result.append(self.get_new_board(i,i-1,moves))
                    if not i in [2,5,8]:# RIGHT 
                       result.append(self.get_new_board(i,i+1,moves))
                    if not i in [6,7,8]:# DOWN
                       result.append(self.get_new_board(i,i+3,moves))
            return result


        def __str__(self):
            return str(self.board[:3])+"\n"+\
                str(self.board[3:6])+"\n"+\
                str(self.board[6:])+"\n"+\
                "-----------------"

        def __eq__(self,other):
               return self.board == other.board

# 초기상태
puzzle = [2,8,3,
          1,0,4,
          7,6,5]

# 목표 상태
goal = [1,2,3,
        4,5,6,
        7,8,0]

# open list
open_queue = [] 
open_queue.append(State(puzzle, goal)) 

# closed list
closed_queue = []
moves = 0;

while len(open_queue) !=0:
    current = open_queue.pop(0)
    print(current)    
    if current.board == goal:
        print("탐색 성공")
        break    
    moves = current.moves+1             
    closed_queue.append(current)

    for state in current.expand(moves): 
        if (state in closed_queue) or (state in open_queue):
            continue
        else:
            open_queue.append(State)
            print("탐색 실패")

8-puzzle을 DFS방법으로 풀고 그 과정을 출력하는 코드입니다. 코드 자체는 대학 강의 자료에서 그대로 가져온 것이고 정상적으로 실행되는 교수님과 같은 환경에서 실행했다고 생각합니다

하지만 print(current)에서 current = State(puzzle, goal)이지만 str을 통해 리스트가 출력되지 않고 그저 state의 주소가 출력됩니다. (str이 정상적으로 실행되지 않는 것 같습니다)

또한 'State' object has no attribute 'expand' 라는 오류가 출력되는데 오류의 원인을 찾아보았지만 위 코드와는 크게 상관이 없어 보였습니다.. 교수님과 다른 사람들은 정상적으로 실행되는 걸 확인했는데 도대체 왜 안되는 건가요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    파이썬은 indent 가 문법입니다.

    indent 즉 들여쓰기를 잘 확인하세요.

    아랫코드로 해보세요.

    class State:
        def __init__(self, board, goal, moves=0):
            self.board = board
            self.moves = moves
            self.goal = goal
    
        # i1과 i2를 교환하여 새로운 상태를 반환함
        def get_new_board(self, i1, i2, moves):
            new_board = self.board[:]
            new_board[i1], new_board[i2] = new_board[i2], new_board[i1]
    
            return State(new_board, self.goal, moves)
    
        # 자식 노드를 확장하여 리스트에 저장하여 반환하기
        def expand(self, moves):
            result = []
            i = self.board.index(0)
            if not i in [0,1,2]:# up
                result.append(self.get_new_board(i,i-3,moves))
                if not i in [0,3,6]:# LEFT
                   result.append(self.get_new_board(i,i-1,moves))
                if not i in [2,5,8]:# RIGHT 
                   result.append(self.get_new_board(i,i+1,moves))
                if not i in [6,7,8]:# DOWN
                   result.append(self.get_new_board(i,i+3,moves))
            return result
    
    
        def __str__(self):
            return str(self.board[:3])+"\n"+\
                str(self.board[3:6])+"\n"+\
                str(self.board[6:])+"\n"+\
                "-----------------"
    
        def __eq__(self,other):
            return self.board == other.board
    
    • 정말 감사합니다. 파이썬을 처음 써보는 거라 기본적인 걸 몰랐네요.. 괄호를 안쓰는데 어떻게 구분을 하는지 잘 생각해봤어야 했습니다 서재영 2021.10.11 16:39

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)