Python Lab Manual Work: Command Line Arguments

 import sys

'''
Program to show the working of Command Line Arguments!
'''
if(len(sys.argv)<2):
    print("Less Arguments!")
    sys.exit()
elif(2<=len(sys.argv)<=4):
    print("The number of Command Line Arguments are:- ",len(sys.argv))
    print("The command line arguments are: ",end=" ")
    for elem in sys.argv:
        print(elem,end=" ")
    sys.exit()
else:
    print("Too many arguments!")

################# To get the GCD of two numbers ######################
nums=list(map(int,input("Enter the numbers: ").split()))
ls=[print(max([x if nums[0]%x==0 and nums[1]%x==0 else -1 for x in range(1,min(nums)+1) ])) for i in range(1)]

def exponentiation(base,power)->int:
    if(power==1):
        return base
    return base*exponentiation(base,power-1)
print(exponentiation(2,4))

################# To find the max of a list #####################
def main():
    try:
        # To check for float values
        ls=list(map(float,input("Enter the numbers: ").split()))
    except ValueError as e:
        print("We got a value error!")
        return
    m=ls[0]
    for num in ls[1:]:
        if num>m:
            m=num
    print(m)
main()

#################### To find the first n prime numbers ##########
n=int(input("What's n? "))
ls=[i for i in range(2,555+1) if i not in [i for i in range(2,555+1)
for j in range(2,i) if i%j==0]]
ls1=[print(ls[i]) for i in range(n)]

################## Multiplication of Matrices in Python ###########
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
ls=[[0 for i in range(len(Y[0]))] for j in range(len(X))]
for i in range(len(X)):
    for l in range(len(Y[i])):
        for j in range(len(X[i])):
            ls[i][l]+=X[i][j]*Y[j][l]
# Working on reducing the lines of code...ignore the below
# part:-
# ans=[print(X[i][j]*Y[j][l]) for i in range(len(X)) for l in range(len(Y[i])) for j in range(X[i])]
# print(ans)
print(ls)

############# Newton's Method to find the Square root of a number #########
def sqroot(n,l)->int:
    '''
        n: Number whose root is needed,
        l: The tolerance limit(difference between the number
          and it's root).
    '''
    x=n
    while(True):
        root=0.5*(x+(n/x))
        if(abs(root-x)<l):
            break
        x=root
    print(f"The square root of {n} is {x}.")
sqroot(327,0.0000001)
''' Linear and Binary Search '''
def linear_search(ls,elem):
    n=len(ls)
    for i in range(n):
        if elem==ls[i]:
            return i
    return "Not Found"
def binary_search(ls,elem):
    l,r=0,len(ls)-1
    while(l<r):
        m=(l+r)//2
        if(ls[l]==elem):
            return l
        elif(ls[r]==elem):
            return r
        elif(ls[m]==elem):
            return m
        if elem<ls[m]:
            r=m-1
        else:
            l=m+1
# print(binary_search(sorted([1,21,11,23,4,5]),4))
print(linear_search([1,21,11,23,44,2],22))

Comments

Popular Posts