0% found this document useful (0 votes)
14 views13 pages

31 48codetantra Programs

Uploaded by

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

31 48codetantra Programs

Uploaded by

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

31.

Write a Python program implementing the following operations on arrays using


the array module:

1. Print the first n elements


2. Print the elements with given stride value
3. Print the elements in reverse order
4. Copy the contents into another array.

# Function to print the first n elements of the array

def print_first_n(arr, n):

if n <= 0 or n > len(arr):

print("Number should be positive and less than or equal to size of array")

return

print(f"The {n} elements of the array are:")

for i in range(n):

print(arr[i], end=' ')

print()

# Function to print elements in reverse order

def print_reverse(arr):

print("Array elements in reverse order:", arr[::-1])

# Function to copy contents into another array

def copy_array(arr):

new_arr = [element for element in arr]

print("After copying the elements to second list:", new_arr)

# Taking input from the user

size = int(input("Enter the size of the list: "))

arr = [int(input(f"Enter element {i}: ")) for i in range(size)]

# Displaying the original array


print("The list is:", arr)

# Performing operations

n_elements = int(input("Enter how many elements do you want to print: "))

print_first_n(arr, n_elements)

print_reverse(arr)

copy_array(arr)

32. Write a Python program to find addition of two matrices.

m = int(input('Number of rows for matrix - A, m = '))

n = int(input('Number of columns for matrix - A, n = '))

p = int(input('Number of rows for matrix - B, p = '))

q = int(input('Number of columns for matrix - B, q = '))

# Function to input matrix values

def input_matrix(rows, cols):

matrix = []

for i in range(rows):

row = []

for j in range(cols):

entry = int(input(f"Entry in row: {i + 1} column: {j + 1}\n"))

row.append(entry)

matrix.append(row)

return matrix

# Function to add two matrices

def add_matrices(matrix_a, matrix_b):

result_matrix = []

for i in range(len(matrix_a)):

row = []
for j in range(len(matrix_a[0])):

row.append(matrix_a[i][j] + matrix_b[i][j])

result_matrix.append(row)

return result_matrix

# Check if matrices can be added

if p == m and n == q:

print('Enter values for matrix - A')

matrix_a = input_matrix(m, n)

print('Enter values for matrix - B')

matrix_b = input_matrix(p, q)

# Displaying the matrices

print(f"Matrix a = {matrix_a}")

print(f"Matrix b = {matrix_b}")

# Perform matrix addition

result = add_matrices(matrix_a, matrix_b)

# Display the result

print(f"Addition of two matrices = {result}")

else:

print('Addition is not possible')

33. Write a Python program to perform multiplication of two matrices.

def matmult(A, B):

# Write Code

""" End of Function: matmult """

def readmatrix(name = ''):


# Write Code

""" End of Function: matmult """

matrixa = readmatrix('matrix - A')

matrixb = readmatrix('matrix - B')

print("Matrix - A =", matrixa)

print("Matrix - B =", matrixb)

print("Matrix - A * Matrix- B =", matmult(matrixa, matrixb))

34. Write a Python program to find the sum of N natural numbers using user-defined
functions.

def sum_of_natural_numbers(n):

if n <= 0:

print("Natural numbers start from 1")

return

sum_n = (n * (n + 1)) // 2

print(f"Sum of {n} natural numbers is: {sum_n}")

# Taking user input for the number of natural numbers

num = int(input("Enter no. of natural numbers: "))

sum_of_natural_numbers(num)

35. Write a Python program that has a function that takes a list and returns a sorted list.

def sort_list(input_list):

sorted_list = sorted(input_list)

return sorted_list

input_elements = input("Enter the list elements: ").split()


try:

input_list = [int(x) for x in input_elements]

print("The list is:", input_list)

sorted_result = sort_list(input_list)

print("Sorted list:", sorted_result)

except ValueError:

print("Invalid input. Please enter a list of integers.")

36. Write a python program to print factorial of given number using a Function.

def fact(x):

# find the factorail and print minimum of the given number

if x == 0:

return 1

else:

return x * fact(x - 1)

try:

x = int(input("x: "))

result = fact(x)

print(result)

except ValueError:

print("Please enter a valid integer.")

37. Write a python program to find factorial of a number using Recursion.

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n-1)
# Input from the user

num = int(input("Enter a number: "))

# Check if the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print(f"The factorial of {num} is {factorial(num)}")

38. Write a python program to print fibonacci series up to given range using functions
without using recursion

def fibonacci_series(n):

a, b = 0, 1

while a <= n:

print(a)

a, b = b, a + b

# Input from the user

range_limit = int(input("Enter the range: "))

# Print Fibonacci series up to the given range

print(f"Fibonacci series of number upto {range_limit}:")

fibonacci_series(range_limit)

39. def fibonacci_series(n):

if n <= 0:

return []

elif n == 1:

return [0]
elif n == 2:

return [0, 1]

else:

fib_series = fibonacci_series(n - 1)

fib_series.append(fib_series[-1] + fib_series[-2])

return fib_series

# Input from the user

max_limit = int(input("Enter the maximum limit to generate the fibonacci series: "))

# Generate and print Fibonacci series up to the given limit

result = fibonacci_series(max_limit)

print("The fibonacci series is:")

for num in result:

print(num)

40. Write a program that takes a list of age of members from user and find the
members eligible for voting with age grater than 17 using filter() function with
lambda.
# Input from the user

age_list = list(map(int, input("Enter the age of members: ").split()))

# Using filter() with lambda to find members eligible for voting (age greater than 17)

eligible_voters = list(filter(lambda age: age > 17, age_list))

# Display the result

print("Eligible for voting:", eligible_voters)

41. Write a program that takes a list animal names in lower case and changes those strings to
upper case strings using map() function with lambda.

# Taking input from the user and converting it to a list of lowercase animal names
animal_names = input("Enter animal names: ").split()

# Using map and lambda to convert the animal names to uppercase

animal_names_upper = list(map(lambda x: x.upper(), animal_names))

# Displaying the result

print("Animal names in Upper case:", animal_names_upper)

42. Write a program that takes a list of integer from user and find the maximum element
using reduce() function with lambda.

from functools import reduce

# Taking input from the user and converting it to a list of integers

elements = list(map(int, input("Enter elements of list: ").split()))

# Using reduce and lambda to find the maximum element

max_element = reduce(lambda x, y: x if x > y else y, elements)

# Displaying the result

print("The maximum element of the list is :", max_element)

43. write a simple try except block.

Given two integer inputs num1 and num2. Perform division operation
on num1 and num2 using try-except block.

Print the result as shown in the sample test cases.

num1 = int(input("num1: "))

num2 = int(input("num2: "))

try:

print(num1/num2)
except:

print("exception occurred")

44. Let's write a program with a try block and two except blocks that handles two
types of exceptions. Follow the below-given instructions and write the missing code
in the provided editor.

 In the given try block take two integer inputs a and b. Perform the arithmetic
operations +, / and * on a, b and store the results in c, d and e.
 Print try successful.
 Open an except block with name ZeroDivisionError.
 Print zero division error occurred.
 Open an except block with name NameError.
 Print name error occurred.
 Open an except block with name Exception.
 Print exception occurred.

try:

# take user inputs a and b and perform arithmetic operations

a=int(input("a: "))

b=int(input("b: "))

c=a+b

d=a/b

e=a*b

if a == 0:

f = fun1(a)

# Display success message

print("try successful")

# Handle division by zero exception

except ZeroDivisionError:

# Display corresponding error

print("zero division error occurred")


# Handle NameError exception

except NameError :

# Display corresponding error

print("name error occurred")

except Exception :

# Display corresponding exception

print("exception occurred")

def fun1(n):

print(n)

46. Write a python program to create a new file and add the given text into the file.

# Input from the user

text_to_write = input("Enter text to write into file: ")

# Create a new file and write the text into it

file_name = "output_file.txt"

with open(file_name, "w") as file:

file.write(text_to_write)

# Display the contents of the file

with open(file_name, "r") as file:

file_contents = file.read()

print("Contents of the file:")

print(file_contents)

47.write a python program to add the contents into an existing file and display the contents
of a file from the specified position.
def write_content(file_name, content):

with open(file_name, 'a') as file:

file.write(content)

def read_content(file_name, position):

if position < 0:

print("Invalid position")

return

with open(file_name, 'r') as file:

file.seek(position)

content = file.read()

return content

file_name = "myfile.txt"

# Add content to the file

content = input("Enter text to write into file: ")

write_content(file_name, content)

# Read content from specified position

position = int(input("Enter position to print: "))

result = read_content(file_name, position)

print(result)

48.write a Python program to find the product of two given numbers, implementing
the following logic:
Consider an example of 14 x 20
def find_product(num1, num2):
# Displaying the two numbers

#print(num1)

#print(num2)

# Initializing variables

sum_result = 0

while num1 > 0:

# Checking if the first number is even or odd

if num1 % 2 == 0:

#print("First Number is Even")

print(num2)

# Action for even number

sum_result += 0

num1 = num1 // 2

num2 = num2 * 2

else:

#print("First Number is Odd")

print("+" + str(num2))

# Action for odd number

sum_result += num2

num1 = num1 // 2

num2 = num2 * 2

print("stop")

print("Final sum:", sum_result)


# Taking input from the user

num1 = int(input())

num2 = int(input())

# Calling the function to find the product

find_product(num1, num2)

You might also like