Advertisement

Simple Python Program Code ( Python For Beginners) Part - 9

Simple Python Program Code ( Python For Beginners) Part - 9

1. Find the Sum of Elements in a List:
my_list = [1, 2, 3, 4, 5]
sum_of_elements = sum(my_list)
print("Sum of elements:", sum_of_elements)

2. Generate a Fibonacci Sequence Using a Loop:
def generate_fibonacci(n):
fibonacci_sequence = [0, 1]
for i in range(2, n):
next_num = fibonacci_sequence[-1] + fibonacci_sequence[-2]
fibonacci_sequence.append(next_num)
return fibonacci_sequence
terms = 10
print("Fibonacci sequence:", generate_fibonacci(terms))

3. Calculate the Exponential Value Using a Loop:
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1
for _ in range(exponent):
result *= base
print("Result:", result)

4. Implement Linear Search Algorithm Using a Loop:
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")

5. Calculate the Area of a Triangle Using Heron's Formula:
import math
a = float(input("Enter the length of side a: "))
b = float(input("Enter the length of side b: "))
c = float(input("Enter the length of side c: "))
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("Area of the triangle:", area)

6. Implement a Merge Sort Algorithm:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
arr = [12, 11, 13, 5, 6, 7]
merge_sort(arr)
print("Sorted array:", arr)

7. Find the Area of a Circle:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius * radius
print("Area of the circle:", area)

8. Implement a Binary Search Algorithm Using a Loop:
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")

9. Check if a String is a Valid Email Address:
import re
def is_valid_email(email):
return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
input_email = input("Enter an email address: ")
if is_valid_email(input_email):
print("Valid email address")
else:
print("Invalid email address")

10. Generate a Random List of Numbers:
import random
random_list = random.sample(range(1, 100), 5)
print("Random list:", random_list)

Post a Comment

0 Comments