BASHA TECH

[HackerRank][Python] 본문

Activity/Coding Test

[HackerRank][Python]

Basha 2023. 4. 11. 11:23
728x90

Task

Complete the function displayPathtoPrincess which takes in two parameters - the integer N and the character array grid. The grid will be formatted exactly as you see it in the input, so for the sample input the princess is at grid[2][0]. The function shall output moves (LEFT, RIGHT, UP or DOWN) on consecutive lines to rescue/reach the princess. The goal is to reach the princess in as few moves as possible.

 

The above sample input is just to help you understand the format. The princess ('p') can be in any one of the four corners.

 

Scoring

Your score is calculated as follows : (NxN - number of moves made to rescue the princess)/10, where N is the size of the grid (3x3 in the sample testcase).

 

def displayPathtoPrincess(n, grid):
    # Find the position of the princess and the bot
    for i in range(n):
        for j in range(n):
            if grid[i][j] == 'p':
                princess_row, princess_col = i, j
            elif grid[i][j] == 'm':
                bot_row, bot_col = i, j
                
    # Determine the moves to rescue the princess
    row_moves = princess_row - bot_row
    col_moves = princess_col - bot_col
    
    # Display the moves to rescue the princess
    if row_moves > 0:
        print("DOWN\n" * row_moves, end="")
    elif row_moves < 0:
        print("UP\n" * abs(row_moves), end="")
        
    if col_moves > 0:
        print("RIGHT\n" * col_moves, end="")
    elif col_moves < 0:
        print("LEFT\n" * abs(col_moves), end="")
        

# Get the input from the user
n = int(input())
grid = []
for i in range(n):
    grid.append(input().strip())

# Call the function to display the moves to rescue the princess
displayPathtoPrincess(n, grid)

 

This is a Python script that prompts the user to input the size of the grid (n) and the grid itself (grid). It then calls the function displayPathtoPrincess with these parameters.

 

However, the function displayPathtoPrincess is not implemented in this script. Instead, there is a comment saying "print all the moves here" indicating that the function's implementation is missing and needs to be added.

To implement the function, you can use the code provided in my previous answer as a starting point. Here's the modified code that takes the input from the user and calls the displayPathtoPrincess function:

 

This code prompts the user to input the size of the grid (n) and the grid itself (grid) using the input() function. It then calls the displayPathtoPrincess function with these parameters to display the moves required to rescue the princess.

728x90
반응형
Comments