[go: up one dir, main page]

0% found this document useful (0 votes)
58 views12 pages

DV With Python-1-5

This document contains questions and Python code examples related to data analysis and visualization. It includes programs to find the best test average, check if a number is a palindrome, calculate Fibonacci numbers, convert between binary and decimal and octal and hexadecimal, analyze characters in a string, compare string similarity, and create bar, scatter, and histogram plots using Matplotlib.

Uploaded by

Madhu
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)
58 views12 pages

DV With Python-1-5

This document contains questions and Python code examples related to data analysis and visualization. It includes programs to find the best test average, check if a number is a palindrome, calculate Fibonacci numbers, convert between binary and decimal and octal and hexadecimal, analyze characters in a string, compare string similarity, and create bar, scatter, and histogram plots using Matplotlib.

Uploaded by

Madhu
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/ 12

Sri Sairam College of Engineering

Q1.
a. Write a python program to find the best of two test average marks out of
three test’s marks accepted from the user.

Python Code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

m1 = int(input("Enter marks for test1 : "))


m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))

best_of_two = sorted([m1, m2, m3], reverse=True)[:2]


average_best_of_two = sum(best_of_two)/2

print("Average of best two test marks out of three test’s marks is",
average_best_of_two);

Output:

b) Develop a Python program to check whether a given number is palindrome or


not and also count the number of occurrences of each digit in the input number.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Sri Sairam College of Engineering

from collections import Counter

value = input("Enter a value : ")


if value == value[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

counted_dict = Counter(value)
for key in sorted(counted_dict.keys()):
print(f'{key} appears {counted_dict[key]} times');

"""
#Alternate way to count appearances
for i in range(10):
if value.count(str(i)) > 0:
print(f'{str(i)} appears {value.count(str(i))} times')
"""

Output : 1

Output2:

Q2. a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program


which accepts a value for N (where N >0) as input and pass this value to the
function. Display suitable error message if the condition for input value is not
followed.
Python Code:
#!/usr/bin/env python3
Sri Sairam College of Engineering

# -*- coding: utf-8 -*-

def fn(n):
if n <= 2:
return n - 1
else:
return fn(n-1) + fn(n-2)

try:
num = int(input("Enter a number : "))
if num > 0:
print(f' fn({num}) = {fn(num)}')
else:
print("Input should be greater than 0")
except ValueError:
print("Try with numeric value")

Ouput:

b) Develop a python program to convert binary to decimal, octal to hexadecimal


using functions.

Python Code
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

"""
def bin2Dec(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 2**i
Sri Sairam College of Engineering

i += 1

return dec

def oct2Hex(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 8**i
i += 1
list=[]
while dec != 0:
list.append(dec%16)
dec = dec // 16

nl=[]
for elem in list[::-1]:
if elem <= 9:
nl.append(str(elem))
else:
nl.append(chr(ord('A') + (elem -10)))
hex = "".join(nl)

return hex

base = 2
num1 = input("Enter a binary number : ")
# print(bin2Dec(num1))
print(int(num1, base))
"""

#A better implementation
def bin2Dec(val):
return int(val, 2)
Sri Sairam College of Engineering

def oct2Hex(val):
return int(val, 8)

try:
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
except ValueError:
print("Invalid literal in input with base 2")

try:
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
except ValueError:
print("Invalid literal in input with base 8")

Output:

Q3. Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters and lowercase letters.

Python Code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import string

sentence = input("Enter a sentence : ")

wordList = sentence.strip().split(" ")


print(f'This sentence has {len(wordList)} words', end='\n\n')

digit_count = uppercase_count = lowercase_count = 0


Sri Sairam College of Engineering

for character in sentence:


if character in string.digits:
digit_count += 1
elif character in string.ascii_uppercase:
uppercase_count += 1
elif character in string.ascii_lowercase:
lowercase_count += 1

print(f'This sentence has {digit_count} digits',


f' {uppercase_count} upper case letters',
f' {lowercase_count} lower case letters', sep='\n')

Output:

b) Write a Python program to find the string similarity between two given strings

Python Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

str1 = input("Enter String 1 \n").lower()


str2 = input("Enter String 2 \n").lower()

# if len(str2) < len(str1):


# short = len(str2)
# long = len(str1)
# else:
# short = len(str1)
# long = len(str2)

string_1_length = len(str1)
string_2_length = len(str2)
Sri Sairam College of Engineering

short_string_length, long_string_length = min(string_1_length, string_2_length),


max(string_1_length, string_2_length)

match_count = 0
for i in range(short_string_length):
if str1[i] == str2[i]:
match_count += 1

print("Similarity between two said strings:")


print(match_count/long_string_length)

"""
# An alternative solution to the same problem using Python libraries

from difflib import SequenceMatcher

str1 = input("Enter String 1 : ")


str2 = input("Enter String 2 : ")

sim = SequenceMatcher(None, str1, str2).ratio()

print("Similarity between strings \"" + str1 + "\" and \"" + str2 + "\" is : ",sim)

Output:

Q4. a) Write a Python program to Demonstrate how to Draw a Bar Plot using
Matplotlib.

Python Code:

import matplotlib.pyplot as plt


Sri Sairam College of Engineering

# Sample data for demonstration


categories = ['0-10', '10-20', '20-30', '30-40', '40-50']
values = [55, 48, 25, 68, 90]

# Create a bar plot


plt.bar(categories, values, color='skyblue')

# Add labels and title


plt.xlabel('Overs')
plt.ylabel('Runs')
plt.title('Bar Plot Showing Runs scored in an ODI Match')

# Display the plot


plt.show()

Output:

b) Write a Python program to Demonstrate how to Draw a Scatter Plot using


Matplotlib.

Python Code:

import matplotlib.pyplot as plt


Sri Sairam College of Engineering

import numpy as np

# BRICS nations data (hypothetical)


countries = ['Brazil', 'Russia', 'India', 'China', 'South Africa']
population = [213993437, 145912025, 1393409038, 1444216107, 61608912] #
Population in 2021
per_capita_income = [9600, 11600, 2300, 11000, 6500] # Per capita income in
USD

# Scale the population for circle size


circle_size = [pop / 1000000 for pop in population] # Scaling down for better
visualization

# Assign different colors based on index


colors = np.arange(len(countries))

# Create a scatter plot with varying circle sizes and colors


scatter = plt.scatter(population, per_capita_income, s=circle_size, c=colors,
cmap='viridis', alpha=0.7, label='BRICS Nations')

# Annotate each point with the country name


for i, country in enumerate(countries):
plt.annotate(country, (population[i], per_capita_income[i]), textcoords="offset
points", xytext=(0,5), ha='center')

# Add colorbar
plt.colorbar(scatter, label='Index')

# Add labels and title


plt.xlabel('Population')
plt.ylabel('Per Capita Income (USD)')
plt.title('Population vs Per Capita Income of BRICS Nations')

# Display the plot


plt.show()
Sri Sairam College of Engineering

Q5. a) Write a Python program to Demonstrate how to Draw a Histogram Plot


using Matplotlib.

Python Code:

import matplotlib.pyplot as plt


import numpy as np

# Generate random student scores (example data)


np.random.seed(42)
student_scores = np.random.normal(loc=70, scale=15, size=100)

# Create a histogram plot


plt.hist(student_scores, bins=20, color='skyblue', edgecolor='black')

# Add labels and title


plt.xlabel('Student Scores')
plt.ylabel('Frequency')
plt.title('Distribution of Student Scores')

# Display the plot


plt.show()
Sri Sairam College of Engineering

Output :

b) Write a Python program to Demonstrate how to Draw a Pie Chart using


Matplotlib.

Python Code:
import matplotlib.pyplot as plt

#Number of FIFA World Cup wins for different countries


countries = ['Brazil', 'Germany', 'Italy', 'Argentina', 'Uruguay', 'France', 'England',
'Spain']
wins = [5, 4, 4, 3, 2, 2, 1, 1] # Replace with actual data

# Colors for each country


colors = ['yellow', 'magenta', 'green', 'blue', 'lightblue', 'blue', 'red', 'cyan']

plt.pie(wins, labels=countries, autopct='%1.1f%%', colors=colors, startangle=90,


explode=[0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2], shadow=True)

# Add title
plt.title('FIFA World Cup Wins by Country')

# Display the plot


plt.axis('equal') # Equal aspect ratio ensures that the pie chart is circular.
plt.show()

Output:

You might also like