2016-11-04 1 views
0

파이썬 할당에 대한 작업을하고 있습니다. 재귀 적으로 옵션을 거치지 않고 할당을 롤백하려면 임의 생성기를 사용해야합니다.파이썬 할당이 올바른 대답을 찾지 못했습니다.

간단한 대답으로 고전적인 문제이지만 임의 선택은 우연히 그것을 찾아야합니다. 함수가 견고한 것처럼 출력이 같은 패턴을 반복하는 이유를 알 수 없습니다. 엔티티의 동일한 이동을 유발하는 문제가 있습니까?

EDIT : 게시 된 블록이 반복적으로 출력되지만 모든 요소가 'west'목록에 있으면 중지되어야합니다.

배정 : 농부, 늑대, 염소, 양배추와 함께 농부는 모든 개체를 강 서쪽으로 이동해야합니다. 늑대, 염소 및 양배추 한쪽에 혼자 머무를 수 없습니다. 늑대가 염소를 먹을 것이며 염소가 한쪽 (동쪽 또는 서쪽)에 혼자 있다면 양배추가 먹을 것입니다. 이러한 제한은 금지 된 [] 목록에 의해 반영되며 요소가 강변을 변경할 때마다 확인해야합니다.

코드 :

import random 

# The following comments and some changes in the code were provided by Mr. Alexey Pogodin. 
# Code has been changed to follow these guidelines. 
# All style recommendations below are based on PEP 8 (Style Guide for Python Code) 
# http://www.python.org/dev/peps/pep-0008/ 
# Python module names should be all-lowercase. 
# Global variable names should be lowercase, with words separated by underscores as necessary to improve readability. 
# Always surround these binary operators with a single space on either side: assignment, augmented assignment, 
# comparisons, Booleans 
# whitespace after comma is required 

east = ['C', 'F', 'G', 'W'] 
west = [] 
forbidden = [['C', 'G', 'W'],['C', 'G'],['G', 'W']] 

#Complete the following function so it Prints the objects at East and then the objects at West========================== 
def print_contains(east, west): 
    print(east) 
    print(west) 

    return 

#Go west: Complete this function according to the instructions on HW4 
def go_west(east, west): 
    west.append('F') 
    east.remove('F') 

    isForbidden = 1 

    while isForbidden == 1: 
     curr = random.choice(east) 
     west.append(curr) 
     east.remove(curr) 

     if (all(x in east for x in forbidden[0]) or 
       all(x in east for x in forbidden[1]) or 
       all(x in east for x in forbidden[2])): 
      isForbidden = 1 
      east.append(curr) 
      west.remove(curr) 
     else: 
      isForbidden = 0 
      break 


    print_contains(east, west) 
    print('-------------------------------------\n') 
    return east, west 




#Go East: Complete this function according to the instructions on HW4 
def go_east(east, west): 
    east.append('F') 
    west.remove('F') 

    isForbidden = 1 

    while isForbidden == 1: 
     curr = random.choice(west) 
     east.append(curr) 
     west.remove(curr) 

     if (all(x in west for x in forbidden[0]) or 
       all(x in west for x in forbidden[1]) or 
       all(x in west for x in forbidden[2])): 
      isForbidden = 1 
      west.append(curr) 
      east.remove(curr) 
     else: 
      isForbidden = 0 
      break 


    print_contains(east, west) 
    print('-------------------------------------\n')  
    return east, west 


# Solution: This function returns True if all objects are on the West side otherwise returns False (One line of code)  
def solution(): 
    if not east: 
     return True 
    else: 
     return False 



#DO not change anything in the following lines. Your job is to complete the functions above. 
# Main 

print_contains(east, west) 
print('-------------------------------------') 

condition = True 
while condition: 
    east, west = go_west(east,west) 
    if not solution(): 
     east, west = go_east(east,west) 
    else: 
     condition = False 

출력 : 농부

당신이 동쪽으로 이동
['C', 'W', 'F', 'G'] 
[] 
------------------------------------- 

['W', 'C'] 
['F', 'G'] 
------------------------------------- 

['W', 'C', 'F', 'G'] 
[] 
------------------------------------- 

['W', 'C'] 
['F', 'G'] 
------------------------------------- 

['W', 'C', 'F', 'G'] 
[] 
------------------------------------- 

['W', 'C'] 
['F', 'G'] 
------------------------------------- 

['W', 'C', 'F', 'G'] 
[] 
------------------------------------- 
etc... 
+0

금지 목록과 관련된 'for' 루프는 무엇입니까? – Rodolfo

+0

@Rodolfo 과제를 설명하기 위해 편집했습니다. – BleuGamer

+0

코드는 실제로 전혀 파이썬이 아니므로 이해하기가 약간 혼란 스럽습니다. 파이썬은 부울을 지원하기 때문에'0'과'1' 대신'False'와'True'를 사용하십시오. 게다가,'1'은'True'의 부울 값을 가지므로'while isForbidden == 1'을 쓰지 말고'while isForbidden' 만 쓰십시오 (물론 다른 상태를 구현하고 싶지는 않지만 코드는 그렇지 않습니다).). 게다가 파이썬에서 2 년 동안 프로그래밍을 해왔지만 결코'all' 메소드를 사용하지 못했습니다. 네가 필요하다고 생각하지 않아. –

답변

2

, 당신은 항상 선박 항목. 첫 번째 여행 (서쪽으로 이동) 후 서쪽 해안에는 단 하나의 항목 만 있습니다. 따라서 동쪽으로 나가는 농부 동행을 선택하는 것은 서부 출품 한 것입니다. 그래서 처음에는 동쪽 해안에 있던 동일한 아이템으로 끝납니다. 강물 사이를 오가는 물건을 무작위로 선적했습니다.

한 가지 해결 방법은 제공 할 빈 항목을 삽입하는 것입니다. 그것은 무작위로 고른 것이고, 농부는 그 자신을 가로 지르 게됩니다. 어떤 경우에는 퍼즐을 해결할 수 있기를 원하는 것입니다.

관련 문제