You are on page 1of 24

In [2]:  m1 = int(input("Enter marks for test1 : "))

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


m3 = int(input("Enter marks for test3 : "))
if m1 <= m2 and m1 <= m3:
avgMarks = (m2+m3)/2
elif m2 <= m1 and m2 <= m3:
avgMarks = (m1+m3)/2
elif m3 <= m1 and m2 <= m2:
avgMarks = (m1+m2)/2
print("Average of best two test marks out of three test’s marks is",avgMarks);

Enter marks for test1 : 20


Enter marks for test2 : 19
Enter marks for test3 : 20
Average of best two test marks out of three test’s marks is 20.0

In [3]:  val = int(input("Enter a value : "))


str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");

Enter a value : 12321


Palindrome
1 appears 2 times
2 appears 2 times
3 appears 1 times
In [4]:  def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
num = int(input("Enter a number : "))
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")

Enter a number : 2
fn(2) = 1
In [6]:  def binary_to_decimal(binary):
decimal = 0
power = 0
while binary != 0:
last_digit = binary % 10
decimal += last_digit * (2 ** power)
binary //= 10
power += 1
return decimal
def octal_to_hexadecimal(octal):
decimal = 0
power = 0
while octal != 0:
last_digit = octal % 10
decimal += last_digit * (8 ** power)
octal //= 10
power += 1
hexadecimal = ""
hex_digits = "0123456789ABCDEF"
while decimal != 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16
return hexadecimal
# Binary to Decimal conversion
binary_number = input("Enter a binary number: ")
decimal_number = binary_to_decimal(int(binary_number))
print("Decimal equivalent:", decimal_number)
# Octal to Hexadecimal conversion
octal_number = input("Enter an octal number: ")
hexadecimal_number = octal_to_hexadecimal(int(octal_number))
print("Hexadecimal equivalent:", hexadecimal_number)

Enter a binary number: 100010001


Decimal equivalent: 273
Enter an octal number: 675
Hexadecimal equivalent: 1BD
In [8]:  def analyze_sentence(sentence):
word_count = len(sentence.split())
digit_count = 0
uppercase_count = 0
lowercase_count = 0
for char in sentence:
if char.isdigit():
digit_count += 1
elif char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
return word_count, digit_count, uppercase_count, lowercase_count
user_sentence = input("Enter a sentence: ")
word_count, digit_count, uppercase_count, lowercase_count =analyze_sentence(user_sentence)
print("Number of words:", word_count)
print("Number of digits:", digit_count)
print("Number of uppercase letters:", uppercase_count)
print("Number of lowercase letters:", lowercase_count)

Enter a sentence: DHanush is a bad boy


Number of words: 5
Number of digits: 0
Number of uppercase letters: 2
Number of lowercase letters: 14
In [9]:  str1 = input("Enter String 1 \n")
str2 = input("Enter String 2 \n")
if len(str2) < len(str1):
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt/long)

Enter String 1
dhanush
Enter String 2
dhanas
Similarity between two said strings:
0.7142857142857143
In [10]:  import matplotlib.pyplot as plt
# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [25, 50, 75, 100]
# Create a bar plot
plt.bar(categories, values, color='blue')
# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')
# Show the plot
plt.show()

In [11]:  import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 15, 13, 17, 20, 22, 25, 30, 28, 35]
# Create a scatter plot
plt.scatter(x, y, color='blue', marker='o', label='Scatter Points', alpha=0.6)
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
# Show the plot
plt.legend()
plt.grid(True)
plt.show()

In [12]:  import matplotlib.pyplot as plt
# Sample data
data = [10, 15, 10, 20, 25, 30, 25, 30, 30, 35, 40, 45, 45, 45, 50]
# Create a histogram plot
plt.hist(data, bins=5, color='blue', edgecolor='black')
# Add labels and title
plt.xlabel('Value Bins')
plt.ylabel('Frequency')
plt.title('Histogram Plot Example')
# Show the plot
plt.grid(True)
plt.show()
In [13]:  import matplotlib.pyplot as plt
# Sample data
labels = ['Category A', 'Category B', 'Category C', 'Category D']
sizes = [30, 45, 15, 10]
colors = ['lightblue', 'lightcoral', 'lightgreen', 'lightsalmon']
explode = (0.1, 0, 0, 0) # Explode the first slice (Category A)
# Create a pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
# Add a title
plt.title('Pie Chart Example')
# Show the plot
plt.show()
In [15]:  import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a linear plot
plt.plot(x, y, marker='o', color='blue')
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Linear Plot Example')
# Show the plot
plt.grid(True)
plt.show()

In [16]:  import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a linear plot with custom line formatting
plt.plot(x, y, marker='o', color='blue', linestyle='--', linewidth=2,
markersize=8, label='Line Example')
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Linear Plot with Line Formatting')
# Show a legend
plt.legend()
# Show the plot
plt.grid(True)
plt.show()
In [17]:  import seaborn as sns
import matplotlib.pyplot as plt
# Load a built-in dataset from Seaborn
tips = sns.load_dataset("tips")
# Set Seaborn style and color palette
sns.set(style="whitegrid", palette="Set1")
# Create a customized scatter plot
plt.figure(figsize=(8, 6))
sns.scatterplot(x="total_bill", y="tip", data=tips, hue="time", style="sex",
s=100, palette="Set2")
plt.title("Customized Scatter Plot")
plt.xlabel("Total Bill")
plt.ylabel("Tip")
plt.legend(title="Time of Day")
plt.show()
# Create a customized histogram
plt.figure(figsize=(8, 6))
sns.histplot(tips["total_bill"], bins=20, kde=True, color="skyblue",
line_kws={"color": "red"})
plt.title("Customized Histogram")
plt.xlabel("Total Bill")
plt.ylabel("Frequency")
plt.grid(True)
plt.show()
# Create a customized box plot
plt.figure(figsize=(8, 6))
sns.boxplot(x="day", y="total_bill", data=tips, palette="husl")
plt.title("Customized Box Plot")
plt.xlabel("Day")
plt.ylabel("Total Bill")
plt.show()

In [25]:  import plotly.graph_objects as go
import numpy as np
# Create a grid of x and y values
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
# Define a 3D function (e.g., a surface)
Z = np.tan(np.sqrt(X**2 + Y**2))
# Create a 3D surface plot using Plotly
fig = go.Figure(data=go.Surface(z=Z, x=x, y=y))
fig.update_layout(scene=dict(zaxis_title="Z-axis", yaxis_title="Y-axis",
xaxis_title="X-axis"),
title="3D Surface Plot")
# Show the plot
fig.show()
3D Surface Plot
In [28]:  import plotly.graph_objects as go
import pandas as pd
# Sample time series data
data = {
'Date': pd.date_range(start='2023-01-01', periods=30, freq='D'),
'Value': [10, 15, 12, 18, 22, 24, 30, 28, 35, 40, 45, 48, 52, 50, 60, 58, 65,
70, 75, 80, 78, 85, 90, 95, 100, 95, 105, 110, 115, 120]
}
df = pd.DataFrame(data)
# Create a time series line plot
fig = go.Figure(data=go.Scatter(x=df['Date'], y=df['Value'],
mode='lines+markers', name='Time Series'))
# Set axis labels and plot title
fig.update_layout(xaxis_title='Date', yaxis_title='Value', title='Time Series Plot')
# Show the plot
fig.show()
Time Series Plot

120

100

80
Value

60

40

20

Jan 1 Jan 8 Jan 15 Jan 22 Jan 29


2023
In [29]:  import plotly.express as px
# Sample data
locations = ['New York', 'Los Angeles', 'Chicago', 'San Francisco']
latitudes = [40.7128, 34.0522, 41.8781, 37.7749]
longitudes = [-74.0060, -118.2437, -87.6298, -122.4194]
# Create a map
fig = px.scatter_geo(lat=latitudes, lon=longitudes, locationmode='USA-states',
text=locations)
# Customize the map
fig.update_geos(
projection_scale=10,
center=dict(lon=-95, lat=38),
visible=False,
showcoastlines=True,
coastlinecolor="RebeccaPurple",
showland=True,
landcolor="LightGreen",
showocean=True,
oceancolor="LightBlue",
showlakes=True,
lakecolor="LightBlue",
)
# Set map title
fig.update_layout(
title_text='Sample US Map',
title_x=0.5,
)
# Show the map
fig.show()
Sample US Map

Chicago

In [ ]:  ​

You might also like