Design an algorithm in Python that takes in a list of numbers and prints out the first…
- User
Design an algorithm in Python that takes in a list of numbers and prints out the first and last element in the list. lst=[5,3,1,7,9]
Assistant
Design an algorithm in Python that takes in a list of numbers and prints out the first and last element in the list. lst=[5,3,1,7,9]
Problem: Design an algorithm in Python that takes in a list of numbers and prints out the first and last element in the list. lst=[5,3,1,7,9]
Approach: Design: First and Last Element Extraction
Key considerations:
Implement
Args: lst: A list of numbers
Returns: tuple: (first_element, last_element) or None if invalid """ Input validation
Complexity: | O(1) | Direct index access |
Let me implement this solution.
| Metric | Value | Explanation |
|---|---|---|
| Time Complexity | O(1) | Direct index access |
| Space Complexity | O(1) | No additional storage needed |
def print_first_and_last(lst):
"""
Prints the first and last elements of a list.
Args:
lst: A list of numbers
Returns:
tuple: (first_element, last_element) or None if invalid
"""
# Input validation
if lst is None:
print("Error: Input is None")
return None
if not isinstance(lst, list):
print("Error: Input must be a list")
return None
if len(lst) == 0:
print("Error: List is empty")
return None
# Extract first and last elements
first_element = lst[0]
last_element = lst[-1] # Python negative indexing
# Print results
print(f"First element: {first_element}")
print(f"Last element: {last_element}")
return (first_element, last_element)
# Main execution
if __name__ == "__main__":
lst = [5, 3, 1, 7, 9]
print(f"Input list: {lst}\n")
print_first_and_last(lst)
Input list: [5, 3, 1, 7, 9]
First element: 5
Last element: 9
# Test cases
print_first_and_last([]) # Empty list → Error
print_first_and_last([42]) # Single element → 42, 42
print_first_and_last([1, 2]) # Two elements → 1, 2
print_first_and_last(None) # None input → Error
print_first_and_last("not a list") # Wrong type → Error
| Decision | Rationale |
|---|---|
Use lst[-1] for last element | Pythonic, O(1) access, avoids calculating length |
| Return tuple + print | Dual purpose: display result AND allow further use |
| Comprehensive validation | Production-ready code handles malformed inputs |
if __name__ == "__main__" | Allows module import without execution |