## Question

- Create a function that returns the letter position where the ball final position is once the swapping is finish.

### description

- 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

- 1. initialise a current position "B"
- 2. iterate over the list of swap combination
- 2.1 iterate over each swap combination

- 3. check the ball have been swap
- 3.1 if current position is exist in the swap combination, it is swapped
- 3.2 update the current position
- 3.2.1 if current_position equals to the first letter
- 3.2.2 then final letter is the current position
- 3.3.1 if current_position not equal the first letter
- 3.3.2 then first letter is the current position

- 4. 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

## Top comments (0)