# Fibonacci sequence generator up to n terms
def fibonacci(n):
sequence = [0, 1]
while len(sequence) < n:
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
print(fibonacci(20))
# Prime number checker for numbers up to n
def primes_up_to(n):
primes = []
for num in range(2, n+1):
is_prime = True
for div in range(2, int(num**0.5)+1):
if num % div == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes
print(primes_up_to(50))
# Bubble sort implementation on a list
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))
# Calculate factorial of a number recursively
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n-1)
print(factorial(10))
# Check if a string is a palindrome
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("A man a plan a canal Panama"))
# Simple class representing a bank account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited ${amount}. New balance is ${self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount}. New balance is ${self.balance}")
else:
print("Insufficient balance or invalid amount.")
account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)
# Read a text file and count word frequency
from collections import Counter
import re
def count_words(filename):
with open(filename, 'r', encoding='utf-8') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
return Counter(words)
# Example: Make sure 'sample.txt' exists in the working directory
# print(count_words('sample.txt'))
# Merge two sorted lists into one sorted list
def merge_sorted_lists(list1, list2):
merged = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
merged.extend(list1[i:])
merged.extend(list2[j:])
return merged
print(merge_sorted_lists([1, 3, 5, 7], [2, 4, 6, 8]))
# Count vowels in a given string
def count_vowels(text):
vowels = "aeiouAEIOU"
count = {v:0 for v in vowels}
for char in text:
if char in count:
count[char] += 1
return count
print(count_vowels("The quick brown fox jumps over the lazy dog."))
# Generate a multiplication table for numbers 1 to 10
def multiplication_table():
for i in range(1, 11):
for j in range(1, 11):
print(f"{i*j:4}", end="")
print()
multiplication_table()
# Find GCD (Greatest Common Divisor) using Euclid's algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(270, 192))
# Simple stopwatch class using time module
import time
class Stopwatch:
def __init__(self):
self.start_time = None
self.elapsed = 0
self.running = False
def start(self):
if not self.running:
self.start_time = time.time()
self.running = True
def stop(self):
if self.running:
self.elapsed += time.time() - self.start_time
self.running = False
def reset(self):
self.start_time = None
self.elapsed = 0
self.running = False
def elapsed_time(self):
if self.running:
return self.elapsed + (time.time() - self.start_time)
return self.elapsed
sw = Stopwatch()
sw.start()
time.sleep(2)
sw.stop()
print(f"Elapsed time: {sw.elapsed_time():.2f} seconds")
# Read integers from a list and output only even numbers
def filter_even_numbers(numbers):
evens = [num for num in numbers if num % 2 == 0]
return evens
print(filter_even_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# Convert decimal to binary string representation
def decimal_to_binary(n):
if n == 0:
return "0"
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //=2
return binary
print(decimal_to_binary(156))
# Check if two strings are anagrams
def are_anagrams(s1, s2):
return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower())
print(are_anagrams("Listen", "Silent"))
print(are_anagrams("Hello", "World"))
# Find the longest word in a sentence
def longest_word(sentence):
words = sentence.split()
longest = max(words, key=len)
return longest
print(longest_word("The quick brown fox jumps over the lazy dog"))
# Find all divisors of a number
def find_divisors(n):
divisors = []
for i in range(1, n+1):
if n % i == 0:
divisors.append(i)
return divisors
print(find_divisors(36))
# Detect if a number is Armstrong number
def is_armstrong(number):
digits = [int(d) for d in str(number)]
power = len(digits)
total = sum([d ** power for d in digits])
return total == number
print(is_armstrong(153)) # True
print(is_armstrong(123)) # False
# Basic calculator supporting +, -, *, /
def calculator(a, b, op):
if op == '+':
return a + b
if op == '-':
return a - b
if op == '*':
return a * b
if op == '/':
if b != 0:
return a / b
else:
return "Error: Division by zero"
return "Unsupported operation"
print(calculator(10, 5, '+'))
print(calculator(10, 0, '/'))
# Convert temperature from Celsius to Fahrenheit and vice versa
def convert_temperature(temp, unit):
if unit.lower() == 'c':
return (temp * 9/5) + 32
elif unit.lower() == 'f':
return (temp - 32) * 5/9
else:
return "Unknown unit"
print(convert_temperature(100, 'C'))
print(convert_temperature(212, 'F'))
# Bubble sort descending order and count swaps
def bubble_sort_desc(arr):
n = len(arr)
swaps = 0
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] < arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swaps += 1
return arr, swaps
sorted_arr, total_swaps = bubble_sort_desc([5, 2, 9, 1, 5, 6])
print(sorted_arr)
print(f"Total swaps: {total_swaps}")
# Recursive function to sum digits of a number
def sum_digits(n):
if n == 0:
return 0
return (n % 10) + sum_digits(n // 10)
print(sum_digits(12345)) # Output: 15
# Generate a list of all prime factors of a number
def prime_factors(n):
factors = []
divisor = 2
while n >= 2:
if n % divisor == 0:
factors.append(divisor)
n //= divisor
else:
divisor += 1
return factors
print(prime_factors(56))
# Simple decorator to measure function execution time
import time
def timeit(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function {func.__name__!r} executed in {(end - start):.4f} seconds")
return result
return wrapper
@timeit
def slow_function(n):
time.sleep(n)
return "Done"
print(slow_function(2))
# Find second largest element in a list
def second_largest(nums):
first = second = float('-inf')
for n in nums:
if n > first:
second = first
first = n
elif first > n > second:
second = n
if second == float('-inf'):
return None
return second
print(second_largest([10, 20, 4, 45, 99, 99]))
# Simple Tic Tac Toe game logic check for winner
def check_winner(board):
# Rows, columns and diagonals
lines = board + [[board[r][c] for r in range(3)] for c in range(3)] + \
[[board[i][i] for i in range(3)], [board[i][2-i] for i in range(3)]]
for line in lines:
if line.count(line[0]) == 3 and line[0] != ' ':
return f"Winner: {line[0]}"
return "No winner"
board = [
['X', 'O', 'X'],
['O', 'O', 'X'],
[' ', ' ', 'O']
]
print(check_winner(board))
# Convert Roman numerals to integers
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000}
total = 0
prev = 0
for char in reversed(s):
curr = roman_dict[char]
if curr >= prev:
total += curr
else:
total -= curr
prev = curr
return total
print(roman_to_int("MCMXCIV")) # Output: 1994
# Generate Pascal's triangle up to n rows
def pascals_triangle(n):
triangle = []
for i in range(n):
row = [1]
if i > 0:
last_row = triangle[-1]
row.extend([last_row[j] + last_row[j+1] for j in range(len(last_row)-1)])
row.append(1)
triangle.append(row)
return triangle
for row in pascals_triangle(10):
print(row)
# Check if a year is a leap year
def is_leap_year(year):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
return False
print(is_leap_year(2000)) # True
print(is_leap_year(1900)) # False
print(is_leap_year(2024)) # True
# Function to flatten a nested list
def flatten(nested_list):
flat = []
for item in nested_list:
if isinstance(item, list):
flat.extend(flatten(item))
else:
flat.append(item)
return flat
print(flatten([1, [2, [3, 4], 5], 6, [7, 8]]))
# Draw a hollow square of size n with '*'
def hollow_square(n):
for i in range(n):
if i == 0 or i == n-1:
print('*' * n)
else:
print('*' + ' '*(n-2) + '*')
hollow_square(10)