Prime Number Check
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(29))
Fibonacci Series
def fibonacci(n):
fib_series = [0, 1]
for i in range(2, n):
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
print(fibonacci(10))
Sum of Digits
def sum_of_digits(n):
if n == 0:
return 0
return n % 10 + sum_of_digits(n // 10)
print(sum_of_digits(1234))
Factorial Using Recursion
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
Simple Calculator
def calculator(a, b, operation):
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
return a / b
print(calculator(10, 5, '+'))
Count Vowels and Consonants
def count_vowels_consonants(string):
vowels = "aeiouAEIOU"
v_count = sum(1 for char in string if char in vowels)
c_count = len([char for char in string if char.isalpha() and char not in vowels])
return v_count, c_count
print(count_vowels_consonants("Hello World"))
Reverse a String
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
Palindrome Checker
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("radar"))
Sorting a List
def sort_list(lst):
return sorted(lst)
print(sort_list([4, 3, 1, 2]))
Remove Duplicates from List
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))
Frequency Counter in List
from collections import Counter
def frequency_counter(lst):
return Counter(lst)
print(frequency_counter([1, 2, 2, 3, 4, 4, 5]))
File Read and Write
def read_write_file():
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
data = infile.read()
outfile.write(data)
# Note: Ensure 'input.txt' file is present.
Word and Line Count in File
def count_words_lines(filename):
with open(filename, 'r') as file:
lines = file.readlines()
word_count = sum(len(line.split()) for line in lines)
return len(lines), word_count
print(count_words_lines("input.txt")) # Note: Ensure 'input.txt' file is present.
Student Class
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
student1 = Student("John", 16, 'A')
print(student1.name, student1.age, student1.grade)
Bank Account Class
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
self.balance -= amount
account1 = BankAccount("Alice", 1000)
account1.deposit(500)
print(account1.balance)
Stack Implementation
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop())
Binary Search
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
print(binary_search([1, 2, 3, 4, 5], 3))
Array Creation and Manipulation
import numpy as np
array = np.array([1, 2, 3])
print(array * 2)
Line Plot Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()