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

Ishaan Fundametals of Computer Programming Lab

Uploaded by

pawanbisht393
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Ishaan Fundametals of Computer Programming Lab

Uploaded by

pawanbisht393
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Experiment 1

Write a Python function that takes two numbers as input and returns a
string indicating whether the first number is greater than, less than, or
equal to the second number using comparison operators.

Code:

def num_comp(x, y):


if x > y:
print("First Number is greater than the Second Number.")
elif x < y:
print("Second Number is greater than the First Number.")
elif x == y:
print("Both the numbers are equal.")

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

num_comp(num1, num2)

Output :
Experiment 2
Create a Python program that functions as a calculator. It should
support addition, subtraction, multiplication, division, and modulus
operations. Maintain a history of calculations performed and provide an
option to display the history. Implement error handling for division by
zero.

Code:

hist = []
while True:

oper = input("Choose an operation to perform '+', '-', '*', '/',


'%' or 'history': ")

if oper == 'history':
for i in hist:
print(i)
break

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

if oper == '+':
print("Output :", num1 + num2)
hist.append(f"{num1} + {num2} = {num1 + num2}")
elif oper == '-':
print("Output :", num1 - num2)
hist.append(f"{num1} - {num2} = {num1 - num2}")
elif oper == '*':
print("Output :", num1 * num2)
hist.append(f"{num1} * {num2} = {num1 * num2}")
elif oper == '/':
if num2 != 0:
print("Output :", num1 / num2)
hist.append(f"{num1} / {num2} = {num1 / num2}")
elif num2 == 0:
print("Can not divide by Zero.")
elif oper == '%':
print("Output :", num1 % num2)
hist.append(f"{num1} % {num2} = {num1 % num2}")

q = input("Quit? (y/n): ")


if q == 'y':
break
Output:

Experiment 3
Develop a Python function that takes a list of tuples as input, where
each tuple contains two numbers. For each tuple, compare the numbers
using all comparison operators and store the results in a dictionary.
Return a list of dictionaries for all comparisons.

Code:

def tuple_comp(l):
dict_list = [{} for _ in range(len(l))]
for i in range(len(l)):

dict_list[i][f'{l[i][0]} is greater than {l[i][1]}'] = True


if l[i][0] > l[i][1] else False

dict_list[i][f'{l[i][0]} is less than {l[i][1]}'] = True if


l[i][0] < l[i][1] else False

dict_list[i][f'{l[i][0]} is equal to {l[i][1]}'] = True if


l[i][0] == l[i][1] else False

return dict_list

given_list = [(1,2),(2,2),(2,1)]

print(tuple_comp(given_list))

Output:

Experiment 4
Write a Python program to simulate the operations of basic logic gates
(AND, OR, NOT, NAND, NOR, XOR) using functions. The program should
take two boolean inputs and the type of gate, then return the result of
the logical operation.

Code:

def AND(bool1, bool2):

return bool1 and bool2

def OR(bool1, bool2):

return bool1 or bool2

def NOT(bool1, bool2):

return not bool1, not bool2

def NAND(bool1, bool2):

return not (bool1 and bool2)

def NOR(bool1, bool2):

return not (bool1 or bool2)

def XOR(bool1, bool2):

return (bool1 and (not bool2)) or (( not bool1) and bool2)

input1 = input("Enter a boolean value (True/False): ")

input2 = input("Enter another boolean value (True/False): ")

if input1.lower() == 'false':

input1 = 0

if input2.lower == 'false':
input2 = 0

gate = input("Choose a gate AND, OR, NOT,NAND, NOR, XOR: ")

if gate.upper() == 'AND':

print("Resultant:", AND(input1, input2))

elif gate.upper() == 'OR':

print("Resultant:", OR(input1, input2))

elif gate.upper() == 'NOT':

print("Resultant 1, Resultant 2:", NOT(input1, input2))

elif gate.upper() == 'NAND':

print("Resultant:", NAND(input1, input2))

elif gate.upper() == 'NOR':

print("Resultant:", NOR(input1, input2))

elif gate.upper() == 'XOR':

print("Resultant:", XOR(input1, input2))

Output:

Experiment 5
Develop a Python function that takes a string and a substring as input
and returns the number of times the substring appears in the string.
Implement this without using built-in string functions and optimize it
for large inputs.

Code:

def string_match(string, substring):


matches = 0
for i in range(len(string)):

if string[i] == substring[0]:
for j in range(len(substring)):
if string[i + j] != substring[j]:
break
else:
matches += 1
return matches

input_string = 'hello world! hello world! hello world!'


input_sub_string = 'hello'

print("Number of times substring appears in string:",


string_match(input_string, input_sub_string))

Output:

Experiment 6
Write a Python function that performs bitwise operations (AND, OR,
XOR) on two arrays of integers. The function should take two arrays
and an operator as input, perform the bitwise operation element-wise,
and return the resulting array.

Code:

def bitwise_opers(l1, l2, oper):


resultant_list = []
for i in range(len(l1)):
if oper == 'AND':
resultant_list.append(l1[i] & l2[i])
elif oper == 'OR':
resultant_list.append(l1[i] | l2[i])
elif oper == 'XOR':
resultant_list.append(l1[i] ^ l2[i])
return resultant_list

input_list_1 = [1,2,3,4]
input_list_2 = [5,6,7,8]

print(bitwise_opers(input_list_1, input_list_2, 'OR'))


print(bitwise_opers(input_list_1, input_list_2, 'AND'))
print(bitwise_opers(input_list_1, input_list_2, 'XOR'))

Output:

Experiment 7
Create a Python function that takes a list of integers and returns a new
list containing only the unique elements of the original list. Use a set to
remove duplicates and maintain the order of elements as they appear in
the original list.

Code:

def remve_dups(int_list):
new_list = []
set_of_int_list = set(int_list)
for i in int_list:
if i in set_of_int_list:
new_list.append(i)
set_of_int_list.remove(i)

return new_list

input_list = [1,2,4,3,2,1,5]

print(remve_dups(input_list))

Output:

Experiment 8
Write a Python function that takes a string of text and returns a
dictionary with the frequency of each word in the text. The function
should handle punctuation and capitalization correctly and provide a
case-insensitive count.

Code:

def frequency_checker(text):
freq_dict = {}
l_text = text.split()
for i in range(len(l_text)):
if l_text[i][-1] == ',' or l_text[i][-1] == '.' or
l_text[i][-1] == ':' or l_text[i][-1] == ';':
l_text[i] = l_text[i][:-1]

if l_text[i].lower() not in freq_dict:


freq_dict[l_text[i].lower()] = 1
else:
freq_dict[l_text[i].lower()] += 1

return freq_dict

print(frequency_checker("Last night, The apple eating Goat ate


the apple last night in the Apple store"))

Output:

Experiment 9
Create a Python function that takes a tuple as an argument and returns
a new tuple with the elements reversed. Demonstrate the use of tuples
as function parameters and unpacking tuple elements within the
function.

Code:

def tuple_revesion(tup):
x,y = tup
new_tup = (y,x)
return new_tup

input_tuple = (11,22)

print(tuple_revesion(input_tuple))

Output:

Experiment 10
Create a Python function that finds all prime numbers up to a given
number n. Use nested loops to check for primality and optimize the
function to handle large inputs efficiently. Additionally, allow the user
to break the loop prematurely if they input a specific command.

Code:

def find_primes(n):
for x in range(2,n+1):
for i in range(2,(x//2)+1):
if x % i == 0 :
break
else:
print(x)
if input('quit?(y/n): ') == 'y':
break

find_primes(50)

output:

You might also like