0% found this document useful (0 votes)
7 views

python_activity_programs

The document outlines a series of programming tasks, primarily in Python, that include converting between octal and hexadecimal, implementing sorting algorithms, generating random numbers, and solving mathematical equations using various transforms. Each task is accompanied by sample code demonstrating the implementation. The document serves as a comprehensive guide for practicing programming skills in data manipulation and mathematical computations.

Uploaded by

guybms4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

python_activity_programs

The document outlines a series of programming tasks, primarily in Python, that include converting between octal and hexadecimal, implementing sorting algorithms, generating random numbers, and solving mathematical equations using various transforms. Each task is accompanied by sample code demonstrating the implementation. The document serves as a comprehensive guide for practicing programming skills in data manipulation and mathematical computations.

Uploaded by

guybms4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

ACTIVITY PROGRAMS

1.Develop a program to convert Octal to Hexadecimal and Hexadecimal to Octal.

2.Write a Python program to implement insertion sort and merge sort using lists.

3.Generate a Random Number using inbuilt functions randrange(), shuffle, uniform.

4.Program to find and print all permutations of a given sequence (Integers/String) using list
and functions.

5.Program to find and print all combinations of a given sequence (Integers/String) using list
and functions.

6.Develop a Program for Cos Wave Generation.

7.Program to solve a given 1st order difference equation using Z transform.

8.Program to solve a given 1st order differential equation using Laplace transform.

9.Program to calculate mean, median, mode, standard deviation, and variance.

10.Program To Generate Random Numbers:


a. From a given list of specified Random Numbers
b. Random floating-point number between 0 and 1
c. Random integer between a given range (e.g., 1 and 100)

11.Program to print all permutations for a given length of sequence:


a. Using List
b. Using Library functions

12.Program to print all permutations of coin tossing for a given number of flips.

13.Program to print all combinations of the dice using recursion and memorization.
Program 1: Develop a program to convert Octal to Hexadecimal and
Hexadecimal to Octal.

# Function to convert Octal to Hexadecimal


def octal_to_hex(oct_num):
dec = 0 # Initialize decimal value
base = 1 # Start with base 8^0 = 1

# Loop through the octal digits in reverse (right to left)


for digit in reversed(oct_num):
dec += int(digit) * base # Convert digit to decimal and add
base *= 8 # Increase base by power of 8

# Now convert decimal to hexadecimal


hex_digits = "0123456789ABCDEF" # All hex characters
hex_num = "" # Final hex result as string

# Loop to convert decimal to hex


while dec > 0:
rem = dec % 16 # Get remainder
hex_num = hex_digits[rem] + hex_num # Add corresponding hex char
dec //= 16 # Reduce decimal for next iteration

# If input was 0, return '0'


return hex_num if hex_num else "0"

# Function to convert Hexadecimal to Octal


def hex_to_octal(hex_num):
dec = 0 # Initialize decimal value
base = 1 # Start with base 16^0 = 1
hex_num = hex_num.upper() # Convert to uppercase (in case user enters 'a', 'b', etc.)

# Loop through hex digits in reverse


for digit in reversed(hex_num):
if digit.isdigit(): # For 0-9
val = int(digit) # Convert character to integer
else:
val = ord(digit) - 55 # For A-F: A=10, B=11, ... Z=35 (but we use only till F)
dec += val * base # Add to decimal value
base *= 16 # Increase base
# Convert decimal to octal
oct_num = "" # Final octal result as string

# Loop to convert decimal to octal


while dec > 0:
rem = dec % 8 # Get remainder
oct_num = str(rem) + oct_num # Add digit to result
dec //= 8 # Reduce decimal

# If input was 0, return '0'


return oct_num if oct_num else "0"

# --------------- MAIN MENU ---------------

print("1. Octal to Hexadecimal") # Show option 1


print("2. Hexadecimal to Octal") # Show option 2

choice = input("Choose option (1 or 2): ") # Ask user to pick

# If user chose octal to hexadecimal


if choice == '1':
octal = input("Enter Octal number: ") # Ask for octal number
print("Hexadecimal:", octal_to_hex(octal)) # Show result

# If user chose hexadecimal to octal


elif choice == '2':
hexa = input("Enter Hexadecimal number: ") # Ask for hex number
print("Octal:", hex_to_octal(hexa)) # Show result

# Invalid choice handling


else:
print("Invalid option.") # Error message

OUTPUT:
Program 2: Write a Python program to implement insertion sort and merge sort
using lists.

# -------- Insertion Sort --------


def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i] # Current element to be compared
j=i-1

# Move elements that are greater than key to one position ahead
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j] # Shift element to right
j -= 1

arr[j + 1] = key # Place key in its correct position

return arr

# -------- Merge Sort --------


def merge_sort(arr):
if len(arr) <= 1:
return arr # Base case: already sorted

mid = len(arr) // 2 # Find midpoint


left_half = merge_sort(arr[:mid]) # Sort left half
right_half = merge_sort(arr[mid:]) # Sort right half

# Merge the two halves


return merge(left_half, right_half)

# Helper function to merge two sorted lists


def merge(left, right):
result = []
i=j=0

# Compare elements from both halves and merge in order


while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1

# Add remaining elements


result.extend(left[i:])
result.extend(right[j:])
return result

# -------- Main Program --------


print("1. Insertion Sort")
print("2. Merge Sort")
choice = input("Enter your choice (1 or 2): ")

data = input("Enter the numbers separated by space: ")


arr = list(map(int, data.strip().split())) # Convert input to list of integers

if choice == '1':
sorted_arr = insertion_sort(arr.copy())
print("Sorted using Insertion Sort:", sorted_arr)

elif choice == '2':


sorted_arr = merge_sort(arr.copy())
print("Sorted using Merge Sort:", sorted_arr)

else:
print("Invalid choice. Please enter 1 or 2.")
OUTPUT:

Program 3: Generate a Random Number using inbuilt functions randrange(),


shuffle, uniform.

# Import random module for generating random values


import random

# --------- Using randrange() ---------


# Generates a random number between 10 and 50 (excluding 50)
num1 = random.randrange(10, 50)
print("Random number using randrange(10, 50):", num1)

# --------- Using shuffle() ---------


# Creates a list of numbers, shuffles it, then picks one
numbers = [11, 22, 33, 44, 55]
random.shuffle(numbers) # This rearranges the list randomly
print("List after shuffle():", numbers)
print("First number after shuffle:", numbers[0])

# --------- Using uniform() ---------


# Generates a random float between 1.5 and 9.5
num2 = random.uniform(1.5, 9.5)
print("Random float using uniform(1.5, 9.5):", num2)
OUTPUT:

Program 4: Program to find and print all permutations of a given sequence


(Integers/String) using list and functions.

# Program to print all permutations of a given sequence


# Supports both integers and strings

# Function to generate permutations recursively


def generate_permutations(seq):
# Base case: only one permutation possible
if len(seq) == 1:
return [seq.copy()] # Return a copy as list of lists

result = [] # To store all permutations

# Iterate through the sequence


for i in range(len(seq)):
# Pick the element at index i
fixed = seq[i]

# Remaining list after removing the picked element


rest = seq[:i] + seq[i+1:]

# Recursively get permutations of the remaining part


sub_perms = generate_permutations(rest)

# Add the fixed element to each of the sub-permutations


for p in sub_perms:
result.append([fixed] + p)

return result
# ------ Main Code ------

user_input = input("Enter a sequence (e.g., '123' or 'abc'): ")

# If input is digits only, treat as list of integers


if user_input.isdigit():
seq = [int(ch) for ch in user_input]
else:
seq = list(user_input) # Treat as characters

# Generate all permutations


all_perms = generate_permutations(seq)

# Print results
print("All possible permutations:")
for p in all_perms:
print(p)

OUTPUT:
Program 5: Program to find and print all combinations of a given sequence
(Integers/String) using list and functions.

# Program to generate and print all combinations of a given sequence


# Works for both strings and integer sequences

# Function to generate combinations


def generate_combinations(seq):
all_combos = []

# Inner recursive function to build combinations


def combine(index, current):
if index == len(seq):
if current: # Avoid empty combination
all_combos.append(current[:]) # Store a copy
return

# Include the current element


current.append(seq[index])
combine(index + 1, current)

# Exclude the current element


current.pop()
combine(index + 1, current)

combine(0, []) # Start recursion


return all_combos

# ---- Main Program ----

user_input = input("Enter a sequence (e.g., 123 or abc): ")

# Convert to list of int or chars based on input type


if user_input.isdigit():
seq = [int(ch) for ch in user_input]
else:
seq = list(user_input)

# Get all combinations


combos = generate_combinations(seq)

# Print each combination


print("All possible combinations:")
for c in combos:
print(c)

OUPUT:

Program 6: Develop a Program for Cos Wave Generation.

# Program to generate and display a Cosine Wave

# Import required libraries


import numpy as np
import matplotlib.pyplot as plt

# --- Function to generate cosine wave ---


def generate_cos_wave(freq, amplitude, duration, sample_rate):
t = np.linspace(0, duration, int(sample_rate * duration)) # Time values
y = amplitude * np.cos(2 * np.pi * freq * t) # Cosine values
return t, y

# --- Main logic ---


# User inputs
frequency = float(input("Enter frequency (Hz): "))
amplitude = float(input("Enter amplitude: "))
duration = float(input("Enter duration (seconds): "))

# Sampling rate (samples per second)


sampling_rate = 1000

# Generate the wave


time_values, wave_values = generate_cos_wave(frequency, amplitude, duration,
sampling_rate)
# --- Plotting ---
plt.figure(figsize=(8, 4))
plt.plot(time_values, wave_values, label="Cosine Wave", color='blue')
plt.title("Cosine Wave")
plt.xlabel("Time (s)")
plt.ylabel("Amplitude")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()

OUTPUT:
Program 7: Program to solve a given 1st order difference equation using Z
transform.

import numpy as np
import matplotlib.pyplot as plt

# Function to solve first-order difference equation: y[n] = a*y[n-1] + x[n]


def difference_equation(a, x):
n = len(x)
y = np.zeros(n)
y[0] = x[0] # initial condition: y[0] = x[0]
for i in range(1, n):
y[i] = a * y[i - 1] + x[i]
return y

# Parameters
a = 0.5 # constant in the equation
n_samples = 10 # number of samples
x = np.ones(n_samples) # input sequence x[n] = 1 for all n
y = difference_equation(a, x) # solve the difference equation

# Output
print("Input x[n]:", x)
print("Output y[n]:", y)

# Plotting
plt.stem(range(n_samples), x, basefmt="b-", linefmt="b-", markerfmt="bo", label="Input
x[n]")
plt.stem(range(n_samples), y, basefmt="r-", linefmt="r-", markerfmt="ro", label="Output
y[n]")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.title("First-Order Difference Equation: y[n] = a*y[n-1] + x[n]")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Program 8: Program to solve a given 1st order differential equation using
Laplace transform.

import sympy as sp

# Define symbols
t, s = sp.symbols('t s')
y = sp.Function('y')
x = sp.Function('x')
a = sp.Symbol('a')

# --- Input Section ---


a_val = float(input("Enter constant 'a' in dy/dt + a*y = x(t): "))
x_input = input("Enter x(t) as a function of t (e.g., 1, exp(-t), sin(t)): ")
y0 = float(input("Enter initial condition y(0): "))
# Convert x(t) input to symbolic expression
x_t = sp.sympify(x_input)

# Step 1: Compute Laplace Transform of x(t)


X_s = sp.laplace_transform(x_t, t, s, noconds=True)

# Step 2: Solve for Y(s)


Y_s = (X_s + y0) / (s + a_val)
Y_s = sp.simplify(Y_s)

# Step 3: Inverse Laplace to get y(t)


y_t = sp.inverse_laplace_transform(Y_s, s, t)

# --- Output ---


print("\nGiven Equation: dy/dt +", a_val, "* y(t) = x(t)")
print("\nLaplace Transform of x(t):")
sp.pprint(X_s)

print("\nLaplace Domain Solution Y(s):")


sp.pprint(Y_s)

print("\nTime-domain Solution y(t):")


sp.pprint(y_t)

OUTPUT:
Program 9: Program to calculate mean, median, mode, standard deviation, and
variance.

import statistics as stats

# ---- Input ----


data_input = input("Enter numbers separated by spaces: ")
data = list(map(float, data_input.strip().split()))

# ---- Calculations ----


mean_val = stats.mean(data)
median_val = stats.median(data)

# Handle multiple modes


try:
mode_val = stats.mode(data)
except:
mode_val = "No unique mode"

variance_val = stats.variance(data)
std_dev_val = stats.stdev(data)

📊
# ---- Output ----
print("\n Statistical Measures:")
print(f"Mean: {mean_val}")
print(f"Median: {median_val}")
print(f"Mode: {mode_val}")
print(f"Variance: {variance_val}")
print(f"Standard Deviation: {std_dev_val}")

OUTPUT:
Program 10: Program To Generate Random Numbers:
a. From a given list of specified Random Numbers
b. Random floating-point number between 0 and 1
c. Random integer between a given range (e.g., 1 and 100)

import random

# a. From a given list of specified Random Numbers


given_list = [3, 7, 13, 27, 42, 69, 88]
random_from_list = random.choice(given_list)
print("Random number from list:", random_from_list)

# b. Random floating-point number between 0 and 1


random_float = random.random()
print("Random float between 0 and 1:", random_float)

# c. Random integer between a given range (e.g., 1 and 100)


random_int = random.randint(1, 100)
print("Random integer between 1 and 100:", random_int)

OUTPUT:
Program 11: Program to print all permutations for a given length of sequence:
a. Using List
b. Using Library functions

from itertools import permutations

# Input from user


elements = input("Enter elements separated by space (e.g. 1 2 3): ").split()
r = int(input("Enter the length of each permutation: "))

print("\n[a] Permutations using Manual Logic (List + Recursion):")

def generate_permutations(seq, r):


result = []

def recurse(path, used):


if len(path) == r:
result.append(path[:])
return
for i in range(len(seq)):
if not used[i]:
used[i] = True
path.append(seq[i])
recurse(path, used)
path.pop()
used[i] = False

recurse([], [False]*len(seq))
return result

manual_result = generate_permutations(elements, r)
for item in manual_result:
print(item)
print(f"Total permutations (manual): {len(manual_result)}")

print("\n[b] Permutations using itertools.permutations:")

library_result = list(permutations(elements, r))


for item in library_result:
print(item)
print(f"Total permutations (library): {len(library_result)}")
Program 12: Program to print all permutations of coin tossing for a given number of flips.

def generate_coin_tosses(n):
results = []

def backtrack(current, flips_left):


if flips_left == 0:
results.append(current)
return
backtrack(current + 'H', flips_left - 1)
backtrack(current + 'T', flips_left - 1)

backtrack('', n)
return results

# Input number of flips


flips = int(input("Enter number of coin flips: "))

print(f"\nAll possible outcomes for {flips} coin flips:\n")


outcomes = generate_coin_tosses(flips)
for outcome in outcomes:
print(outcome)

print(f"\nTotal permutations: {len(outcomes)}")

OUTPUT:​
Program 13: Program to print all combinations of the dice using recursion and
memorization.

from functools import lru_cache

@lru_cache(maxsize=None)
def dice_combinations(n):
if n == 0:
return [[]]
result = []
for face in range(1, 7):
for combo in dice_combinations(n - 1):
result.append([face] + combo)
return result

# Input from user


num_dice = int(input("Enter number of dice: "))

print(f"\nAll combinations for {num_dice} dice:\n")


combinations = dice_combinations(num_dice)

# Transpose the combinations to print sideways


for i in range(num_dice):
row = [str(combo[i]) for combo in combinations]
print(" ".join(row))

OUTPUT:

You might also like