Lesson 5.2 · Write it
Swap halves
A functionPython or Java10 tests, 7 of them hidden
On a phone? Put the lines in order instead
Write a function that swaps the two halves of a text value.
texthas an even number of characters, and at least 2. It contains only English letters, digits, spaces and punctuation.- The two halves have the same number of characters. The first half is the one at the start of
text. - Return the second half followed by the first half.
Only the value your function returns is checked.
def swap_halves(text: str) -> str
Examples
Your function is tested on 10 cases: the 3 examples below, and 7 hidden ones that check the rules above.
- swap_halves("abcd") should return "cdab": ab and cd change places (rule 3)
- swap_halves("ab") should return "ba": two characters, the fewest allowed: each half is one character (rule 1)
- swap_halves("a tree") should return "reea t": a space is a character, and moves with its half (rule 2)
public static String swapHalves(String text)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 10 cases: the 3 examples below, and 7 hidden ones that check the rules above.
- swapHalves("abcd") should return "cdab": ab and cd change places (rule 3)
- swapHalves("ab") should return "ba": two characters, the fewest allowed: each half is one character (rule 1)
- swapHalves("a tree") should return "reea t": a space is a character, and moves with its half (rule 2)