Simple Program Code In Python ( Python For Beginners) Part - 3
1. Check Anagram:
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
if is_anagram(string1, string2):
print("Anagrams")
else:
print("Not anagrams")
2. Generate a Random Number:
import random
print("Random number:", random.randint(1, 100))
3. Binary Search Algorithm:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search(arr, x)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
4. Check Armstrong Number:
def is_armstrong(n):
order = len(str(n))
temp = n
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
return n == sum
number = int(input("Enter a number: "))
if is_armstrong(number):
print("Armstrong number")
else:
print("Not an Armstrong number")
5. Generate a Simple Pattern:
n = 5
for i in range(n):
print('* ' * (i + 1))
6. Linear Search Algorithm:
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = [4, 2, 1, 7, 5]
x = 7
result = linear_search(arr, x)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
7. Calculate the Power of a Number:
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = base ** exponent
print("Result:", result)
8. Print the Fibonacci Series:
def fibonacci_series(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
terms = int(input("Enter the number of terms: "))
print("Fibonacci series:")
fibonacci_series(terms)
9. Merge Two Sorted Lists:
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
merged_list = sorted(list1 + list2)
print("Merged and sorted list:", merged_list)
10. Generate a Simple Pyramid Pattern:
n = 5
for i in range(n):
print(" " * (n - i - 1) + "*" * (2 * i + 1))
0 Comments