ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def reg(name, seen={}, order=[]):
    if name not in seen:
        seen[name] = len(order)
        order = order + [name]
    return seen[name], len(order)
print(reg("a"), reg("b"), reg("a"), reg("c"))
  1. A. (0, 1) (1, 2) (0, 2) (2, 3)
  2. B. (0, 1) (0, 1) (0, 1) (0, 1)
  3. C. (0, 1) (1, 2) (0, 0) (2, 3)
  4. D. (0, 1) (0, 1) (0, 0) (0, 1)

Correct answer: D. (0, 1) (0, 1) (0, 0) (0, 1)

Both defaults are created once, but they are used differently. seen[name] = … mutates the shared dict, so it remembers names across calls. order = order + [name] builds a NEW list and rebinds only the local name; the default list stays [] forever. So every new name gets index len([]) = 0 and the local length 1; the repeat call for 'a' skips the if and sees the untouched default, length 0: (0, 1) (0, 1) (0, 0) (0, 1). The option with indices 0, 1, 2 would be right had the code used order.append(name).

More Python Programming questions

Exams that ask this topic