Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

1.python Assignment: July 8, 2021

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

1.

Python Assignment

July 8, 2021

Python: without numpy or sklearn


Q1: Given two matrices please print the product of those two matrices

[7]: # write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input examples

import pdb
# you can free to change all these codes/structure
# here A and B are list of lists
def matrix_mul(A, B):
A_nrows=len(A)
A_ncols=len(A[0])
B_nrows=len(B)
B_ncols=len(B[0])
C=[[0 for x in range(B_ncols)] for y in range(A_nrows) ]

if (A_ncols==B_nrows):
#do mat mult
for i in range(A_nrows):
for j in range(B_ncols):
for k in range(A_ncols):
C[i][j]+= A[i][k]*B[k][j]
#pdb.set_trace()
return(C)
else:
print("Matrix multiplication is not possible")

A=[[1,2,3],[3,4,5]]
B=[[3,4,5],[5,6,7],[7,8,9]]

#pdb.set_trace()
matrix_mul(A, B)

1
[7]: [[34, 40, 46], [64, 76, 88]]

Q2: Select a number randomly with probability proportional to its magnitude from the given array
of n elements
consider an experiment, selecting an element from the list A randomly with probability proportional
to its magnitude. assume we are doing the same experiment for 100 times with replacement, in
each experiment you will print a number that is selected randomly from A.

[7]: import random


from random import uniform
# write your python code here
# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input examples

# you can free to change all these codes/structure


def pick_a_number_from_list(A):
# your code here for picking an element from with the probability␣
,→propotional to its magnitude

num= random.uniform(0,sum(A))
select_num=min(A)
B=sorted(A)
C=[]
for i in range(len(B)):
C.append(sum(B[0:i+1]))
#pdb.set_trace()

for i in range(len(C)):
if num> C[i]:
select_num=B[i+1]

return select_num

def sampling_based_on_magnitued(A):
for i in range(1,50):
number = pick_a_number_from_list(A)
print(number)

A = [0 ,5 ,27 ,6 ,13 ,28 ,100, 45, 10 ,79]


#A=[5,10]
sampling_based_on_magnitued(A)

27
45
45
10
5

2
79
45
100
27
13
79
27
100
79
28
100
27
100
100
79
100
79
100
100
79
100
79
79
79
100
79
100
79
79
100
79
45
79
28
79
100
100
28
13
100
100
28
45
100
Q3: Replace the digits in the string with #
consider a string that will have digits in that, we need to remove all the not digits and replace the
digits with #

3
[18]: import re
# write your python code here
# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input examples

# you can free to change all these codes/structure


# String: it will be the input to your program
def replace_digits(String):
# write your code
return_string=[]
for char in String:
if char.isdigit():
return_string.append('#')
strjoin=''
return(strjoin.join(return_string)) # modified string which is after␣
,→replacing the # with digits

A='abc234'
replace_digits(A)

[18]: '###'

Q4: Students marks dashboard


consider the marks list of class students given two lists Students = [‘stu-
dent1’,‘student2’,‘student3’,‘student4’,‘student5’,‘student6’,‘student7’,‘student8’,‘student9’,‘student10’]
Marks = [45, 78, 12, 14, 48, 43, 45, 98, 35, 80] from the above two lists the Student[0] got Marks[0],
Student[1] got Marks[1] and so on your task is to print the name of students a. Who got top 5
ranks, in the descending order of marks b. Who got least 5 ranks, in the increasing order of marks
d. Who got marks between >25th percentile <75th percentile, in the increasing order of marks

[32]: # write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input examples

# you can free to change all these codes/structure


def display_dash_board(students, marks):
d={}
for i in range(len(marks)):
d[students[i]]=marks[i]

# write code for computing top top 5 students


top_5_students = sorted(d.items(), key=lambda x:x[1], reverse=True)[:5]
# write code for computing top least 5 students
least_5_students = sorted(d.items(), key=lambda x:x[1], reverse=False)[:5]
# write code for computing top least 5 students

4
students_within_25_and_75 = sorted(d.items(), key=lambda x:x[1],␣
,→ reverse=False)[int(0.25*len(marks)):int(0.75*len(marks))]

return top_5_students, least_5_students, students_within_25_and_75

students =␣
,→['student1','student2','student3','student4','student5','student6','student7','student8','st

marks = [45, 78, 12, 14, 48, 43, 47, 98, 35, 80]
top_5_students, least_5_students, students_within_25_and_75 =␣
,→display_dash_board(students, marks)

print("\nTop 5 students")
for element in top_5_students:
print(element[0]+" "+ str(element[1]))

print("\nLeast 5 students")
for element in least_5_students:
print(element[0]+" "+ str(element[1]))

print("\nStudents within 25 and 75")


for element in students_within_25_and_75:
print(element[0]+" "+ str(element[1]))

Top 5 students
student8 98
student10 80
student2 78
student5 48
student7 47

Least 5 students
student3 12
student4 14
student9 35
student6 43
student1 45

Students within 25 and 75


student9 35
student6 43
student1 45
student7 47
student5 48
Q5: Find the closest points

5
consider you have given n data points in the form of list of tuples like
S=[(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5),..,(xn,yn)] and a point P=(p,q) your task is to
find 5 closest points(based on cosine distance) in S from P cosine distance between two points
(x,y) and (p,q) is defind as cos−1 ( √ 2 (x·p+y·q)
2
√ 2 2 )
(x +y )· (p +q )

[6]: import math


import pdb
from heapq import nlargest

# write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input examples

# you can free to change all these codes/structure

# here S is list of tuples and P is a tuple ot len=2


def closest_points_to_p(S, P):
# write your code here
point_x=P[0]
point_y=P[1]
points_return={}
for point in S:
x=point[0]
y=point[1]

distance= math.acos((x*point_x+y*point_y)/math.sqrt(x*x+y*y)/math.
,→ sqrt(point_x*point_x+point_y*point_y))
points_return[distance]=point

return sorted(points_return.items(), key=lambda x:x[0], reverse=False)[:5] ␣


,→ # its list of tuples

S= [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1),(6,0),(1,-1)]
P= (3,-4)
#closest_points_to_p(S, P)
points = closest_points_to_p(S, P)

for x in points:
print(x[1]) #print the returned values

(6, -7)
(1, -1)
(6, 0)
(-5, -8)
(-1, -1)
Q6: Find Which line separates oranges and apples

6
consider you have given two set of data points in the form of list of tuples like
and set of line equations(in the string formate, i.e list of strings)
your task is to for each line that is given print “YES”/“NO”, you will print yes, if all the red points
are one side of the line and blue points are other side of the line, otherwise no

[14]: import math


import re
import pdb
# write your python code here
# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input strings

# you can free to change all these codes/structure


def i_am_the_one(red,blue,line):
w= (re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", line ))
red_distance=[]
blue_distance=[]
result="No"

for point in blue:


blue_distance.
,→append(point[0]*float(w[0])+point[1]*float(w[1])+float(w[2]))

for point in red:


red_distance.
,→append(point[0]*float(w[0])+point[1]*float(w[1])+float(w[2]))

#pdb.set_trace()

if (all(x>0 for x in blue_distance) & all(y<0 for y in red_distance)):


result="Yes"
if (all(x<0 for x in blue_distance) & all(y>0 for y in red_distance)):
result="Yes"

return result

Red= [(1,1),(2,1),(4,2),(2,4), (-1,4)]


Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]

for i in Lines:
yes_or_no = i_am_the_one(Red, Blue, i)
print(yes_or_no) # the returned value

Yes
No
No

7
Yes
Q7: Filling the missing values in the specified formate
You will be given a string with digits and ‘_’(missing value) symbols you have to replace the ‘_’
symbols as explained
for a given string with comma seprate values, which will have both missing values numbers like ex:
”, , x, , , _” you need fill the missing values
Q: your program reads a string like ex: ”, , x, , , _” and returns the filled sequence
Ex:

[55]: # write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input strings

import pdb

# you can free to change all these codes/structure


def curve_smoothing(string):
char_list=string.split(",")
num_list=[]
for char in char_list:
if char=="_":
num_list.append(0)
else:
num_list.append(int(char))

return fill_iter(num_list)

def fill_iter(number_list):
num_list_new=[]
index=[i for i, e in enumerate(number_list) if e != 0]

if len(index)==1 and (index[0]==0 or index[0]==len(number_list)-1):


insert_val=number_list[index[0]]/len(number_list)
for x in range(len(number_list)):
number_list[x]=insert_val

else:
start_index=0
start_val=0
current_index=0
current_val=0
for element in index:
insert_val=(number_list[element]+current_val)/
,→(element-start_index+1)

8
for x in range(start_index,element+1):
number_list[x]=insert_val
current_val=insert_val
start_index=element
#pdb.set_trace()

if element==index[-1]:
if(element<len(number_list)-1):
insert_val=(number_list[element])/(len(number_list)-element)
for x in range(element,len(number_list)):
number_list[x]=insert_val
current_val=insert_val
start_index=element

return number_list

S= "_,_,30,_,_,_,50,_,_"
#S="_,_,_,24"
#S="40,_,_,_,60"
#S="80,_,_,_,_"
smoothed_values= curve_smoothing(S)
print(smoothed_values)

[10.0, 10.0, 12.0, 12.0, 12.0, 12.0, 4.0, 4.0, 4.0]


Q8: Filling the missing values in the specified formate
You will be given a list of lists, each sublist will be of length 2 i.e. [[x,y],[p,q],[l,m]..[r,s]] consider its
like a martrix of n rows and two columns 1. the first column F will contain only 5 uniques values
(F1, F2, F3, F4, F5) 2. the second column S will contain only 3 uniques values (S1, S2, S3)
Ex:

[16]: # write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input strings

# you can free to change all these codes/structure


def compute_conditional_probabilites(A):
F=set()
S=set()
for element in A:
F.add(element[0])
S.add(element[1])
for f in F:

9
for s in S:
n,d=0,0
for element in A:
if element[0]==f and element[1]==s:
n=n+1
if element[1]==s:
d=d+1
print("P(F="+f+"|S=="+s+")="+str(n)+"/"+str(d))

# print the output as per the instructions

A =␣
,→[['F1','S1'],['F2','S2'],['F3','S3'],['F1','S2'],['F2','S3'],['F3','S2'],['F2','S1'],['F4','

compute_conditional_probabilites(A)

P(F=F3|S==S2)=1/3
P(F=F3|S==S3)=1/3
P(F=F3|S==S1)=0/4
P(F=F4|S==S2)=0/3
P(F=F4|S==S3)=1/3
P(F=F4|S==S1)=1/4
P(F=F5|S==S2)=0/3
P(F=F5|S==S3)=0/3
P(F=F5|S==S1)=1/4
P(F=F1|S==S2)=1/3
P(F=F1|S==S3)=0/3
P(F=F1|S==S1)=1/4
P(F=F2|S==S2)=1/3
P(F=F2|S==S3)=1/3
P(F=F2|S==S1)=1/4
Q9: Given two sentances S1, S2
You will be given two sentances S1, S2 your task is to find
Ex:

[20]: # write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input strings

# you can free to change all these codes/structure


def string_features(S1, S2):
s1=set(S1.split(" "))
s2=set(S2.split(" "))
a=len(set.intersection(s1,s2))
b=s1-s2

10
c=s2-s1
return a, b, c

S1= "the first column F will contain only 5 uniques values"


S2= "the second column S will contain only 3 uniques values"
a,b,c = string_features(S1, S2)
print(a)
print(list(b))
print(list(c))

7
['first', 'F', '5']
['3', 'second', 'S']
Q10: Given two sentances S1, S2
You will be given a list of lists, each sublist will be of length 2 i.e. [[x,y],[p,q],[l,m]..[r,s]] consider
its like a martrix of n rows and two columns
a. the first column Y will contain interger values
b. the second column Yscore will be having float values Your task is to find the value of
f (Y, Yscore ) = −1 ∗ n1 Σf oreachY,Yscore pair (Y log10(Yscore ) + (1 − Y )log10(1 − Yscore )) here n
is the number of rows in the matrix
−1
8 ·((1·log10 (0.4)+0·log10 (0.6))+(0·log10 (0.5)+1·log10 (0.5))+...+(1·log10 (0.8)+0·log10 (0.2)))

[6]: # write your python code here


# you can take the above example as sample input for your program to test
# it should work for any general input try not to hard code for only given␣
,→input strings

import math
# you can free to change all these codes/structure
def compute_log_loss(A):
f=0
for y in A:
f+=y[0]*math.log10(y[1])+(1-y[0])* math.log10(1-y[1])
f=-1*f/len(A)

return f

A = [[1, 0.4], [0, 0.5], [0, 0.9], [0, 0.3], [0, 0.6], [1, 0.1], [1, 0.9], [1,␣
,→0.8]]

loss = compute_log_loss(A)
print(loss)

0.42430993457031635

[ ]:

11

You might also like