Python PCA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

1.Write a program to demonstrate basic data type in python.

Source Code:

a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

Output:-
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
2. Write a program to compute distance between two points taking
input from the user.

Source Code:-

# distance between two points


import math

#Function to calculate distance

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

#Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) * 1.0)

# Drivers Code
print("%.6f"%distance(3, 4, 4, 3))

Output:-
1.414214
2.a) Write a program add.py that takes 2 numbers as command line
arguments and prints its sum.

Source Code:-
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output:-
Enter first number: 34
Enter second number: 23
The sum of 34 and 23 is 57.0
3. Write a Program for checking whether the given number is an
even number or not.

Source Code:-

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("the number is even")
else:
print("the number is odd")

Output:-
Enter a number: 34
the number is even
3.a) Using a for loop, write a program that prints out the decimal
equivalents of ½+1/3+1/4+. . . , 1/10

Source Code:-
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(2,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))

Output:-
Enter the number of terms: 6
The sum of series is 0.5
The sum of series is 0.83
The sum of series is 1.08
The sum of series is 1.28
The sum of series is 1.45
4. Write a Program to demonstrate list and tuple in python.

Source Code:-
L =[1,"a","string",1+2]
print(L)
L.append(6)
print(L)
L.pop()
print(L)
print(L[1])

Output:-
[1, 'a', 'string', 3]
[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3]
a
tup = (1, "a", "string", 1+2)
print(tup)
print(tup[1])

Output:-
(1, 'a', 'string', 3)
a
4.a) Write a program using a for loop that loops over a sequence.

Source Code:-
str="I am a python developer"
for i in str:
print(i)

Output:-
I

a
m

p
y
t
h
o
n

d
e
v
e
l
o
p
e
r
4.b) Write a program using a while loop that asks the user for a
number, and prints a countdown from that number to zero.
Source Code:-
n = int(input("Enter A Number: "));
while n >=0:
print (n);
n = n - 1;

Output:-
Enter A Number: 3
3
2
1
0
5. Find the sum of all the primes below two million.

Source Code:-
def eratosthenes2(n):
##Declare a set an unordered collection of unique elements
multiples=set()

##Iterate through [2,2000000]


for i in range(2,n+1):

##If i has not been eliminated already


if i not in multiples:

##Yay prime!
yield i

##Add multiples of the prime in the range to the 'invalid' set


multiples.update(range(i*i,n+1,i))
iter=0
ml=list(eratosthenes2(2000000))
for x in ml:
iter=int(x)+iter
print(iter)

Output:-
142913828922
5.a) By considering the terms in the Fibonacci sequence whose
values do not exceed four million, WAP to find the sum of the even-
valued terms.

Source Code:-
prev,cur = 0,1
total = 0
while True:
prev,cur = cur,prev + cur
if cur >= 4000000:
break
if cur % 2 == 0:
total += cur
print(total)

Output:-
2
10
44
188
798
3382
14328
60696
257114
1089154
4613732
6. Write a program to count the numbers of characters in the string
and store them in a dictionary data structure.

Source Code:-

str=input("Enter a String: ")


dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)

#OR
str=input("Enter a String: ")
dict = {}
for i in str:
dict[i] = str.count(i)
print (dict)
#OR
str=input("Enter a String: ")
dist={}
L=len(str);
d={str:L};
print(d)

Output:-
Enter a String: 3
{'3': 1}
Enter a String: 4
{'4': 1}
Enter a String: 6
{'6': 1}
6.a) Write a program to use split and join methods in the string and
trace a birthday of a person with a dictionary data structure.

Source Code:-
pen='+'
pin=['H','E','L','L','O']
print("Joining")
print(pen.join(pin))
c=pen.join(pin)
print("Splitting")
print(c.split('+'))
people={'Netaji':{'birthday':'Aug 15'},'Manaswi':{'birthday':'Mar
21'},'Chandrika':{'birthday':'July 7'}}
labels={'birthday':'birth date'}

name=input("Name: ")
request=input('birthday(b)?')
if request=='b':
key='birthday'
if name in people:
print("%s's %s is %s." % (name,labels[key], people[name][key]))
Output:-
Joining
H+E+L+L+O
Splitting
['H', 'E', 'L', 'L', 'O']
Name: Manaswi
birthday(b)?b
Manaswi's birth date is Mar 21.
7. Write a program to count frequency of characters in a given file.
Can you use character frequency to tell whether the given file is a
Python program file, C program file or a text file?

Source Code:-
import os
count =0
line=1

file=open('/Users/smritisarkar/Desktop/python-test/random.py')
for line in file:

for l in range(0,len(line)):

count+=1;
print("count:",count)

filename,file_extension=os.path.splitext('/Users/smritisarkar/Desktop/
python-test/random.py');
print("file_extension==",file_extension);

if(file_extension=='.py'):

print("its python program file");

elif(file_extension==".txt"):

print("its a txt file");

elif(file_extension=='.c'):
print("its a c program file")
Output:-
count: 12
file_extension== .py
its python program file
9. Write a function nearly equal to test whether two strings are
nearly equal. Two strings a and b are nearly equal when a can be
generated by a single mutation.

Source Code:-

from difflib import SequenceMatcher


def Nearly_Equal(a,b):
return SequenceMatcher(None,a,b).ratio();
a="khit"
b="khitc"
c=Nearly_Equal(a,b)
if(c*100>80):
print("Both Strings are similar")
print("a is mutation on b")
else:
print("Both Strings are Different")

Output:-
Both Strings are similar
a is mutation on b
9.a) Write function to compute gcd, lcm of two numbers. Each
function shouldn’t exceed one line.

Source Code:-

import math
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2 value:"))
gcd = math.gcd(n1, n2)
print("GCD value is:",gcd)
def lcm(n,m):
return n * m / gcd
print("LCM value is:",int(lcm(n1,n2)))

Output:-
Enter n1 value:24
Enter n2 value:36
GCD value is: 12
LCM value is: 72

You might also like