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

Python

Uploaded by

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

Python

Uploaded by

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

Python

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


Ans :

2 (i) Write a program to compute distance between two points taking input from the user.
Ans.

(ii) Write a program add.py that takes 2 numbers as command line arguments and prints
its sum.
Ans :
Python Code:
def add_numbers(a, b):
return a + b
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = add_numbers(num1, num2)
print("Sum:", result)
Copy
Input :
Enter the first number: 5
Enter the second number: 6
Copy
Output :
Sum: 11.0

3 (i) Write a Program for checking whether the given number is an even number or not.
Ans :
num = int (input (“Enter any number to test whether it is odd or even: “)

if (num % 2) == 0:

print (“The number is even”)

else:

print (“The provided number is odd”)

Output:

Enter any number to test whether it is odd or even:887


887 is odd.

(ii) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, ..., 1/10
Ans :

a=1
for b in range(2, 11):
print(f"{a}/{b} :", a/b)

Output
1/2 : 0.5
1/3 : 0.3333333333333333
1/4 : 0.25
1/5 : 0.2
1/6 : 0.16666666666666666
1/7 : 0.14285714285714285
1/8 : 0.125
1/9 : 0.1111111111111111
1/10 : 0.1
4 (i) Write a Program to demonstrate list and tuple in python.
Ans :
In [1]:
L1=[10,25.5,3+2j,"Hello"]
L1
Out[1]:
[10, 25.5, (3+2j), 'Hello']
In above list, each item is of different type. Further, each item is accessible by positional index
starting from 0. Hence L1[2] will return 25.5
In [2]:
L1[1]
Out[2]:
25.5
Tuple: Tuple looks similar to list. The only difference is that comma separated items of same or
different type are enclosed in parentheses. Individual items follow zero based index, as in list or
string.
In [3]:
T1=(10,25.5,3+2j,"Hello")
T1
Out[3]:
(10, 25.5, (3+2j), 'Hello')
In [4]:
T1[1]
Out[4]:
25.5

(ii) Write a program using a for loop that loops over a sequence.
Ans :

li = ["Geeks", "for", "Geeks"]

for i in li:
print(i)
print('-----')
for i in range(len(li)):
print(li[i])

Output
Geeks
for
Geeks
-----
Geeks
for
Geeks

(iii) Write a program using a while loop that asks the user for a number, and prints a
countdown
from that number to zero.
Ans :
looking_for_positive_number = True
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)

while int_reply > 0:


print(int_reply)
int_reply = int_reply - 1
looking_for_positive_number = False
This is what it returns (I used 5 as the positive number):
Enter positive number: 5
5
4
3
2
1
Ideally, it should return something like this (also used 5 here):
Enter positive number: 5
5
4
3
2
1
0

5 (i) Find the sum of all the primes below two million.
Ans :
last_number = int(input("\nPlease enter the last number up till which sum of prime number is
to be found:"))
print ("We will find the sum of prime numbers in python upto", last_number)
sum = 0
for number in range(2, Last_number + 1):
i=2
for i in range(2, number):
if (int(number % i) == 0):
i = number
break;
if i is not number:
sum = sum + number
print("\nThe sum of prime numbers in python from 1 to ", Last_number, " is :", sum)
Output:
Please enter the last number up till which sum of prime number is to be found: 60
We will find the sum of prime numbers in python upto 60
The sum of prime numbers in python from 1 to 60 is : 438

(ii) 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.
Ans :

def evenFibSum(limit) :
if (limit < 2) :
return 0

ef1 = 0
ef2 = 2
sm= ef1 + ef2

while (ef2 <= limit) :

ef3 = 4 * ef2 + ef1

if (ef3 > limit) :


break
ef1 = ef2
ef2 = ef3
sm = sm + ef2

return sm
limit = 400
print(evenFibSum(limit))

Output :

188
Time Complexity: O(n)
Auxiliary Space: O(1)

6 (i) Write a program to count the numbers of characters in the string and store them in a
dictionary data structure.
Ans :

test_str = "GeeksforGeeks"
all_freq = {}

for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
print("Count of all characters in GeeksforGeeks is :\n "
+ str(all_freq))

Output
Count of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}
(ii) Write a program to use split and join methods in the string and trace a birthday of a
person with a dictionary data structure.
Ans :

def split_string(string):

list_string = string.split(' ')

return list_string

def join_string(list_string):
string = '-'.join(list_string)

return string
if __name__ == '__main__':
string = 'Geeks for Geeks'
list_string = split_string(string)
print(list_string)
new_string = join_string(list_string)
print(new_string)

Output
['Geeks', 'for', 'Geeks']
Geeks-for-Geeks

7 (i) 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?
Ans :

def letterFrequency(fileName, letter):


file = open(fileName, 'r')

text = file.read()

return text.count(letter)

print(letterFrequency('gfg.txt', 'g'))

Output:

(ii) 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?
Ans :
import collections # Import the 'collections' module for Counter.
import pprint # Import 'pprint' for pretty printing.
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)

print(value)
Copy
Sample Output:
File Name: abc.txt
Counter({' ': 93,
'E': 64,
'N': 45,
'A': 42,
'T': 40,
'I': 36,
'O': 31,
'R': 29,
'H': 25,
'D': 19,
'M': 17,
'Y': 17,
'L': 15,
'F': 15,
'U': 14,
'C': 13,
'G': 13,
'S': 12,
',': 7,
'B': 6,
'W': 5,
'9': 5,
'.': 4,
'P': 4,
'1': 3,
'\n': 2,
'0': 2,
'3': 2,
':': 1,
'-': 1,
'K': 1,
'(': 1,
')': 1,
'V': 1})
8 (i) Write a program to print each line of a file in reverse order.
Ans :

f1 = open("output1.txt", "w")

with open("file.txt", "r") as myfile:


data = myfile.read()

data_1 = data[::-1]

f1.write(data_1)

f1.close()

Output:

(ii) Write a program to compute the number of characters, words and lines in a file.
Ans :

def counter(fname):

num_words = 0

num_lines = 0
num_charc = 0

num_spaces = 0
with open(fname, 'r') as f:
for line in f:

num_lines += 1

word = 'Y'
for letter in line:
if (letter != ' ' and word == 'Y'):
num_words += 1
word = 'N'
elif (letter == ' '):
num_spaces += 1
word = 'Y'
for i in letter:
if(i !=" " and i !="\n"):
num_charc += 1
print("Number of words in text file: ", num_words)
print("Number of lines in text file: ", num_lines)
print('Number of characters in text file: ', num_charc)
print('Number of spaces in text file: ', num_spaces)

# Driver Code:
if __name__ == '__main__':
fname = 'File1.txt'
try:
counter(fname)
except:
print('File not found')

Output:
Number of words in text file: 25
Number of lines in text file: 4
Number of characters in text file: 91
Number of spaces in text file: 21

9 (i) 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 on.
Ans :

from string import ascii_lowercase


def get_freq(test_str):
freqs = {char: 0 for char in ascii_lowercase}
for char in test_str:
freqs[char] += 1
return freqs

test_str1 = 'aabcdaa'
test_str2 = "abbaccd"
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
K=2
freqs_1 = get_freq(test_str1)
freqs_2 = get_freq(test_str2)
res = True
for char in ascii_lowercase:
if abs(freqs_1[char] - freqs_2[char]) > K:
res = False
break
print("Are strings similar ? : " + str(res))

Output:
The original string 1 is : aabcdaa
The original string 2 is : abbaccd
Are strings similar ? : True
(ii) Write function to compute gcd, lcm of two numbers. Each function shouldn't exceed
one line.
Ans :
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a,b):
return (a // gcd(a,b))* b
a = 15
b = 20
print('LCM of', a, 'and', b, 'is', lcm(a, b))

Output
LCM of 15 and 20 is 60

10 (i) Write a program to implement Merge sort.


Ans :

def merge(arr, l, m, r):


n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0, n1):
L[i] = arr[l + i]

for j in range(0, n2):


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

i=0 # Initial index of first subarray


j=0 # Initial index of second subarray
k=l # Initial index of merged subarray

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1

def mergeSort(arr, l, r):


if l < r:

m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")

mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")

Output
Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

(ii) Write a program to implement Selection sort, Insertion sort.


Ans :

def selectionSort(array, size):

for ind in range(size):


min_index = ind

for j in range(ind + 1, size):


if array[j] < array[min_index]:
min_index = j
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2, 45, 0, 11, -9,88,-97,-202,747]


size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)
Output
The array after sorting in Ascending Order by selection sort is:
[-202, -97, -9, -2, 0, 11, 45, 88, 747]
Experiments
1. Program to display the addition, subtraction, multiplication and division of two
number using console application.
2. Program to display the first 10 natural numbers and their sum using console
application.
3. Program to display the addition using the windows application.
4. Write a program to convert input string from lower to upper and upper to lower case.
5. Write a program to simple calculator using windows application.
6. Write a program working with Page using ASP.Net.
7. Write a program working with forms using ASP.NET.
8. Write a program to connectivity with Oracle database.00
9. Write a program to access data source through ADO.NET. Galaxy A13
10. Write a program to manage the session.

You might also like