You are on page 1of 20

INTRODUCTION TO COMPUTER

SCIENCE AND CONTEMPORARAY LAN

[ASSIGNMENT]
PYTHON PROGRAMS

MADE BY : MUHAMMAD SAEED DESAI


SERIAL NO : 47
EVENING SECTION : A
BATCH - 2021
1.
CODE OF MULTIPLE OF 3 : 
2.
c = 0 
d = 0 
a = float ( input ( "enter first no :")) 
b = float ( input  ( "enter second  no :")) 
while ( c  ==  0 ): 
    c = a * b 
    d = c / 3 
if ( d % 3 == 0 ) : 
    print ( "multiple of 3 is :") 
else : 
    print ( "not a multiple of 3 :") 
2 . CODE OF MULTIPLE OF 7 : 
c = 0 
d = 0 
a = float ( input ( "enter first no :")) 
b = float ( input  ( "enter second  no :")) 
while ( c  ==  0 ): 
    c = a * b 
    d = c / 7 
if ( d % 7 == 0 ) : 
    print ( "multiple of 7 is :") 
else : 
    print ( "not a multiple of 7 :") 
 
 
 
 
3 . Write a C program to print all
permutations of a given string 
def toString(List): 
    return ''.join(List) 
def permute(a, l, r): 
    if l==r: 
        print toString(a) 
    else: 
        for i in xrange(l,r+1): 
            a[l], a[i] = a[i], a[l] 
            permute(a, l+1, r) 
            a[l], a[i] = a[i], a[l]  
string = "ABC" 
n = len(string) 
a = list(string) 
permute(a, 0, n-1) 
4.  Lucky Numbers 
def isLucky(n): 
         next_position = n 
      
    if isLucky.counter > n: 
        return 1 
    if n % isLucky.counter == 0: 
        return 0 
         next_position = next_position - next_position / 
                                   isLucky.counter 
      
    isLucky.counter = isLucky.counter + 1 
      
    return isLucky(next_position) 
if isLucky(x): 
    print x,"is a Lucky number" 
else: 
    print x,"is not a Lucky number" 
 

5  Write a program to add two numbers in base


14 
 
 
def getNumeralValue(num) : 
  
    if( num >= '0' and num <= '9') : 
        return ord(num) - ord('0') 
    if( num >= 'A' and num <= 'D') : 
        return ord(num ) - ord('A') + 10 
 
def getNumeral(val): 
  
    if( val >= 0 and val <= 9): 
        return chr(val + ord('0')) 
    if( val >= 10 and val <= 14) : 
        return chr(val + ord('A') - 10) 
  
def sumBase14(num1, num2): 
  
    l1 = len(num1) 
    l2 = len(num2) 
    carry = 0 
          
    if(l1 != l2) : 
      
        print("Function doesn't support numbers of different" 
                " lengths. If you want to add such numbers then" 
                " prefix smaller number with required no. of zeroes") 
      
    res = [0]*(l1 + 1) 
              
     for i in range(l1 - 1, -1, -1): 
      
                nml1 = getNumeralValue(num1[i]) 
        nml2 = getNumeralValue(num2[i]) 
          
               res_nml = carry + nml1 + nml2; 
          
            if(res_nml >= 14) : 
            carry = 1 
            res_nml -= 14 
        else: 
            carry = 0 
        res[i+1] = getNumeral(res_nml) 
          
    if(carry == 0): 
        return (res + 1) 
      
    res[0] = '1' 
    return res 
 if __name__ == "__main__": 
      
    num1 = "DC2" 
    num2 = "0A3" 
  
    print("Result is ",end="") 
    res = sumBase14(num1, num2) 
    for i in range(len(res)): 
        print(res[i],end="") 
 

 6 . Babylonian method for square root 


 
def squareRoot(n): 
x = n 
y = 1 
# e decides the accuracy level 
e = 0.000001 
while(x - y > e): 
x = (x + y)/2 
y = n / x 
return x 
 7 . Multiply two integers without using
multiplication, division and bitwise operators,
and no loops 
 
def multiply(x,y): 
    if(y == 0): 
        return 0 
    if(y > 0 ): 
        return (x + multiply(x, y - 1)) 
    if(y < 0 ): 
        return -multiply(x, -y) 
 
 

8 . Print all combinations of points that can


compose a given number 
 
MAX_POINT = 3; 
ARR_SIZE = 100;  
arr = [0] * ARR_SIZE; 
def printCompositions(n, i): 
    if (n == 0): 
        printArray(arr, i); 
    elif(n > 0): 
        for k in range(1,MAX_POINT + 1): 
            arr[i] = k; 
            printCompositions(n - k, i + 1); 
def printArray(arr, arr_size): 
    for i in range(arr_size): 
        print(arr[i], end = " "); 
    print(); 
   

9. Write you own Power without


using multiplication(*) and division(/) operators 
def pow(a,b): 
    if(b==0): 
        return 1 
          
    answer=a 
    increment=a 
      
    for i in range(1,b): 
        for j in range (1,a): 
            answer+=increment 
        increment=answer 
    return answer 
 

10.Program for Fibonacci numbers


# Function for nth Fibonacci number
 
def Fibonacci(n):
    if n<0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n==0:
        return 0
    # Second Fibonacci number is 1
    elif n==1:
        return 1
    else:
        return Fibonacci(n-1)+Fibonacci(n-2)

11.Average of a stream of numbersAverage of


a stream of numbers
def getAvg(prev_avg, x, n):
    return ((prev_avg *
             n + x) /
            (n + 1));
 def streamAvg(arr, n):
    avg = 0;
    for i in range(n):
        avg = getAvg(avg, arr[i], i);
        print("Average of ", i + 1,
              " numbers is ", avg);

12.Count numbers that don’t contain 3


# Python program to count numbers upto n that don't contain 3

# Returns count of numbers which are in range from 1 to n


# and don't contain 3 as a digit
def count(n):
# Base Cases ( n is not negative)
if n < 3:
return n
elif n >= 3 and n < 10:
return n-1

# Calculate 10^(d-1) ( 10 raise to the power d-1 ) where d


# is number of digits in n. po will be 100 for n = 578

po = 1
while n/po > 9:
po = po * 10

# Find the MSD ( msd is 5 for 578 )


msd = n/po

if msd != 3:
# For 578, total will be 4*count(10^2 - 1) + 4 + ccount(78)
return count(msd) * count(po-1) + count(msd) + count(n%po)
else:
# For 35 total will be equal to count(29)
return count(msd * po - 1)

# Driver Program
n = 578
print count(n)

13.Magic Square
def generateSquare(n):
 
    # 2-D array with all
    # slots set to 0
    magicSquare = [[0 for x in range(n)]
                   for y in range(n)]
 
    # initialize position of 1
    i = n / 2
    j = n - 1
 
    # Fill the magic square
    # by placing values
    num = 1
    while num <= (n * n):
        if i == -1 and j == n:  # 3rd condition
            j = n - 2
            i = 0
        else:
 
            # next number goes out of
            # right side of square
            if j == n:
                j = 0
 
            # next number goes
            # out of upper side
            if i < 0:
                i = n - 1
 
        if magicSquare[int(i)][int(j)]:  # 2nd condition
            j = j - 2
            i = i + 1
            continue
        else:
            magicSquare[int(i)][int(j)] = num
            num = num + 1
 
        j = j + 1
        i = i - 1  # 1st condition
 
    # Printing magic square
    print("Magic Squre for n =", n)
    print("Sum of each row or column",
          n * (n * n + 1) / 2, "\n")
 
    for i in range(0, n):
        for j in range(0, n):
            print('%2d ' % (magicSquare[i][j]),
                  end='')
 
            # To display output
            # in matrix form
            if j == n - 1:
                print()

14.Sieve of Eratosthenes
def SieveOfEratosthenes(n):
 
    # Create a boolean array
    # "prime[0..n]" and initialize
    #  all entries it as true.
    # A value in prime[i] will
    # finally be false if i is
    # Not a prime, else true.
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
 
        # If prime[p] is not
        # changed, then it is a prime
        if (prime[p] == True):
 
            # Update all multiples of p
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
 
    # Print all prime numbers
    for p in range(2, n+1):
        if prime[p]:
            print p,

15.Number which has the maximum


number of distinct prime factors in the
range M to N

def maximumNumberDistinctPrimeRange(m, n):


 
    # array to store the number
    # of distinct primes
    factorCount = [0] * (n + 1)
 
    # true if index 'i' is a prime
    prime = [False] * (n + 1)
 
    # initializing the number of
    # factors to 0 and
    for i in range(n + 1) :
        factorCount[i] = 0
        prime[i] = True # Used in Sieve
 
    for i in range(2, n + 1) :
 
        # condition works only when 'i'
        # is prime, hence for factors of
        # all prime number, the prime
        # status is changed to false
        if (prime[i] == True) :
 
            # Number is prime
            factorCount[i] = 1
 
            # number of factor of a
            # prime number is 1
            for j in range(i * 2, n + 1, i) :
 
                # incrementing factorCount all
                # the factors of i
                factorCount[j] += 1
 
                # and changing prime status
                # to false
                prime[j] = False
 
    # Initialize the max and num
    max = factorCount[m]
    num = m
 
    # Gets the maximum number
    for i in range(m, n + 1) :
 
        # Gets the maximum number
        if (factorCount[i] > max) :
            max = factorCount[i]
            num = i
    return num

16.Find day of the week for a given date


def dayofweek(d, m, y):
    t = [ 0, 3, 2, 5, 0, 3,
          5, 1, 4, 6, 2, 4 ]
    y -= m < 3
    return (( y + int(y / 4) - int(y / 100)
             + int(y / 400) + t[m - 1] + d) % 7)

17.DFA based division


def isMultiple3(c, size):
state = '0'
for i in range(size):
digit = c[i]
if state == '0':

if (digit == '1'):
state = '1'
elif state == '1':
if (digit == '0'):
state = '2'
else:
state = '0'
elif state == '2':
if (digit == '0'):
state = '1'
if (state == '0'):
return True
return False
if __name__=="__main__":
size = 5
c = [ '1', '0', '1', '0', '1']
if (isMultiple3(c, size)):
print("YES")
else:
print("NO")

18.Generate integer from 1 to 7 with equal


probability
if name == '__main__':
     
    for first in range(1, 6):
        for second in range(1, 6):
                print(5 * first + second - 5)

19.Given a number, find the next smallest


palindrome
def generateNextPalindromeUtil (num, n) :
 
    # find the index of mid digit
    mid = int(n/2 )
 
    # A bool variable to check if copy of left
    # side to right is sufficient or not
    leftsmaller = False
 
    # end of left side is always 'mid -1'
    i = mid - 1
 
    # Beginning of right side depends
    # if n is odd or even
    j = mid + 1 if (n % 2) else mid
 
    # Initially, ignore the middle same digits
    while (i >= 0 and num[i] == num[j]) :
        i-=1
        j+=1
 
    # Find if the middle digit(s) need to be
    # incremented or not (or copying left
    # side is not sufficient)
    if ( i < 0 or num[i] < num[j]):
        leftsmaller = True
 
    # Copy the mirror of left to tight
    while (i >= 0) :
     
        num[j] = num[i]
        j+=1
        i-=1
     
 
    # Handle the case where middle
    # digit(s) must be incremented.
    # This part of code is for CASE 1 and CASE 2.2
    if (leftsmaller == True) :
     
        carry = 1
        i = mid - 1
 
        # If there are odd digits, then increment
        # the middle digit and store the carry
        if (n%2 == 1) :
         
            num[mid] += carry
            carry = int(num[mid] / 10 )
            num[mid] %= 10
            j = mid + 1
         
        else:
            j = mid
 
        # Add 1 to the rightmost digit of the
        # left side, propagate the carry
        # towards MSB digit and simultaneously
        # copying mirror of the left side
        # to the right side.
        while (i >= 0) :
         
            num[i] += carry
            carry = int(num[i] / 10)
            num[i] %= 10
            num[j] = num[i] # copy mirror to right
            j+=1
            i-=1
         
# The function that prints next
# palindrome of a given number num[]
# with n digits.
def generateNextPalindrome(num, n ) :
 
    print("\nNext palindrome is:")
 
    # Input type 1: All the digits are 9, simply o/p 1
    # followed by n-1 0's followed by 1.
    if( AreAll9s( num, n ) == True) :
     
        print( "1")
        for i in range(1, n):
            print( "0" )
        print( "1")
     
 
    # Input type 2 and 3
    else:
     
        generateNextPalindromeUtil ( num, n )
 
        # print the result
        printArray (num, n)
     
# A utility function to check if num has all 9s
def AreAll9s(num, n ):
    for i in range(1, n):
        if( num[i] != 9 ) :
            return 0
    return 1
 
 
# Utility that prints out an array on a line
def printArray(arr, n):
 
    for i in range(0, n):
        print(int(arr[i]),end=" ")
    print()

20.Make a fair coin from a biased coin


def foo():
   
    # Some code here
    pass
 
# Returns both 0 and 1
# with 50% probability
def my_fun():
   
    val1, val2 = foo(), foo()
     
    if val1 ^ val2:
       
        # Will reach here with
        # (0.24 + 0.24) probability
        return val1
       
    # Will reach here with
    # (1 - 0.24 - 0.24) probability
    return my_fun()
 
# Driver Code
if __name__ == '__main__':
    print(my_fun())

21.Check divisibility by 7
def isDivisibleBy7(num) :
     
    # If number is negative, make it positive
    if num < 0 :
        return isDivisibleBy7( -num )
 
    # Base cases
    if( num == 0 or num == 7 ) :
        return True
     
    if( num < 10 ) :
        return False
         
    # Recur for ( num / 10 - 2 * num % 10 )
    return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) )
     
# Driver program
num = 616
if(isDivisibleBy7(num)) :
    print "Divisible"
else :
    print "Not Divisible"

22.Find the largest multiple of 3 | Set 1


(Using Queue)
# Time: O(n)
# Space: O(1)

import collections

class Solution(object):
def largestMultipleOfThree(self, digits):
"""
:type digits: List[int]
:rtype: str
"""
lookup = {0: [],
1: [(1,), (4,), (7,), (2, 2), (5, 2), (5, 5), (8, 2), (8, 5), (8, 8)],
2: [(2,), (5,), (8,), (1, 1), (4, 1), (4, 4), (7, 1), (7, 4), (7, 7)]}
count = collections.Counter(digits)
for deletes in lookup[sum(digits)%3]:
delete_count = collections.Counter(deletes)
if all(count[k] >= v for k, v in delete_count.iteritems()):
for k, v in delete_count.iteritems():
count[k] -= v
break
result = "".join(str(d)*count[d] for d in reversed(xrange(10)))
return "0" if result and result[0] == '0' else result

# Time: O(n)
# Space: O(1)
class Solution2(object):
def largestMultipleOfThree(self, digits):
"""
:type digits: List[int]
:rtype: str
"""
def candidates_gen(r):
if r == 0:
return
for i in xrange(10):
yield [i]
for i in xrange(10):
for j in xrange(i+1):
yield [i, j]

count, r = collections.Counter(digits), sum(digits)%3


for deletes in candidates_gen(r):
delete_count = collections.Counter(deletes)
if sum(deletes)%3 == r and \
all(count[k] >= v for k, v in delete_count.iteritems()):
for k, v in delete_count.iteritems():
count[k] -= v
break
result = "".join(str(d)*count[d] for d in reversed(xrange(10)))
return "0" if result and result[0] == '0' else result

23.Lexicographic rank of a string


def fact(n) :
    f = 1
    while n >= 1 :
        f = f * n
        n = n - 1
    return f
     
# A utility function to count smaller
# characters on right of arr[low]
def findSmallerInRight(st, low, high) :
     
    countRight = 0
    i = low + 1
    while i <= high :
        if st[i] < st[low] :
            countRight = countRight + 1
        i = i + 1
  
    return countRight
     
# A function to find rank of a string
# in all permutations of characters
def findRank (st) :
    ln = len(st)
    mul = fact(ln)
    rank = 1
    i = 0
  
    while i < ln :
         
        mul = mul / (ln - i)
         
        # count number of chars smaller
        # than str[i] fron str[i + 1] to
        # str[len-1]
        countRight = findSmallerInRight(st, i, ln-1)
  
        rank = rank + countRight * mul
        i = i + 1
         
    return rank

24.Print all permutations in sorted


(lexicographic) order
def fact(n) :
f=1
while n >= 1 :
f=f*n
n=n-1
return f
def findSmallerInRight(st, low, high) :
countRight = 0
i = low + 1
while i <= high :
if st[i] < st[low] :
countRight = countRight + 1
i=i+1
return countRight
def findRank (st) :
ln = len(st)
mul = fact(ln)
rank = 1
i=0
while i < ln :
mul = mul / (ln - i)
countRight = findSmallerInRight(st, i, ln-1)
rank = rank + countRight * mul
i=i+1

return rank
st = "string"
print (findRank(st))

25.Shuffle a given array


import random
def randomize (arr, n):
for i in range(n-1,0,-1):
j = random.randint(0,i+1)
arr[i],arr[j] = arr[j],arr[i]

return arr
arr = [1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
print(randomize(arr, n))

26.Space and time efficient Binomial


Coefficient
def binomialCoefficient(n, k):
    # since C(n, k) = C(n, n - k)
    if(k > n - k):
        k = n - k
    # initialize result
    res = 1
    # Calculate value of
    # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]
    for i in range(k):
        res = res * (n - i)
        res = res / (i + 1)
    return res
 
# Driver program to test above function
n = 8
k = 2
res = binomialCoefficient(n, k)
print("Value of C(% d, % d) is % d" %(n, k, res))
27.Reservoir Sampling
import random
# A utility function
# to print an array
def printArray(stream,n):
    for i in range(n):
        print(stream[i],end=" ");
    print();
 
# A function to randomly select
# k items from stream[0..n-1].
def selectKItems(stream, n, k):
        i=0;
        # index for elements
        # in stream[]
         
        # reservoir[] is the output
        # array. Initialize it with
        # first k elements from stream[]
        reservoir = [0]*k;
        for i in range(k):
            reservoir[i] = stream[i];
         
        # Iterate from the (k+1)th
        # element to nth element
        while(i < n):
            # Pick a random index
            # from 0 to i.
            j = random.randrange(i+1);
             
            # If the randomly picked
            # index is smaller than k,
            # then replace the element
            # present at the index
            # with new element from stream
            if(j < k):
                reservoir[j] = stream[i];
            i+=1;
         
        print("Following are k randomly selected items");
        printArray(reservoir, k);

28.Pascal’s Triangle
n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j])
if(n!=0):
a[i].append(1)
for i in range(n):
print(" "*(n-i),end=" ",sep=" ")
for j in range(0,i+1):
print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
print()

29.Select a random number from stream,


with O(1) space
import random
  
# A function to randomly select a item
# from stream[0], stream[1], .. stream[i-1]
def selectRandom(x):
      
    # The resultant random number
    res = 0;
      
    # Count of numbers visited 
    # so far in stream
    count = 0;
  
    # increment count of numbers 
    # seen so far
    count += 1;
  
    # If this is the first element 
    # from stream, return it
    if (count == 1):
        res = x;
    else:
          
        # Generate a random number 
        # from 0 to count - 1
        i = random.randrange(count);
  
        # Replace the prev random number 
        # with new number with 1/count 
        # probability
        if (i == count - 1):
            res = x;
    return res;
import random
  
# A function to randomly select a item
# from stream[0], stream[1], .. stream[i-1]
def selectRandom(x):
      
    # The resultant random number
    res = 0;
      
    # Count of numbers visited 
    # so far in stream
    count = 0;
  
    # increment count of numbers 
    # seen so far
    count += 1;
  
    # If this is the first element 
    # from stream, return it
    if (count == 1):
        res = x;
    else:
          
        # Generate a random number 
        # from 0 to count - 1
        i = random.randrange(count);
  
        # Replace the prev random number 
        # with new number with 1/count 
        # probability
        if (i == count - 1):
            res = x;
    return res;

THE END

You might also like