Python exercise 12: find the hidden ball

Table of Contents

Question

  • Create a function that returns the letter position where the ball final position is once the swapping is finish.
  • There are three cups on a table, at positions A, B, and C. At the start, there is a ball hidden under the cup at position B.

  • There will be several swap perform, represented by two letters.
  • For example, if I swap the cups at positions A and B, this can be represented as AB or BA.

Examples

cup_swapping(["AB", "CA"]) ➞ "C"

cup_swapping(["AC", "CA", "CA", "AC"]) ➞ "B"

cup_swapping(["BA", "AC", "CA", "BC"]) ➞ "A"

My solution

  • initialise a current position "B"
  • iterate over the list of swap combination
    • iterate over each swap combination
      • check the ball have been swap
        • if current position is exist in the swap combination, it is swapped
          • update the current position to another letter
          • if current_position equals to the first letter
            • the final letter is the current position
          • if current_position not equal the first letter
            • the first letter is the current position
  • print the final position
def cup_swapping(swaps):  
    current_position = "B"  
    for move in swaps:  
        if current_position in move:  
            if current_position == move[0]:  
                current_position = move[1]  
            else:  
                current_position = move[0]  
    return current_position 

Solution by others

Method 1

  • shorten version of my answer
def cup_swapping(swaps):  
    current_position = "B"  
    for move in swaps:  
        if current_position in move:  
            current_position = move[1] if move[0] == current_position else move[0]  
    return current_position

Method 2

def cup_swapping(swaps, current_position="B"):  
    for move in swaps:  
        current_position = move.replace(current_position, "") if current_position in move else current_position  
    return current_position
  • key point
  • iterate over each swap
    • in the swap, there is two letter
    • if the current position appear in the swap, replace that letter with empty string
      • i.e. replace "AB" to "A" if current position is "A"
      • and also update the current position to the remaining single letter
    • if the current position do not appear in the swap, keep the current position

      My reflection

  • It is a good feeling to solve a problem without hint. First I got stuck when just write the code, then I try to solve the question by writing the algorithm down, it sudden feel much easier to think. Thus, I will make the habit the write down the algorithm first rather coding at first. Beside, I learn new way to shorten the if else statement

Credit

challenge found on edabit

Leave a Reply