Skip to content

What is it trying to do?

Read · 1 of 3

Name the purpose

AI code often comes with vague names, or confident comments that don't match. Ignore both: try a tiny input by hand and see what comes out.

Once you can say what the code does in one sentence, you can check that sentence against what it *should* do.

Read this lesson as text

Work out a function's job from what goes in and what comes out.

Name the purpose

AI code often comes with vague names, or confident comments that don't match. Ignore both: try a tiny input by hand and see what comes out.

Once you can say what the code does in one sentence, you can check that sentence against what it *should* do.

Mystery 1

def mystery(nums):
    seen = set()
    out = []
    for x in nums:
        if x not in seen:
            seen.add(x)
            out.append(x)
    return out

n = int(input())
print(*mystery(list(map(int, input().split()))))

What does mystery do?

  • Sorts the numbers
  • Removes repeats, keeping the first copy of each in order
  • Keeps only the numbers that appear twice
Show the answer

Removes repeats, keeping the first copy of each in order. Each number is added to out the first time it's seen and skipped after that. Try 3 1 3 2 1: you get 3 1 2.

Mystery 2

def mystery(s):
    i, j = 0, len(s) - 1
    while i < j:
        if s[i] != s[j]:
            return False
        i += 1
        j -= 1
    return True

print(mystery(input()))

What does mystery check?

  • Whether the text reads the same backwards
  • Whether every letter is different
  • Whether the letters are in alphabetical order
Show the answer

Whether the text reads the same backwards. It compares the first and last letters, then moves both inwards. That's a palindrome check.