0% found this document useful (0 votes)
198 views11 pages

Optional Assignment 1

The document contains code snippets and explanations for 9 questions related to programming in Python. Some key points: 1) It includes functions to find the multiplication table of a number, twin prime numbers less than 1000, prime factors of a number, and implementations of permutation and combination formulae. 2) Other functions calculate the binary representation of a decimal number, the sum of the cubes of the digits of a number, check if a number is an Armstrong number, and find the list of Armstrong numbers in a range. 3) Further functions defined are for finding the multiplicative digital root and multiplicative persistence of a number, and to return the product of the digits of a number. 4) The document

Uploaded by

Rahul Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views11 pages

Optional Assignment 1

The document contains code snippets and explanations for 9 questions related to programming in Python. Some key points: 1) It includes functions to find the multiplication table of a number, twin prime numbers less than 1000, prime factors of a number, and implementations of permutation and combination formulae. 2) Other functions calculate the binary representation of a decimal number, the sum of the cubes of the digits of a number, check if a number is an Armstrong number, and find the list of Armstrong numbers in a range. 3) Further functions defined are for finding the multiplicative digital root and multiplicative persistence of a number, and to return the product of the digits of a number. 4) The document

Uploaded by

Rahul Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

OptionalAssignment1

October 8, 2018

1 Optional Assignment - 1
1.0.1 Q1- Write aprogram that Inputs a number and prints the multiplication table of that
number
In [1]: # Keyboard input for numbers
num = input("Input intger number for multiplication - ")
#try to catch error
try:
num=float(num)
except:
print("Please enter integer number")

#printing multiplication tabel


for i in range(1,11,1):
mul= num*i
print(num," X ", i, "=\t",mul)

Input intger number for multiplication - 8


8.0 X 1 = 8.0
8.0 X 2 = 16.0
8.0 X 3 = 24.0
8.0 X 4 = 32.0
8.0 X 5 = 40.0
8.0 X 6 = 48.0
8.0 X 7 = 56.0
8.0 X 8 = 64.0
8.0 X 9 = 72.0
8.0 X 10 = 80.0

1
1.0.2 Q2. Write a program to find out twin prime less than 1000.
1.0.3 reference -
1.0.4 1. https://www.geeksforgeeks.org/twin-prime-numbers-between-1-and-n/
1.0.5 2. https://www.geeksforgeeks.org/sieve-of-eratosthenes/
1.0.6 3. https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
1.0.7 4. https://www.programiz.com/python-programming/examples/prime-number-intervals
1.0.8 Algorithm
Input: an integer n > 1.
Let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true.
for i = 2, 3, 4, ..., not exceeding n: if A[i] is true: for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
A[j] := false.
Output: all i such that A[i] is true.

In [2]: import numpy as np


import math
#array of natural numbers between 3 and 1000 because 2 is even prime
prime=[]
div = math.floor(np.sqrt(1000))+1
# intialize while loop
#starting condition
for i in range(3,1001):
# print (i)

for j in range(2,i):
if (i%j)==0:
break
else:
# print(i)
prime.append(i)

twin_prime = []
#add -1 for IndexError: list index out of range
for p in range(len(prime)-1):
#print(prime[p+1]-prime[p])
if (prime[p+1]-prime[p]) == 2:
tp=(prime[p],prime[p+1])
#print(tp)
twin_prime.append(tp)

print(twin_prime)

[(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73), (101, 103), (107, 1

2
1.0.9 Q3. Write a program to find out the prime factors of a number.
In [3]: """
Input input number
"""
import math

num = input("Input intger number to find prime factors - ")


#try to catch error
try:
num=int(num)
except:
print("Please enter integer number")

multiple= int(math.sqrt(num)+1)

print("prime factor of ", num ," are :")


for i in range(2,num):
while num % i ==0:
print(i)
num=num/i

Input intger number to find prime factors - 68


prime factor of 68 are :
2
2
17

1.0.10 Q4. Write a programe to implement fomulae of permutation and combination


In [4]: """
Permuation = n!/(n-r)!
Combination = n!/(r!*(n-r)!)
given n>r

"""
n = input("Input number of objects 'n' -")
r = input("Input no. obj. 'n' taken times 'r' =")
try:
r=int(r)
# print(r)
n=int(n)
# print(n)
except:
print("Please enter integer number")

#FACTORIALS

3
#duplicate value n since vale of n changes during while iterartion
nf=n

n_factorial=1
if nf==0 or nf==1:
n_factorial=1
else:
while nf>0:
n_factorial= n_factorial*nf
# print(n_factorial)
nf-=1
#(n-r)!
# print("n_factorial",n_factorial)
# print(n)

nr= n-r

# print(nr)

nr_factorial=1
if nr==0 or nr==1:
n_factorial=1
else:
while nr>0:
nr_factorial= nr_factorial*nr
# print(nr_factorial)
nr-=1
# print(nr_factorial)
# while nr>0

r_factorial=1
if r==0 or r==1:
r_factorial=1
else:
while r>0:
r_factorial= r_factorial*r
# print(r_factorial)
r-=1
# print(r_factorial)

# premutation
print("\n")

print("Permutation = ",n_factorial/nr_factorial)
print("\n")
print("combination =",n_factorial/(nr_factorial*r_factorial))

4
Input number of objects 'n' -5
Input no. obj. 'n' taken times 'r' =2

Permutation = 20.0

combination = 10.0

1.0.11 Q5. Convert decimal to binary number


In [5]: try:
n = int(input("Input number of objects 'n' -"))
except:
print("input Integer" )

l=[]
if n==0 or n==1:
print("Binary of {} is {}".format(n,n))
else:
num=n
while num>0:
b=num%2
l.append(b)
# print(b)
num=num//2
(l.reverse())
print("Binary of {} is {}".format(n,l))

Input number of objects 'n' -8


Binary of 8 is [1, 0, 0, 0]

1.0.12 Q6. write a function cubesum()


Note :- - In recreational number theory, a narcissistic number(also known as a pluperfect dig-
ital invariant (PPDI),[3] an "Armstrong number" (after Michael F. Armstrong)or a plus perfect
number)[6] is a number that is the sum of its own digits each raised to the power of the number
of digits. This definition depends on the base b of the number system used, e.g., b = 10 for the
decimal system or b = 2 for the binary system.

Ref:- https://en.wikipedia.org/wiki/Narcissistic_number

In [9]: ################### Q6 -a cubesum()


def cubesum(n):
"""

5
Input integer

output sum of cube of individual number


"""
n=str(n)
intial=0
if str.isdigit(n):
for i in n:
i=int(i)
intial += i**3
return intial

else:
return print("input must be integer")

################### Q6 - b ArmstrongNumber()

def ArmstrongNumber(n):
'''
Input - Intgers for which Armstrong number is to be found
Output - Armstrong Number
that is, number is the sum of its own digits each raised to the power of the number
'''
n=str(n)
power=len(n)
# print(power)
intial=0
if str.isdigit(n):
for i in n:
# print(i)
i=int(i)
intial += i**power
# print(intial)
return intial

else:
return print("input must be integer")

################### Q6 - c ArmstrongNumber()

def isArmstrong(n):
"""
Check Wheather number is armstrong number or not
"""
n=str(n)
if str.isdigit(n):

6
sumn = ArmstrongNumber(n)
if int(n)==sumn:
return True
else:
return False
else:
return print("input must be integer")

###### Q6-D printing Armstrong number

def ArmstrongNumberList(LowerLimit,UpperLimit):
'''
Function return the list of armstrong number in range(lower,upper)
'''
Armlist=[]

for i in range(LowerLimit,UpperLimit+1):
# print(i)
# a = ArmstrongNumber(i)
# print(i,'\t',a)
if isArmstrong(i):
Armlist.append(i)
else:
continue
return Armlist
print("Cube sum of 83 is",cubesum(83),'\n')
print('Armstrong Number list',ArmstrongNumberList(0,10000))

Cube sum of 83 is 539

Armstrong Number list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]

1.0.13 Q7. write a function prodDigits() that input a number and returns products of digit of
that number
In [10]: def prodDigits(n):
'''
Function returns the product of digits of input numbers
'''
n=str(n)
intial=1
if str.isdigit(n):
if len(n)==1:
return int(n)

7
else:
for i in n:
# print(i)
i=int(i)
intial *= i
# print(intial)
return intial

else:
return print("input must be integers")

In [12]: prodDigits(669)

Out[12]: 324

1.0.14 Q8. write a function MDR() and MPersistence()


In [15]: def MDR(n):
'''
Function returns Multiplicative Digital Root of given number
'''
length=len(str(n))
while length>1:
n=prodDigits(n)
length=len(str(n))
return n

def MPersistence(n):
'''
Function returns Multiplicative Persistance of given number
'''
length=len(str(n))
count=0
while length>1:
n=prodDigits(n)
length=len(str(n))
count+=1
return count

print('MDR and Mpersistance for 86 are {} and {} repectively'.format(MDR(86),MPersisten


print('\n')
print('MDR and Mpersistance for 341 are {} and {} repectively'.format(MDR(341),MPersist

MDR and Mpersistance for 86 are 6 and 3 repectively

MDR and Mpersistance for 341 are 2 and 2 repectively

8
1.0.15 Q9. write a function sumPdivisor()
In [17]: def sumPdivisor(n):
'''
Function returns sum of proper divisors of given numbers
'''
n=str(n)
if str.isdigit(n):
result=0
for i in range(1,int(n)):
if (int(n)%i)==0:
# print(i)
# print('\n')
result+=i
# print(result)
return result

else:
return print("input must be integer")
print('Proper divisor of 36 is: ',sumPdivisor(36))

Proper divisor of 36 is: 55

1.0.16 Q10. Write a program to print all the perfect number in given range
In [19]: #
try:
lower=int(input("Input lower range"))
upper=int(input("Input Upper range"))
except:
print('input must be integer number')

perfectNumber=[]
for i in range(lower,upper+1):
# a=sumPdivisor(i)
if i==sumPdivisor(i):
perfectNumber.append(i)
else:
continue
print(perfectNumber)

Input lower range1


Input Upper range500
[6, 28, 496]

9
1.0.17 Q11. write function to print amicable numbers pair
In [20]: def amicable_pair(lower, upper):
result = []
for x in range(lower,upper+1):
y = sumPdivisor(x)
if sumPdivisor(y) == x and x != y:
result.append(tuple(sorted((x,y))))
return set(result)

amicable_pair(200,1000)

Out[20]: {(220, 284)}

1.0.18 Q12. Write a program which can filter odd numbers in a list using filter function
In [21]: def oddNumber(num):
if num%2!=0:
return num
#for Q14
def evenNumber(num):
if num%2==0:
return num

number_list=range(1,100)
print(number_list,'\n')
odd_number=list(filter(oddNumber,number_list))
print(odd_number)

range(1, 100)

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49,

1.0.19 Q13.Write a program which map to make a list whose elements are cube of elements in
givven list
In [22]: def cubeOfNumber(num):
return num**3

lst=range(1,11)

cube=list(map(cubeOfNumber,lst))
print(cube)

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

10
1.0.20 Q14 Write a program which can map() and filter to make list whose elements are cube
of even number in a given list
In [23]: lst=range(1,11)

cubeEven=list(map(cubeOfNumber,filter(evenNumber,lst)))
print(cubeEven)

[8, 64, 216, 512, 1000]

11

You might also like