loc and iloc slices differ in one detail that trips everyone up. Model both.
What to build
A program that answers loc and iloc slices on a list of row labels.
Requirements
- Queries are
loc A B(labels A to B, both included) andiloc I J(positions I up to, not including, J). - Print the selected labels separated by spaces, or
emptywhen nothing is selected (for example when A comes after B). For a loc label that does not exist, printKeyError: 'LABEL'.
Input
Line 1: the row labels separated by spaces. Line 2: q. Then q queries.
Output
q lines.
Constraints
1 to 50 distinct labels; 1 ≤ q ≤ 50; 0 ≤ I, J ≤ 100.
Example
Input:
a b c d
3
loc b c
iloc 1 3
loc c b
Output:
b c
b c
empty
Why it works
Positions follow Python's end-excluded rule, while labels have no natural next value to stop before, so pandas includes both ends of a label slice.
Examples
Example 1 · Input
a b c d 3 loc b c iloc 1 3 loc c b
Expected output
b c b c empty
Example 2 · Input
x y z 2 iloc 0 10 loc x x
Expected output
x y z x
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For loc, find the positions of the two labels and keep everything from the first to the second, inclusive.
Hint 2
For iloc, a Python slice labels[i:j] already excludes the end.
Solution
Show one correct solution (try it yourself first)
labels = input().split()
q = int(input())
for _ in range(q):
kind, a, b = input().split()
if kind == "loc":
missing = [x for x in (a, b) if x not in labels]
if missing:
print(f"KeyError: '{missing[0]}'")
continue
chosen = labels[labels.index(a) : labels.index(b) + 1]
else:
chosen = labels[int(a) : int(b)]
print(" ".join(chosen) if chosen else "empty")