List Comprehension and Functions - Python Typing CST Test
Loading…
List Comprehension and Functions — Python Code
Demonstrates Python's list comprehension, type hints, and function definitions with docstrings.
import math
from typing import List, Optional
def fibonacci(n: int) -> List[int]:
"""Generate fibonacci sequence up to n numbers"""
if n <= 0:
return []
elif n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
def find_primes(limit: int) -> List[int]:
"""Find all prime numbers up to limit using sieve"""
primes = []
sieve = [True] * (limit + 1)
for i in range(2, int(math.sqrt(limit)) + 1):
if sieve[i]:
for j in range(i * i, limit + 1, i):
sieve[j] = False
return [i for i in range(2, limit + 1) if sieve[i]]
# Main execution
if __name__ == "__main__":
fib_sequence = fibonacci(10)
print(f"Fibonacci: {fib_sequence}")
primes = find_primes(30)
print(f"Primes up to 30: {primes}")
# List comprehension example
squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"Even squares: {squares}")Python Language Guide
Python is a high-level, dynamically typed, multi-paradigm programming language known for simplicity, readability, and massive ecosystem support. It powers web development, data science, machine learning, automation, scripting, backend systems, and more.
Primary Use Cases
- ▸Backend web development
- ▸Machine learning & AI
- ▸Data analysis & visualization
- ▸Automation & scripting
- ▸API development
- ▸Scientific computing
- ▸DevOps tooling
- ▸Cybersecurity scripting
Notable Features
- ▸Simple, readable syntax
- ▸Massive standard library
- ▸Dynamically typed
- ▸Extensive third-party ecosystem (PyPI)
- ▸Cross-platform
- ▸Strong scientific & ML libraries
Origin & Creator
Created by Guido van Rossum in 1991, inspired by ABC language with a vision of a simple, readable language for everyday programming tasks.
Industrial Note
Python dominates in AI/ML research, automation-heavy engineering teams, fast MVP prototyping, data-driven industries, hybrid cloud pipelines, ETL scripting, scientific computing, and large-scale analytical workflows.