Illustrative Problems 1. Find Minimum in A List

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

ILLUSTRATIVE PROBLEMS

1. Find minimum in a list

def minimum(x):

mini = x[0]

for i in x[0:]:

if i < mini:

mini = i

else:

mini = x[0]

return (mini)

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

print(minimum(b))

2. Insert a card in a list of sorted cards

guessesTaken = 0

number = random.randint(1, 20)

while guessesTaken < 6:

print('Take a guess.')

guess = input()

guess = int(guess)

guessesTaken = guessesTaken + 1

if guess < number:

print('Your guess is too low.')

if guess > number:

print('Your guess is too high.')

if guess == number:

break
if guess == number:

guessesTaken = str(guessesTaken)

print('Good job, ! You guessed my number in ' + guessesTaken + ' guesses!')

if guess != number:

number = str(number)

print('Nope. The number I was thinking of was ' + number)

3. Towers of Hanoi

def moveTower(height,fromPole, toPole, withPole):

if height >= 1:

moveTower(height-1,fromPole,withPole,toPole)

moveDisk(fromPole,toPole)

moveTower(height-1,withPole,toPole,fromPole)

def moveDisk(fp,tp):

print("moving disk from",fp,"to",tp)

moveTower(3,"A","B","C")

UNIT 2

1. Exchange the values of two variables

def swa(num1,num2):

#swapping with temporary variable

temp=num1

num1=num2

num2=temp

#print the result print("Swapped Numbers")

print(num1)

print(num2)

print("Enter the first number")


#input first number

n1=int(input())

print("Enter the second number")

#input second number

n2=int(input())

swa(n1,n2) #calling Function

2. Distance between two points

def dist(x1,y1,x2,y2):

d1=(x2-x1)**2

d2=(y2-y1)**2

#compute distance

distance=((d1)+(d2))**2

print("The distance between two points",distance)

print("Enter the value of x1")

#input First number

x1=int(input())

print("Enter the value of y1")

#input Second number

y1=int(input())

print("Enter the value of x2")

#input third number

x2=int(input())

print("Enter the value of y2")

#input Fourth number

y2=int(input())

dist(x1,y1,x2,y2) #function call


3. Circulate the values of n variables

def rotate(l,order):

for i in range(0,order):

j=len(l)-1

while(j>0): #swapping

t=l[i]

l[i]=l[j]

l[j]=t

j=j-1

print(i,'rotation',l)

return

L=[10,20,30,40,50] #input

List rotate(L,3) #function call

UNIT 3

1. Square Root of a number

number = int(input("Enter a number to find the square root : "))

if number < 0 :

print("Please enter a valid number.")

else :

sq_root = number ** 0.5

print("Square root of {} is {} ".format(number,sq_root))

2. GCD of two numbers

print("Enter two numbers to compute GCD")

a=int(input())

b=int(input())
if a==0:

print("GCD is",b)

elif b==0:

print("GCD is",a)

elif a>b:

small=b

else:

small=a

gcd=1

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

if a%i==0 and b%i==0:

gcd=i

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

3. Exponentiation

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

b=int(input("Enter its power"))

sum=1

for i in range(b):

sum*=a

print(a,"raised to",b, "is",sum)

4. Sum of numbers in an array

arr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

sum=0

for i in arr:

sum+=i

print("The sum of numbers is", sum)

5. Linear Search
def search(arr, x):

for i in range(len(arr)):

if arr[i] == x:

return i

return -1

arr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

x=int(input("Enter the element to be searched"))

a=search(arr,x)

if a==-1:

print("Element not found")

else:

print("Element is present in position",a)

6. Binary Search

def binarySearch (arr, l, r, x):

# Check base case

if r >= l:

mid = (l + r)//2

# If element is present at the middle itself

if arr[mid] == x:

return mid

# If element is smaller than mid, then it can only be present in left subarray

elif arr[mid] > x:

return binarySearch(arr, l, mid-1, x)

# Else the element can only be present in right subarray

else:

return binarySearch(arr, mid+1, r, x)

else:
# Element is not present in the array

return -1

# Test array

arr = [ 2, 3, 4, 10, 40,56 ]

x = 56

# Function call

result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:

print("Element is present at index %d" % result)

else:

print("Element is not present in array")

UNIT 4

1. Selection Sort

def selsort(A):
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element with the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Main Program
A = [64, 25, 12, 22, 11]
selsort(A)
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i])

2. Insertion Sort

#Function to perform insertion sort


def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greater than key, to one
#position ahead of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Main Program
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("%d" %arr[i])

3. Merge Sort

#Function to perform Merge Sort

def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves

mergeSort(L) # Sorting the first half


mergeSort(R) # Sorting the second half

i = j = k = 0

# Copy data to temp arrays L[] and R[]


while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1

# Checking if any element was left


while i < len(L):
arr[k] = L[i]
i+=1
k+=1

while j < len(R):


arr[k] = R[j]
j+=1
k+=1

# Code to print the list


def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print()

# Main Program
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

4. Histogram of Elements in a List

def histogram(A):

unique = [] #List to hold unique elements in the List A

for x in A:

if x not in unique:

unique.append(x)

for n in unique: #Count of occurrence of elements in the list


unique on the list A

a=A.count(n)

print("Frequency of",n,"is", a )

A=[1,2,3,4,5,6,1,2,3,4,5,1,2,3,4,1,2,3,1,2,1]

histogram(A)

UNIT 5

1. Python Script to count the number of words and characters in a file

#Counting characters in a File

f=open("a.txt",'r')

count=0

for i in f:

for j in i:

count+=1 #character count

print("No of characters in file", count)

#Counting words in a File - Method 1

f=open("a.txt",'r')

wcount=0
for i in f:

words=i.split()

wcount+=len(words)

print("No of words in file", wcount)

#Counting words in a File - Method 2

f=open("a.txt",'r')

wcount=0

for i in f.read().split():

wcount+=1

print("No of words in file", wcount)

2. Copying the contents of one file to the other

from shutil import copyfile

copyfile("a.txt","b.txt") #copies the contents of file a to file b

f=open("b.txt",'r') #To view the contents of the new file

c=f.readlines()

print(c)

Working with Complex numbers

a=2+3j

b=3-2J

c=a+b

print('c',c)

d=int(input("Enter real part of complex number"))

e=int(input("Enter imaginary part of complex number"))


z=complex(d,e)

print('z',z)

f=z-c

print('f',f)

Output:

c (5+1j)

Enter real part of complex number5

Enter imaginary part of complex number-2

z (5-2j)

f -3j

You might also like