You are on page 1of 17

1.

What is Command Line Argument


1. Actually command line argument is another way to take input in python.
2. As we know we use input() function to take input in python. If we use command line argument we don't need any input function .
3. Here Input will be passed to the program as an argument from command prompt.
4. What we use here is sys module to process input from command prompt.
5. Like python, it takes the arguments as a string and saves them in a python list form.

Let's it see by an example

Python Program

#Importing sys module

import sys

#Printing list (input values) we have given in command prompt

print(sys.argv)

#Accessing List elements

print (len(sys.argv))

for i in sys.argv:

print("Arguments", i)

Command Prompt (Input and Output)

Note:

1. The above picture is the command prompt


2. In this, what we did first is change the directory to our directory where our program is.
3. In the second step, we have run the program and also passed arguments (in the orange box).
4. After that we changed our Python program (In IDLE) , actually we did here we put a for loop in our program, and then save the
program and run it again and you can see the output in the command prompt.
2.

X = [[1,2,3],

[2 ,5,6],

[7 ,8,9]]

Y = [[9,8,7],

[6,5,4],

[3,2,1]]

result = [[0,0,0],

[0,0,0],

[0,0,0]]

#multiplication

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

[30,24,18]
[66,53,40]
[138,114,90]

3.

Greatest Common Divisor (GCD) is the largest possible integer, that divides both of the integers, condition is that the numbers must
be non-zero.

Method 1 using in-built method

import math

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

b=int(input("Enter second number:"))

print("GCD of ",a," and ",b,"is:",math.gcd(a,b))

Output
Enter first number:60
Enter second number:48
GCD of 60 and 48 is: 12

Method 2 using Recursion

def gcd(a,b):

if(b==0):

return a

else:

return gcd(b,a%b)

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

b=int(input("Enter second number:"))

GCD=gcd(a,b)

print("GCD of ",a," and ",b,"is:",GCD)

Output

Enter first number:60

Enter second number:48

GCD of 60 and 48 is: 12

4.

Program Code

file__IO ="D:\\Komal\\n1\\goeduhub\\python.txt"

with open(file__IO, 'r') as f:

data = f.read()

line = data.splitlines()

words = data.split()

spaces = data.split(" ")

charc = (len(data) - len(spaces))

print('\n Line number:', len(line), '\n Words number:', len(words),


'\n Spaces:', len(spaces), '\n Characters:', (len(data)-len(spaces)))

Output
Line number: 4

Words number: 29

Spaces: 26

Characters: 194

5.

Newton's Method to find Square root

Let the given number be b and let x be a rough guess of the square root of b.

New x = 0.5 * (x + b/x)

Program Code

def newton_method(number, number_iters = 100):

a = float(number)

for i in range(number_iters):

number = 0.5 * (number + a / number)

return number

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

b=int(input("Enter second number:"))

print("Square root of first number:",newton_method(a))

print("Square root of second number:",newton_method(b))

Output

Enter first number:81


Enter second number:5
Square root of first number: 9.0
Square root of second number: 2.23606797749979

6.

Method 1
num=int(input("Enter number: "))

exp=int(input("Enter exponential value: "))

result=1

for i in range(1,exp+1):

result=result*num

print("Result is:",result)

Output

Enter number: 2
Enter exponential value: 10
Result is: 1024

Method 2 using exponential operator (**)

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

exp=int(input("Enter exponential value: "))

result=num**exp

print("Result is:",result)

Output

Enter number: 8
Enter exponential value: 3
Result is: 512

Method 3 using in-built method

import math

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

exp=int(input("Enter exponential value: "))

result=math.pow(num,exp)

print("Result is:",result)

Output

Enter number: 3
Enter exponential value: 5
Result is: 243.0

7.

Program Code
list1=[10,24,7,54,34,76,21]

print("Maximum number:",max(list1)) #using in-built method

maxn=0

for i in list1: #using loops

if(i>maxn):

maxn=i

print("Maximum number:",max(list1))

Output

Maximum number: 76
Maximum number: 76

8.

Program Code

def search(list,n):

for i in range(len(list)):

if list[i] == n:

return True

return False

list = [1, 2, 'goeduhub', 4,'python','machine learning',6]

n = 'python' # to be searched

if search(list, n):

print("Found at index ",list.index(n))

else:

print("Not Found")

Output

Found at index 4

9.

Binary search
It is a sorting algorithm which follows divide and conquer algorithm in which, the list is divided into two parts and then each element
is compared to middle element of the list. If we get a match then, position of middle element is returned otherwise, we search into
either of the halves depending upon the result produced through the match.

Example: Find 103 in {1, 5, 6, 18, 19, 25, 46, 78, 102, 114}.

• Step 1 - middle element is 19 < 103 : 1, 5 ,6 ,18 ,19 ,25, 46 ,78, 102 ,114
• Step 2 - middle element is 78 < 103 : 1 ,5 ,6, 18 ,19 ,25, 46 ,78, 102 ,114
• Step 3 - middle element is 102 < 103 : 1, 5, 6, 18, 19 ,25, 46, 78, 102, 114
• Step 4 - middle element is 114 > 103 : 1 ,5 ,6, 18, 19, 25, 46 ,78 ,102, 114
• Step 5 - searched value is absent : 1 , 5 , 6 ,18 ,19 , 25 , 46 , 78 , 102 , 114

Algorithm:

Binary-Search(numbers[], x, l, r)
if l = r then
return l
else
m := ⌊(l + r) / 2⌋
if x ≤ numbers[m] then
return Binary-Search(numbers[], x, l, m)
else
return Binary-Search(numbers[], x, m+1, r)

Program Code
def binarySearch(arr,beg,end,item):

if end >= beg:

mid = int((beg+end)/2)

if arr[mid] == item :

return mid+1

elif arr[mid] < item :

return binarySearch(arr,mid+1,end,item)

else:

return binarySearch(arr,beg,mid-1,item)

return -1

a=input("Enter elements :")

b=a.split(",")

arr=[]

for i in b:

arr.append(int(i))

arr.sort()

print("Sorted list:",arr)

item = int(input("Enter the item which you want to search:"))

location = -1;

location = binarySearch(arr,0,len(arr),item);

if location != -1:

print("Item found at location: %d" %(location))

else:

print("Item not found")

Output

Enter elements :4,26,87,12,0,67,69,34,32,48


Sorted list: [0, 4, 12, 26, 32, 34, 48, 67, 69, 87]
Enter the item which you want to search:34
Item found at location: 6

10.

Selection sort
It is an sorting algorithm in which the array is divided into sorted array and unsorted array and
we need to find the minimum element from unsorted array and put it in a sorted array sequence.

Algorithm:

1. Set minimum element to index 0

2. Search the minimum element in the array

3. Swap with value at minimum index

4. Increment minimum to point to next element

5. Repeat until list is sorted

Example:

a = [64, 25, 12, 22, 11]

here we need to find the minimum element and place it in the beginning from i=0 to 4

11 25 12 22 64

here we need to find the minimum element and place it in the beginning from i=1 to 4

11 12 25 22 64

here we need to find the minimum element and place it in the beginning from i=2 to 4

11 12 22 25 64

here we need to find the minimum element and place it in the beginning from i=3 to 4

11 12 22 25 64

Program Code
def selsort(n):

for i in range(len(n)-1,0,-1):

max=0

for j in range(1,i+1):

if n[j]>n[max]:

max = j

temp = n[i]

n[i] = n[max]

n[max] = temp

n = [78,25,11,29,75,69,45,67]

selsort(n)

print("Sorted array : ",n)

Output

Sorted array : [11, 25, 29, 45, 67, 69, 75, 78]

11.

Insertion Sort

It is an sorting algorithm in which first element in the array is assumed as sorted, even if it is an unsorted . then, each element in
the array is checked with the previous elements, resulting in a growing sorted output list. With each iteration, the sorting algorithm
removes one element at a time and finds the appropriate location within the sorted array and inserts it there. The iteration continues
until the whole list is sorted.

Advantages:

• It is more efficient than other similar algorithms such as bubble sort or selection sort.
• It is simple to implement and is quite efficient for small sets of data.

Disadvantages:

• Insertion sort is less efficient on larger data sets and less efficient than the heap sort or quick sort algorithms.

Algorithm:
for j=2 to a.length

key = a[j]

insert a[j] into sorted sequence a[1.........j-1]

i=j-1

while i > 0 and a[i] > key

a[i + 1] = a[i]

i=i-1

a[i + 1] = key

For eg: [ 13, 12, 14, 5, 6 ]

Let 's loop for i = 1 to 4

i = 1. as 12 is smaller than 13, move 13 and insert 12 before 13


[12, 13, 14, 5, 6 ]

i = 2. 14 will remain at same location as all elements in A[0..I-1] are smaller than 14
[12, 13, 14, 5, 6]

i = 3. 5 will move at beginning and other elements from 12 to 14 will move one position to front from their current location.
[5, 12, 13, 14, 6]

i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position to front of their current position.

[5, 6, 12, 13, 14]

Program Code

a=[5,46,12,65,13,78,23,80]

b=[]

for i in range(1,len(a)):

key = a[i]

j = i-1

while j>0 and key<=a[j]:

a[j+1]=a[j]

j = j-1

a[j+1] = key

for i in a:

b.append(i)

print("Elements in sorted order are:",b)

Output
Elements in sorted order are: [5, 12, 13, 23, 46, 65, 78, 80]

12.

Merge Sort

Merge sort is a sorting algorithm that follows divide and conquer approach .

Algorithm:

MSort(arr[], l, r)If right > l

1. middle m = (left+right)/2

2. Call mSort(arr, left, middle)

3. Call mSort(arr, middle+1, right)

4. repeat step 2 and 3:

Call msort(arr, left, middle, right)

Example :

Program Code
def mergeSort(nlist):

print("Splitting:",nlist)

if len(nlist)>1:

mid = len(nlist)//2

lefthalf = nlist[:mid]

righthalf = nlist[mid:]

mergeSort(lefthalf)

mergeSort(righthalf)

i=j=k=0

while i < len(lefthalf) and j < len(righthalf):

if lefthalf[i] < righthalf[j]:

nlist[k]=lefthalf[i]

i=i+1

else:

nlist[k]=righthalf[j]

j=j+1

k=k+1

while i < len(lefthalf):

nlist[k]=lefthalf[i]

i=i+1

k=k+1

while j < len(righthalf):

nlist[k]=righthalf[j]

j=j+1

k=k+1

print("Merging:",nlist)

nlist = [23,47,83,13,56,69]

mergeSort(nlist)

print("Sorted list:",nlist)

Output
Splitting: [23, 47, 83, 13, 56, 69]

Splitting: [23, 47, 83]

Splitting: [23]

Merging: [23]

Splitting: [47, 83]

Splitting: [47]

Merging: [47]

Splitting: [83]

Merging: [83]

Merging: [47, 83]

Merging: [23, 47, 83]

Splitting: [13, 56, 69]

Splitting: [13]

Merging: [13]

Splitting: [56, 69]

Splitting: [56]

Merging: [56]

Splitting: [69]

Merging: [69]

Merging: [56, 69]

Merging: [13, 56, 69]

Merging: [13, 23, 47, 56, 69, 83]

Sorted list: [13, 23, 47, 56, 69, 83]

13.

Program Code
numr=int(input("Enter range:"))

print("Prime numbers:",end=' ')

for n in range(1,numr):

for i in range(2,n):

if(n%i==0):

break

else:

print(n,end=' ')

Output

Enter range: 50
Prime numbers: 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

14.

Program Code
import sys, pygame

pygame.init()

size = width, height = 800, 400

speed = [1, 1]

background = 255, 255, 255

screen = pygame.display.set_mode(size)

pygame.display.set_caption("Bouncing ball")

ball = pygame.image.load("ball.png")

ballrect = ball.get_rect()

while 1:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

ballrect = ballrect.move(speed)

if ballrect.left < 0 or ballrect.right > width:

speed[0] = -speed[0]

if ballrect.top < 0 or ballrect.bottom > height:

speed[1] = -speed[1]

screen.fill(background)

screen.blit(ball, ballrect)

pygame.display.flip()

ball.jpg

Output
Ball is bouncing on Display Screen

You might also like