Simple Python Problems
Simple Python Problems
def is_prime(n):
if n <= 1:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
# Example
print(is_prime(7)) # True
2) Palindrome
def is_palindrome(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
# Example
print(is_palindrome("madam")) # True
3) Factorial
def factorial(n):
result = 1
i = 2
while i <= n:
result = result * i
i += 1
return result
# Example
print(factorial(5)) # 120
4) Armstrong Number
def is_armstrong(n):
original = n
count = 0
temp = n
while temp > 0:
count += 1
temp = temp // 10
temp = n
result = 0
while temp > 0:
digit = temp % 10
power = 1
for _ in range(count):
power *= digit
result += power
temp = temp // 10
return result == original
# Example
print(is_armstrong(153)) # True
5) Star Patterns
def pattern1(n):
for i in range(1, n + 1):
for j in range(i):
print("*", end="")
print()
def pattern2(n):
for i in range(n, 0, -1):
for j in range(i):
print("*", end="")
print()
# Example
pattern1(5)
pattern2(5)
6) Fibonacci
def fibonacci(n):
a = 0
b = 1
count = 0
while count < n:
print(a, end=" ")
c = a + b
a = b
b = c
count += 1
# Example
fibonacci(10)
7) Highest in Array
def find_max(arr):
max_val = arr[0]
i = 1
while i < len(arr):
if arr[i] > max_val:
max_val = arr[i]
i += 1
return max_val
# Example
print(find_max([3, 8, 2, 10])) # 10
8) Lowest in Array
def find_min(arr):
min_val = arr[0]
i = 1
while i < len(arr):
if arr[i] < min_val:
min_val = arr[i]
i += 1
return min_val
# Example
print(find_min([3, 8, 2, 10])) # 2
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]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
# Example
a = [5, 2, 9, 1]
bubble_sort(a)
print(a) # [1, 2, 5, 9]
def transpose(matrix):
rows = len(matrix)
cols = len(matrix[0])
result = []
for i in range(cols):
new_row = []
for j in range(rows):
new_row.append(matrix[j][i])
result.append(new_row)
return result
# Example
mat = [[1, 2], [3, 4]]
print(transpose(mat)) # [[1, 3], [2, 4]]