# Code 1: Fibonacci generator (20+ lines)
def fibonacci(n):
"""Generate Fibonacci sequence up to n terms."""
seq = [0, 1]
while len(seq) < n:
seq.append(seq[-1] + seq[-2])
return seq
def print_fibonacci(n):
fib_seq = fibonacci(n)
for i, val in enumerate(fib_seq):
print(f"Fib({i}) = {val}")
if __name__ == "__main__":
print_fibonacci(25)
python
# Code 2: Simple class with inheritance and method override (22 lines)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
def main():
animals = [Dog("Rex"), Cat("Whiskers"), Animal("Generic")]
for animal in animals:
print(animal.speak())
if __name__ == "__main__":
main()
python
# Code 3: A simple text-based calculator (22 lines)
def calculator():
print("Simple calculator. Type 'exit' to quit.")
while True:
expr = input("Enter expression (e.g. 2 + 2): ").strip()
if expr.lower() == "exit":
print("Exiting calculator.")
break
try:
result = eval(expr, {"__builtins__": None}, {})
print(f"Result: {result}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
calculator()
python
# Code 4: Prime checker with list comprehension (20+ lines)
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
def print_primes_up_to(limit):
primes = [n for n in range(2, limit+1) if is_prime(n)]
print(f"Primes up to {limit}:")
for p in primes:
print(p, end=" ")
print()
if __name__ == "__main__":
print_primes_up_to(50)
python
# Code 5: Simple guessing game (20 lines)
import random
def guessing_game():
number = random.randint(1, 100)
attempts = 0
print("Guess the number between 1 and 100")
while True:
guess = input("Enter your guess: ")
if not guess.isdigit():
print("Please enter a valid number.")
continue
guess = int(guess)
attempts += 1
if guess == number:
print(f"Correct! You guessed it in {attempts} tries.")
break
elif guess < number:
print("Too low.")
else:
print("Too high.")
if __name__ == "__main__":
guessing_game()
python
# Code 6: Basic CSV file read/write (24 lines)
import csv
def write_csv(filename):
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 35, "Chicago"]
]
with open(filename, "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
def read_csv(filename):
with open(filename, newline="") as f:
reader = csv.reader(f)
for row in reader:
print(", ".join(row))
if __name__ == "__main__":
filename = "people.csv"
write_csv(filename)
print("CSV content:")
read_csv(filename)
python
# Code 7: Simple HTTP server (23 lines)
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type","text/html")
self.end_headers()
self.wfile.write(b"<html><body><h1>Hello from server!</h1></body></html>")
def run_server():
server_address = ("", 8000)
httpd = HTTPServer(server_address, SimpleHandler)
print("Starting server on port 8000...")
httpd.serve_forever()
if __name__ == "__main__":
run_server()
python
# Code 8: Palindrome checker for strings (20 lines)
def is_palindrome(s):
s = ''.join(c.lower() for c in s if c.isalnum())
return s == s[::-1]
def test_palindromes():
test_strings = [
"A man, a plan, a canal: Panama",
"racecar",
"hello",
"No lemon, no melon"
]
for s in test_strings:
print(f"'{s}' is palindrome? {is_palindrome(s)}")
if __name__ == "__main__":
test_palindromes()
python
# Code 9: Merge two sorted lists into one sorted list (20 lines)
def merge_sorted_lists(a, b):
merged = []
i, j = 0, 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
merged.append(a[i])
i += 1
else:
merged.append(b[j])
j += 1
merged.extend(a[i:])
merged.extend(b[j:])
return merged
if __name__ == "__main__":
a = [1,3,5,7]
b = [2,4,6,8]
print("Merged list:", merge_sorted_lists(a, b))
python
# Code 10: Count frequency of words in a text (21 lines)
from collections import Counter
def word_frequency(text):
words = [w.lower() for w in text.split()]
freq = Counter(words)
return freq
if __name__ == "__main__":
sample_text = "This is a test. This test is simple. Simple test is good."
frequency = word_frequency(sample_text)
for word, count in frequency.items():
print(f"{word}: {count}")
If you'd like more, just ask!
python
# Code 1: Bubble sort implementation (21 lines)
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break
return arr
if __name__ == "__main__":
data = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", data)
sorted_data = bubble_sort(data)
print("Sorted array:", sorted_data)
python
# Code 2: Recursive factorial function (20 lines)
def factorial(n):
if n < 0:
raise ValueError("Negative numbers do not have factorial.")
if n == 0 or n == 1:
return 1
return n * factorial(n-1)
def test_factorial():
test_values = [0, 1, 5, 7]
for val in test_values:
print(f"Factorial of {val} is {factorial(val)}")
if __name__ == "__main__":
test_factorial()
python
# Code 3: Basic todo list with CRUD operations (22 lines)
todo_list = []
def add_task(task):
todo_list.append(task)
print(f"Added task: {task}")
def list_tasks():
print("Todo List:")
for i, task in enumerate(todo_list, 1):
print(f"{i}. {task}")
def delete_task(index):
if 0 <= index < len(todo_list):
removed = todo_list.pop(index)
print(f"Removed task: {removed}")
else:
print("Invalid task number.")
if __name__ == "__main__":
add_task("Learn Python")
add_task("Write code")
list_tasks()
delete_task(0)
list_tasks()
python
# Code 4: Merge sort algorithm (24 lines)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort(arr):
if len(arr) <=1:
return arr
mid = len(arr)//2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
if __name__ == "__main__":
array = [38, 27, 43, 3, 9, 82, 10]
print("Original:", array)
sorted_array = merge_sort(array)
print("Sorted:", sorted_array)
# Code 8: Count vowels in a string (20 lines)
def count_vowels(s):
vowels = 'aeiou'
s = s.lower()
count = {v:0 for v in vowels}
for char in s:
if char in vowels:
count[char] +=1
return count
if __name__ == "__main__":
text = "This is an example sentence to count vowels."
vowel_counts = count_vowels(text)
print(f"Vowel counts in: '{text}'")
for v, c in vowel_counts.items():
print(f"{v}: {c}")
python
# Code 9: Check balanced parentheses (22 lines)
def is_balanced(s):
stack = []
pairs = {')':'(', ']':'[', '}':'{'}
for char in s:
if char in '([{':
stack.append(char)
elif char in ')]}':
if not stack or stack.pop() != pairs[char]:
return False
return not stack
if __name__ == "__main__":
tests = ["()", "([])", "([)]", "{[]}", "((())"]
for test in tests:
print(f"{test}: {is_balanced(test)}")
python
# Code 10: Read and write JSON file (22 lines)
import json
def write_json(filename, data):
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
def read_json(filename):
with open(filename) as f:
return json.load(f)
if __name__ == "__main__":
data = {
"name": "Alice",
"age": 30,
"languages": ["English", "French"]
}
filename = "data.json"
write_json(filename, data)
read_data = read_json(filename)
print(read_data)