Check if a Number is Prime:
a. A prime number is a natural number greater than 1 that has no positive
divisors other than 1 and itself.
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
Check if a Number is Palindrome:
b. A palindrome number is a number that remains the same when its digits are
reversed.
def is_palindrome(num):
return str(num) == str(num)[::-1]
Reverse a String:
c. Reverses the order of characters in a string.
def reverse_string(s):
return s[::-1]
Check if a String is Anagram:
d. An anagram of a string is another string that contains the same characters,
only the order of characters can be different.
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
Check Armstrong Number:
e. An Armstrong number is a number that is equal to the sum of its own digits
each raised to the power of the number of digits.
def is_armstrong(num):
order = len(str(num))
temp = num
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
return num == sum
Find the Factorial of a Number:
f. Factorial of a non-negative integer is the product of all positive integers less
than or equal to that number.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Calculate Fibonacci Series:
g. The Fibonacci sequence is a series of numbers where each number is the
sum of the two preceding ones, starting from 0 and 1.
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
Find the LCM (Least Common Multiple) of Two Numbers:
h. The least common multiple (LCM) of two numbers is the smallest number
which can be evenly divided by both numbers.
def lcm(x, y):
if x > y:
greater = x
else:
greater = y
while True:
if (greater % x == 0) and (greater % y == 0):
lcm = greater
break
greater += 1
return lcm
Find the GCD (Greatest Common Divisor) of Two Numbers:
i. The greatest common divisor (GCD) of two integers is the largest positive
integer that divides each of the integers.
def gcd(x, y):
while(y):
x, y = y, x % y
return x
Count the Number of Words in a Sentence:
j. Counts the number of words in a given sentence.
def count_words(sentence):
return len(sentence.split())