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

python output

The document contains a series of programming experiments that demonstrate various algorithms and functions in Python. Key tasks include calculating the sum of primes below two million, summing even Fibonacci numbers, counting character frequencies, and implementing sorting algorithms like merge sort, selection sort, and insertion sort. Additionally, it covers string manipulation, file handling, and basic mathematical operations like GCD and LCM.

Uploaded by

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

python output

The document contains a series of programming experiments that demonstrate various algorithms and functions in Python. Key tasks include calculating the sum of primes below two million, summing even Fibonacci numbers, counting character frequencies, and implementing sorting algorithms like merge sort, selection sort, and insertion sort. Additionally, it covers string manipulation, file handling, and basic mathematical operations like GCD and LCM.

Uploaded by

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

Experimet – 5

Ques : Find the sum of all the primes below two million.

Ans : def sum_of_primes_below(limit):

sieve = [True] * limit

sieve[0] = sieve[1] = False

for i in range(2, int(limit ** 0.5) + 1):

if sieve[i]:

for j in range(i*i, limit, i):

sieve[j] = False

return sum(i for i, is_prime in enumerate(sieve) if is_prime)

prime_sum = sum_of_primes_below(2000000)

print("Sum of all primes below 2 million:", prime_sum)

Output :

Sum of all primes below 2 million: 142913828922

Ques : 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 sum_even_fibonacci(limit):

a, b = 1, 2

total = 0

while a <= limit:


if a % 2 == 0:

total += a

a, b = b, a + b

return total

even_fib_sum = sum_even_fibonacci(4000000)

print("Sum of even Fibonacci numbers below 4 million:", even_fib_sum)

Output :
Sum of even Fibonacci numbers below 4 million: 4613732
EXPERIMENT -6

Ques : Write a program to count the numbers of characters in the string and store them in a
dictionary data structure

Ans: def count_characters(input_string):

char_count = {}

for char in input_string:

if char in char_count:

char_count[char] += 1

else:

char_count[char] = 1

return char_count

user_input = input("Enter a string: ")

result = count_characters(user_input)

print("Character frequency dictionary:")

print(result)

OUTPUT :

Enter a string: hello

Character frequency dictionary:

{'h': 1, 'e': 1, 'l': 2, 'o': 1}


Ques: 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 :

birthdays = {

"Alice": "12/05/1995",

"Bob": "23/08/1992",

"Charlie": "10/01/2000"

full_name = input("Enter the full name (e.g., Alice Johnson): ")

name_parts = full_name.split()

first_name = name_parts[0]

if first_name in birthdays:

birthday = birthdays[first_name]

date_parts = birthday.split("/")

formatted_birthday = "-".join(date_parts)

print(f"{first_name}'s birthday is on {formatted_birthday}")

else:

print(f"Sorry, no birthday record found for {first_name}")

OUTPUT :

Enter the full name (e.g., Alice Johnson): Alice Johnson

Alice's birthday is on 12-05-1995


EXPERIMENT – 7

Ques :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 count_char_frequency(filename):
freq = {}
try:
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
for char in content:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq
except FileNotFoundError:
print("File not found.")
return {}
def guess_file_type(freq_dict):
python_keywords = ['def', 'import', 'self', ':', '#']
c_keywords = ['#include', 'int', 'main', '{', '}', ';']
all_chars = ''.join([k * v for k, v in freq_dict.items()])
score = {'Python': 0, 'C': 0, 'Text': 0}
for word in python_keywords:
if word in all_chars:
score['Python'] += 1
for word in c_keywords:
if word in all_chars:
score['C'] += 1
if score['Python'] == 0 and score['C'] == 0:
score['Text'] += 1
return max(score, key=score.get)
file_path = input("Enter file path: ")
freq_result = count_char_frequency(file_path)
if freq_result:
print("\nCharacter Frequency:")
for char, count in sorted(freq_result.items()):
print(f"'{char}': {count}")
file_type = guess_file_type(freq_result)
print(f"\n🔍 Based on character frequency, this looks like a **{file_type}** file.")

OUTPUT :Enter file path: sample.py


Character Frequency:
' ': 100
'\n': 20
'#': 3
'd': 10
Based on character frequency, this looks like a **Python** file.
EXPERIMENT 8

QUES: Write a program to print each line of a file in reverse order.


ANS : def print_lines_in_reverse(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()[::-1]) # strip() to remove \n, [::-1] to reverse
except FileNotFoundError:
print("File not found.")

# Example usage
file_path = input("Enter the file path: ")
print("\nReversed lines:")
print_lines_in_reverse(file_path)

OUTPUT : Enter the file path: sample.txt


Reversed lines:
!dlroW olleH
gnimmargorP nohtyP evol I

QUES : Write a program to compute the number of characters, words and lines in a file.

ANS : def count_file_stats(filename):


try:
with open(filename, 'r', encoding='utf-8') as file:
lines = file.readlines()
line_count = len(lines)
word_count = 0
char_count = 0
for line in lines:
word_count += len(line.split())
char_count += len(line)
print(f"\nFile Statistics:")
print(f"Lines: {line_count}")
print(f"Words: {word_count}")
print(f"Characters (including spaces/newlines): {char_count}")]
except FileNotFoundError:
print("File not found.")
file_path = input("Enter the file path again for stats: ")
count_file_stats(file_path)

OUTPUT :

Enter the file path again for stats: sample.txt


File Statistics:
Lines: 2
Words: 5
Characters (including spaces/newlines): 35
EXPERIMENT – 9
Ques : 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 : def nearly_equal(a, b):

len_a = len(a)

len_b = len(b)

if len_a == len_b:

diff = sum(1 for x, y in zip(a, b) if x != y)

return diff == 1

if abs(len_a - len_b) == 1:

if len_a > len_b:

a, b = b, a

i = j = diff = 0

while i < len(a) and j < len(b):

if a[i] != b[j]:

if diff:

return False

diff += 1

j += 1 # skip one character from longer string

else:

i += 1

j += 1

return True # one mismatch or end of loop

return False

OUTPUT : print(nearly_equal("cat", "cut"))

print(nearly_equal("cat", "cats"))

print(nearly_equal("cats", "cat"))

print(nearly_equal("cat", "dog"))

print(nearly_equal("cat", "cast"))

print(nearly_equal("cat", "cart"))
QUES : Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed
one line.

Ans :
from math import gcd

def lcm(a, b):


return a * b // gcd(a, b)

def main():

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

print(f"GCD of {num1} and {num2}: {gcd(num1, num2)}")


print(f"LCM of {num1} and {num2}: {lcm(num1, num2)}")

if __name__ == "__main__":
main()

Output :

Enter the first number: 12


Enter the second number: 16
GCD of 12 and 16: 4
LCM of 12 and 16: 48
EXPERIMENT – 10

QUES : Write a program to implement Merge sort.

Ans :def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

merge_sort(left_half)

merge_sort(right_half)

i=j=k=0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

def print_array(arr):

for elem in arr:


print(elem, end=" ")

print()

if __name__ == "__main__":

arr = [38, 27, 43, 3, 9, 82, 10]

print("Original array:")

print_array(arr)

merge_sort(arr)

print("\nSorted array:")

print_array(arr)

OUTPUT :

Original array:

38 27 43 3 9 82 10

Sorted array:

3 9 10 27 38 43 82
Ques : Write a program to implement Selection sort, Insertion sort.

Ans : 1. Selection Sort

def selection_sort(arr):

n = len(arr)

for i in range(n):

min_index = i

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

if arr[j] < arr[min_index]:

min_index = j

arr[i], arr[min_index] = arr[min_index], arr[i]

def print_array(arr):

for elem in arr:

print(elem, end=" ")

print()

if __name__ == "__main__":

arr = [64, 25, 12, 22, 11]

print("Original array:")

print_array(arr)

selection_sort(arr)

print("\nSorted array using Selection Sort:")

print_array(arr)

Output :

Original array:

64 25 12 22 11

Sorted array using Selection Sort:

11 12 22 25 64
2. INSERTION SORT

def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]

j=i-1

while j >= 0 and arr[j] > key:

arr[j + 1] = arr[j]

j -= 1

arr[j + 1] = key

def print_array(arr):

for elem in arr:

print(elem, end=" ")

print()

if __name__ == "__main__":

arr = [64, 34, 25, 12, 22, 11, 90]

print("Original array:")

print_array(arr)

insertion_sort(arr)

print("\nSorted array using Insertion Sort:")

print_array(arr)

OUTPUT :

Original array:

64 34 25 12 22 11 90

Sorted array using Insertion Sort:

11 12 22 25 34 64 90

You might also like