Bird
Raised Fist0

Write a polymorphic function combine that accepts either two strings or two lists and returns their concatenation. What is the output of this code?

hard🚀 Application Q15 of Q15
Python - Polymorphism and Dynamic Behavior

Write a polymorphic function combine that accepts either two strings or two lists and returns their concatenation. What is the output of this code?

def combine(a, b):
    if isinstance(a, str) and isinstance(b, str):
        return a + b
    elif isinstance(a, list) and isinstance(b, list):
        return a + b
    else:
        return None

print(combine('Hi, ', 'there!'))
print(combine([1, 2], [3, 4]))
print(combine('Hello', [1, 2]))
A'Hi, there!'\n[1, 2, 3, 4]\nNone
B'Hi, there!'\n[1, 2]\n[3, 4]
CNone\nNone\nNone
D'Hi, there!'\nNone\nNone
Step-by-Step Solution
Solution:
  1. Step 1: Check first call combine('Hi, ', 'there!')

    Both are strings, so returns concatenation 'Hi, there!'.
  2. Step 2: Check second call combine([1, 2], [3, 4])

    Both are lists, so returns concatenated list [1, 2, 3, 4].
  3. Step 3: Check third call combine('Hello', [1, 2])

    Types differ, so returns None.
  4. Final Answer:

    'Hi, there!' [1, 2, 3, 4] None -> Option A
  5. Quick Check:

    Type checks control output [OK]
Quick Trick: Check types of both inputs before combining [OK]
Common Mistakes:
MISTAKES
  • Not checking both inputs' types
  • Trying to combine different types directly
  • Returning wrong default for mismatched types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes