0% found this document useful (0 votes)
53 views

Algorithms Exercise - Solution

The document contains Python code examples that demonstrate various algorithms for working with numbers, lists, strings, and searching. Functions are defined to determine if a number is prime, sum numbers in a range, find the average of a list, count vowels in a string, and use linear and binary search to find items in a list.

Uploaded by

maryam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Algorithms Exercise - Solution

The document contains Python code examples that demonstrate various algorithms for working with numbers, lists, strings, and searching. Functions are defined to determine if a number is prime, sum numbers in a range, find the average of a list, count vowels in a string, and use linear and binary search to find items in a list.

Uploaded by

maryam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Write the python code to solve the

following:
Sequences and summation
Determine if a given number is prime or not.
def isPrime(number):
for i in range(2,number):
if(number % i == 0):
print('not prime')
return
print('Yes it is prime')
#Call the function
isPrime(49)
isPrime(67)

Sum all numbers upto n


def Summation(n):
total = 0
for i in range(1,n+1):
total = total + i
print total
#Call the function
Summation(10)

Another New Solution

def AvgNumbers(nlist):
total = 0
for n in nlist:
total = total + n
return total

#print the function


print('Total is', AvgNumbers([2,3,6,9,0]))

print('Total is', AvgNumbers([22,3,6,19,0]))

Sum a given sequence (for example ∑𝟓𝟏 𝒊𝟐 + 𝟑)


def SumSequence(n):
total = 0
for i in range(1,6):
total = total + (i**2 + 3)
print total
#Call the function
SumSequence(10)

Sum odd numbers upto n


def SumOdd(n):
total = 0
for i in range(1,n+1):
if (i % 2) != 0: #check if number is odd remainder is not equal (!=) to zero
total = total + i
print total

#Call the function


SumOdd(10)

Sum even numbers upto n


def SumEven(n):
total = 0
for i in range(1,n+1):
if (i % 2) == 0: #check if number is even remainder is equal (==) to zero
total = total + i
print total

#Call the function


SumEven(10)

Compute the factorial of a given number

Note: Factorial of a number is as follow:

n! = 1 * 2 * 3* 4… n

def factorial(n):
f = 1
for i in range(2,n+1):
f = f * i
print f
#Call the function
factorial(5)

Compute and print the n terms of a fibonacci sequence


Fibonacci sequence is a recursive sequence that adds the previous two numbers to
get the next number:
an = an-1 + an-2
0 1 1 2 3 5 8 13….
def fibonacci(n):
prev1=0 #1st term
prev2=1 #2nd term
fib_n=0
for i in range (3,n+1): #from 3rd term to nth term
fib_n = prev1+ prev2
prev1 = prev2 #move 2nd term to 1st term
prev2 = fib_n #move current term to 2nd term
print(fib_n)
#call function
fibonacci(10)

Lists
Find the maximum number in list
def FindMax(lstNumbers):
maxn = numbers[0]
for n in lstNumbers:
if n > maxn:
maxn = n
print('Maximum number is ', maxn)
#call function
lst = [3,10,34,11,67,2]
FindMax(lst)

Find the minimum number in a list


def FindMin(lstNumbers):
minn = numbers[0]
for n in lstNumbers:
if n < minn:
minn = n
print('Minimum number is ', minn)
#call function
lst = [3,10,34,11,67,2]
FindMin(lst)
Count even numbers in a list
def CountEven(lstNumbers):
count = 0
for n in lstNumbers:
if (n % 2 ==0): #if n is divisible by 2, no remainders
count = count + 1 # increase counter by 1
print(count)
#call function
lst = [3,10,34,11,67,2]
CountEven(lst)
Count odd numbers in a list
def CountOdd(lstNumbers):
count = 0
for n in lstNumbers:
if (n % 2 !=0): #if n is NOT divisible by 2
count = count + 1 # increase counter by 1
print(count)
#call function
lst = [3,10,34,11,67,2]
CountOdd(lst)

Convert all numbers in a list to even number


def ConvertToEven(lstNumbers):
for i in range(len(lstNumbers)):
if (lstNumbers[i] % 2 !=0): #if n is not divisible by 2
lstNumbers[i] = lstNumbers[i]+ 1 # increase the number by 1
print(lstNumbers)
#call function
lst = [3,10,34,11,67,2]
ConvertToEven(lst)

Count vowels in a string


def countVowels(sentence):
count = 0
lstVowels = ['a','e','i','o','u']
for letter in sentence:
if(letter in lstVowels):
count = count + 1

print(sentence , ' has ', count , ' vowels')

#Call the function


countVowels('discrete math is fun')

Add all the numbers in a list


def SumList(lstNumbers):
total = 0
for n in lstNumbers:
total = total + n
print total

#Call the function


numbers = [3,68,32,44,1,72]
SumList(numbers)
Find the average of all the numbers in a list
def AvgList(lstNumbers):
total = 0
for x in lstNumbers:
total = total + x
avg = total/len(lstNumbers)
print(avg)
#Call the function
AvgList([2,5,1,8])

Add all the odd numbers in a list


def AddOdd(numbers):
total = 0
for n in numbers:
if (n % 2 != 0):
total = total + n
print (total)

#Call the function


lst = [3,10,34,11,67,2]
AddOdd (lst)

Add all the even numbers in a list


def AddEven(numbers):
total = 0
for n in numbers:
if (n % 2 == 0):
total = total + n
print (total)

#Call the function


lst = [3,10,34,11,67,2]
AddEven (lst)
Searching
Find a number in a list using Linear search and print it’s position
def LinearSearch (lstNumbers, searchValue):
for i in range(len(lstNumbers)):
if lstNumbers[i] == searchValue:
print('postion found at position ', i)
return
print('Number not found')
#Call the function
lst = [3,10,34,11,67,2]
LinearSearch(lst,11)

OR New

def LinearSearch (nList, sV):


for i in range(len(nList)):
if nList[i] == sV:
return i ;
return -1

#Call the function


print(LinearSearch([3,10,34,11,67,2],11))

Find a number in a list using Binary Search and print its position
def binarySearch(lstNumbers, searchValue):
low = 0
high = len(lstNumbers) - 1
while (low <=high):
mid = (low + high)//2 #integer division
if (searchValue == lstNumbers[mid]):
print('Number found at ', mid)
return
elif (searchValue < lstNumbers[mid]):
high = mid -1
else:
low = mid + 1
print('not found')

#call function
lst = [12,23,33,45,49,62,74,77,89]
binarySearch(lst,56)
binarySearch(lst,74)
binarySearch(lst,33)
'''
def Swap(x,y):
if (x > y):
z = x
x = y
y = z
print (x, y)

Swap(8,3)
Swap(12,19) #Because 12 is less than 19 it wont swap
'''

'''
def printList1(numbers):
for x in numbers :
print (x)

printList1([10,3,5,16,4])
'''

'''
def PrintList2(numbers):
for i in range (len(numbers)):
print (numbers [i])

PrintList2([4,18,12,64,29,11])
'''

'''
#write a function that print the sum of numbers in a list
def sumList(numbers):
total = 0
for x in numbers :
total = total + x
print(total)

sumList([2,5,1,10])
'''

'''
#write a function that print the average of numbers in a list
def avgList(numbers):
total = 0
for x in numbers :
total = total + x
avg = total / len(numbers)
print(avg)

avgList([2,5,1,8])
'''

'''
#write a function to search a number in a list
def SearchNumber(numbers, x):
found = False
for n in numbers:
if n == x:
found = True
break # to exit the loop

if(found):
print("Number is Found")
else:
print("Not Found")

SearchNumber([3,5,12,9], 8)
'''

'''
#modify the function to find a number and also print the location where
the number was found

def SearchNumber(numbers, x):


found = False
for i in range:
if numbers[i] == x :
found = True
print("Position of number is ", i)
break # to exit the loop

if(found):
print("Number is Found")
else:
print("Not Found")

lst = [3,10,34,11,67,2]
SearchNumber(lst,11)
SearchNumber(lst,2)
SearchNumber(lst,13)
'''

'''
def FindMax(numbers):
maxn = 0
for n in numbers:
if n > maxn :
maxn = n
print("Your Maximum number is ", maxn)

lst = [3,10,34,11,67,2] #we must have a list to search a number


FindMax(lst)
'''

'''
def PrintEven(lstNumbers):
count = 0
for n in lstNumbers:
if (n%2 == 0): # check if n is divisable by 2, no remainders
count = count + 1 #increase counter by 1
print(count)

lst = [2,4,6,8,13,11]
PrintEven(lst)

def PrintEven2(lstNumbers):
count = 0
for i in range (len(lstNumbers)):
if ( lstNumbers[i] % 2 == 0):
count = count + 1

print(count)
#test function
lst = [30,7,2,99,12,11]
PrintEven2(lst)
'''
'''
# Prime number
def IsPrime(num):
for n in range (2,num):
if (num%n == 0):
print(num, "Is Not a Prime number")
return #exit the function / break -> get out from loop

print(num, "Is a Prime number")

#test function
num = int(input("Enter the number : "))
IsPrime(num)
'''

'''
#Linear Search ~Sorted~ ‫ﻣﺮﺗﺐ‬
def LinearSearchSorted(lstNumbers, target):
for n in lstNumbers:
if(n > target):
print ("Not Found")
return
elif (n == target):
print("Found")
return

lst = [2,4,8,10,45,54,66]
LinearSearchSorted(lst, 55)
LinearSearchSorted(lst, 66)
'''

'''
#Linear Search not sorted
def LinearSearch(lstNumbers, target):
for n in lstNumbers:
if(n == target):
print ("Found")
return
print("Not Found")

lst = [2,4,8,10,45,54,66]
LinearSearch(lst, 55)
LinearSearch(lst, 66)
'''

'''
#Linear Search not sorted find the ~index~
def LinearSearchIndex(lstNumbers, target):
for i in range(len(lstNumbers)):
if(lstNumbers[i] == target):
print ("Found")
return i
print("Not Found")
return -1

lst = [2,4,8,10,45,54,66] #it starts from 0


postion = LinearSearchIndex(lst, 8)
print("Number at", postion)
'''

'''
def binarySearch (lstN, sv):
low = 0
high = len(lstN) - 1
while (low <= high):
mid = (low + high) / 2
if (sv == lstN[mid]):
print("Number found at", mid)
return
elif (sv > lstN[mid]):
low = mid + 1
else:
high = mid - 1
print("Not Found")

lst = [2,4,8,10,45,54,66] #it starts from 0


postion = binarySearch(lst, 8)
'''

'''
def printList(lstNumbers):
for i in range (len(lstNumbers)):
print (lstNumbers[i])

#test function
lst = [2,4,8,10,45,54,66]
printList(lst)
'''

'''
def printList(lstNumbers):
i=6
while (i < len(lstNumbers)):
print (lstNumbers[i])

lst = [2,4,8,10,45,54,66]
printList(lst)
'''

#to print from reverse


def printList(lstNumbers):
i=6

while (i > len(lstNumbers)):


print (lstNumbers[i])
i=i-1
lst = [2,4,8,10,45,54,66]
printList(lst)

You might also like