Python
Python
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:
else:
Output:
(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 :
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)
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
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):
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 :
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")
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 :
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
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