0% found this document useful (0 votes)
121 views32 pages

Py Record Final

Here is the code that takes input from the user: Program: def partition(arr, low, high): i = (low-1) # index of smaller element pivot = arr[high] # pivot for j in range(low, high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return (i+1) # Function to do Quick

Uploaded by

aarthi dev
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)
121 views32 pages

Py Record Final

Here is the code that takes input from the user: Program: def partition(arr, low, high): i = (low-1) # index of smaller element pivot = arr[high] # pivot for j in range(low, high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return (i+1) # Function to do Quick

Uploaded by

aarthi dev
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/ 32

What about program no, title of the program date for all the program. Very poor formatting.

Format it properly. Comment given at the particular program do the modifications and can
send me today itself

Aim:
Write a program illustrating binary search

Procedure:
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray
after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.

Program:

def binary_search(alist, key):


"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1

alist = input('Enter the sorted list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = binary_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
Output:

Result:
Result is verified
Aim:
Write a program to print the palindrome prime numbers between one and 100

Procedure:
1. Create loop ranging from one to one hundred

2. use advanced slice operation [start:end:step] leaving start and empty and giving step
a value of -1, this slice operation reverses the string.

3. Now check whether reverse is equal to num,

4. If reverse is equal to num, the number is palindrome

5. When reverse is not equal to num, it is not a palindrome


6. Next create a nested for loop inside the for create in step one ranging from 2 to i
7. If i is divided by a and no reminders exist then number is a palindrome prime
8. If not break from the loop.

Program:
for i in range(1,100):
y = True
if(str(i) == str(i)[::-1]):
if(i>2):
for a in range(2,i):
if(i%a==0):
y = False
break
if y:
print(i)
Output:

Result:
Result Verified
Aim:
Write a program to accept three numbers and print all possible combinations

Procedure:
1. Accept user input of three numbers for combinations
2. Create an empty list
3. Append the user inputted numbers into the list.
4. Create three nested for loops all ranging from zero to three
5. Inside the third loop c4reate a conditional statement that checks whether the first
entered number is not equal to the second and the second is not equal to the third
and that the third is not equal to the first.
6. Print the combinations of the three number through the list

Program:
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
d=[]
d.append(a)
d.append(b)
d.append(c)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(d[i],d[j],d[k])
Output:

Result:
Result Verified
Aim:
Write a program to accept two matrices and display its product

Procedure:
1. Create two matrices that are 3x3 with values in them and assign them to variabiles,X
and Y.
2. Create a third matrix of 3x3 and place a zero in each slot.
3. Iterate through rows of matrix X using a for loop ranging the length of x
4. Create a nested for loop ranging from (len(Y[0]))
5. Iterate through rows of matrix Y using a nested for loop ranging the length of x
6. Result should equally X [i][k] multiplied by Y[k][j]
7. Print Result

Program:
X = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

Y = [[10, 11, 12],


[13, 14, 15],
[16, 17, 18]]

result = [[0, 0, 0],


[0, 0, 0],
[0, 0, 0]]

# iterate through rows of X


for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Output:

Result:
Result is Verified.
Aim:
Write a program to accept the mark of five subjects and display thier grade
Procedure:
1. Accept user input of marks of all subjects
2. Create and average variable that stores the average of all marks entered by user.
3. Using if else condition statements, set condition according to the marks range to
print the corresponding grade.
Program:
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub5)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80 and avg<90):
print("Grade: B")
elif(avg>=70 and avg<80):
print("Grade: C")
elif(avg>=60 and avg<70):
print("Grade: D")
elif(avg>=50 and avg<40):
print("Grade: E")
else:
print("Grade: F")
Output:

Result:
Result is verified.
Aim:
Write a program to find numbers in a string and add it into a list(numlist). Print the list
eliminating the duplicates
Procedure:
1. Create a function to remove duplicates within the list
a. Create a for loop for every number in the entered string
b. Create a conditional statement to check if the number in entered string is
not in final list
2. Accept user input of a string with numbers
3. Using list comprehension , isdigit() and split() methods.
4. Print the numbers in the list
5. Print numbers in list after removing duplicates by calling the function created in step
1

Program:

def Remove(res):

final_list = []

for num in res:

if num not in final_list:

final_list.append(num)

return final_list

test_string = input("enter string with numbers:")

print("The original string : " + test_string)

res = [int(i) for i in test_string.split() if i.isdigit()]

print("The numbers list is : " + str(res))

print("Numbers in list after removing duplicates:")

print(Remove(res))
Output:

Result:
Result is Verified.
Where is the original dictionary displayed….both key and values has to be deleted.
Change the code and o/p.write the procedure properly
Aim:
Write program to generate random numbers between 1-100 and add it to a dictionary,
remove the duplicates and display the output.
Procedure:
1. Import random module
2. Create a looping statement ranging to 100
a. Initialize a dictionary, adding the random numbers into the dictionary
b. Create conditional statements for keys using the values () method.
Program:

import random

ud={}

for k in range(100):

dict={k: random.randint(1,99)}

for key, value in dict.items():

if value not in ud.values():

ud[key]=value

print(ud)
Output:

Result:
Result is verified
Aim:
Illustrate methods of tuples
Procedure:
1. use the index operator [ ] to access an item in a tuple where the index starts from 0.
2. Illustrate negative indexing. The index of -1 refers to the last item, -2 to the second
last item and so on.
3. Illustrate slicing using the slicing operator - colon ":"
4. assign a tuple to different values (reassignment)
5. use + operator to combine two tuples. This is also called concatenation
6. deleting a tuple entirely using the keyword del
7. count() returns the number of items
8. index(x) returns the index of the first item that is equal to x
9. test if an item exists in a tuple or not, using the keyword in
10. terate through each item in a tuple using a for loop

Program:

my_tuple9 = ('p','e','r','m','i','t')

print(my_tuple9[0]) # 'p'

print(my_tuple9[5]) # 't'

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

print(n_tuple[0][3])

print(n_tuple[1][1])

my_tuple7= ('p','e','r','m','i','t')

print(my_tuple7[-1])
print(my_tuple7[-6])

my_tuple6 = ('p','r','o','g','r','a','m','i','z')

print(my_tuple6[1:4])

print(my_tuple6[:-7])

print(my_tuple6[7:])

print(my_tuple6[:])

my_tuple2 = (4, 2, 3, [6, 5])

my_tuple2[3][0] = 9

print(my_tuple2)

my_tuple = ('p','r','o','g','r','a','m','i','z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(my_tuple2)

my_tuple1 = ('p','r','o','g','r','a','m','i','z')

del my_tuple1

print(my_tuple1)

my_tuple = ('a','p','p','l','e',)

print(my_tuple.count('p')) # Output: 2

print(my_tuple.index('l')) # Output: 3

for name in ('John','Kate'):

print("Hello",name)
Output:

Result:
Result is verified.
Get the input from the user. No assigning the input string and characters

Aim:
Write a function to check the occurrence of a characters in string and print the number of
occurrences

Procedure:
1. Create a function count with arguments s and c
a. Set result to zero.
b. Loop through the length of s
c. Set a conditional statement checking if the specified element is present
d. If so increment the counter
2. Print result by making a call to the function created in step 1

Program:

def count(s, c) :

res = 0

for i in range(len(s)) :

if (s[i] == c):

res = res + 1

return res

str= "geeksforgeeks"

c = 'e'

print(count(str, c))
output:

Result:
Result verified
Input should be from the user

Aim:
Write a function to arrange the list of elements using pivot elements
Procedure:
1. Pick an element, called a pivot, from the array. This is usually the first element.

2. Partitioning: reorder the array so that all elements with values less than the pivot come
before the pivot, while all elements with values greater than the pivot come after it
(equal values can go either way). After this partitioning, the pivot is in its final position.
This is called the partition operation.

3. Recursively apply the above steps to the sub-array of elements with smaller values and
separately to the sub-array of elements with greater values.

Program:

def quick_sort(sequence):
length=len(sequence)
if length <=1:
return sequence
else:
pivot=sequence.pop()
items_greater=[]
items_lower=[]
for item in sequence:
if item>pivot:
items_greater.append(item)
else:
items_lower.append(item)
return quick_sort(items_lower) + [pivot] + quick_sort(items_greater)
print(quick_sort([4,6,2,7,5,7]))
Output:

Result:
Result is verified
Lines???
Aim:
Write a function to count number of lines, character and words in a string

Procedure:
1. Accept user string input
2. Set intial character and word count to zero
3. Create a looping statement of each character in entered string
a. Increment character count with every character
b. Increament word count with every white space counted
4. Display output.

Program:
string=input("Enter string:")

char=0

word=1

for i in string:

char=char+1

if(i==' '):

word=word+1

print("Number of words in the string:")

print(word)

print("Number of characters in the string:")

print(char)
output:

Result:
Result is verfied
Aim:
write a swapcase function without using standard swap case in a string

Procedure:
1. Accept user input to convert to uppercase
2. Create looping statement ranging from 0 to the length of the inputted string
a. Create a conditional statement that check if the entered string is lowercase
b. If conditional statement is true swap it into uppercase by subtracting 32 from
it.
c. Else conditional statement is true swap it into uppercase by adding 32 from
it.
3. Display output.

Program:

str1=input("Enter the string to be converted uppercase: ")

for i in range (0,len(str1)):

x=ord(str1[i])

if x>=97 and x<=122:

x=x-32

elif x>=65 and x<=90:

x=x+32

y=chr(x)

print(y,end="")
Output:

Result:
Result is verified
Aim:
Illustrate methods of set

Procedure:
1. Create and initialize set

2. add an element: using add() method


3. add multiple elements: using update() method
4. discard an element: discard()
5. remove an element: remove()
6. pop a random element: pop()
7. use | operator
8. use & operator

Program:
my_set = {1, 2, 3}
print(my_set)

my_set = {1.0, "Hello", (1, 2, 3)}


print(my_set)

my_set = {1,3}
print(my_set)

my_set.add(2)
print(my_set)

my_set.update([2,3,4])
print(my_set)

my_set.update([4,5], {1,6,8})
print(my_set)

my_set.discard(4)
print(my_set)

my_set.remove(6)
print(my_set)

my_set = set("HelloWorld")
print(my_set)
print(my_set.pop())
my_set.clear()
print(my_set)

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A | B)

print(A & B)

print(A - B)

print(A ^ B)
Output:

Result:
Result is verfied
Check the spelling…it is csv file show the content of the csv file first.
Aim:
Write a program to copy the content of a Csv file to text file and vice versa
Procedure:
1. Import CSV
2. Give user choice on if he or she requires csv to text file coversion or vice cersa
3. If choice csv to text selected:
a. Accept user input of the name of the CSV file and text file.
b. Open text file as output file and the CSV file as the input file
c. Write in the output file the contents of the csv file using the functions:
i. Write()
ii. Join()
iii. Reader()
d. Close output file
4. If choice selected by user is to convert text file to a csv file then
a. Accept user input of the name of the CSV file and text file.
b. Open text file as input file and the CSV file as the output file
c. Read contents of text file and using writer function write in into text file.
d. Close file
5. Display output

Program:
import csv

choice=input("enter your choice 1.csv to txt 2.txt to csv")


if(choice=='1'):

csv_file = input('Enter the name of your input file: ')


txt_file = input('Enter the name of your output file: ')
with open(txt_file, "w") as my_output_file:
with open(csv_file, "r") as my_input_file:
[ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
my_output_file.close()
else:
txt_file = input('Enter the name of your input file: ')
csv_file = input('Enter the name of your output file: ')
with open(txt_file, 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(" ") for line in stripped if line)
with open(csv_file, 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('pname','color and gb', 'price','ratings'))
writer.writerows(lines)

Output:

Result:
Result is verified.
AIm:
Write a program to replace numbers as hash in a text file
Procedure:
1. open already existing files
a. the one consisting the content in read mode
b. the empty file with writable power
2. read the first file and save content into a variable
3. print contents of file before swapping
4. next, for every character in the file:
a. check if the character is a number with the following condion on the basis of
ASCII characters: (x > 47 and x < 57)
b. if condintion return as true swap the number with a ‘#’
5. write content after swapping into new file
6. read new file
7. print new file after swapping takes place.

Program:
fp = open("myfile.txt", "r")
fp1 = open("out.txt","w+")
text=fp.read()
print("\n the content of the file is : \n" ,text )
for ch in text :
x=ord(ch)
if(x > 47 and x < 57):
x = ord('#')
ch = chr(x)
fp1.write(ch)
fp1.seek(0)
print(" \n after replacing number :")
text=fp1.readlines()
print(text)
fp.close()
fp1.close()
Output:

Result:
Result is Verified

You might also like