Skip to content
ExamSpine

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.

  1. text has an even number of characters, and at least 2. It contains only English letters, digits, spaces and punctuation.
  2. The two halves have the same number of characters. The first half is the one at the start of text.
  3. 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)

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)
solution.pySolution.java