Python Solutions Collection
Question [Link]
for i in range(1,6):
for j in range(i):
print(i,end=" ")
print(" " * (5 - i), end=" ")
print(" " * (5 - i), end="")
for j in range(1,i+1):
print(j,end=" ")
print()
print()
for i in range(5,0,-1):
for j in range(i):
print(i,end=" ")
print(" " * (5 - i), end=" ")
print(" " * (5 - i), end="")
for j in range(i,0,-1):
print(j,end=" ")
print()
print()
Question [Link]
import math
class Vec3d:
def __init__(self,x=0,y=0,z=0):
self.x=(x)
self.y=(y)
self.z=(z)
def __str__(self):
return f"({self.x}i,{self.y}j,{self.z}k)"
def add(self,b):
return Vec3d(self.x+b.x,self.y+b.y,self.z+b.z)
def sub(self,b):
return Vec3d(self.x-b.x,self.y-b.y,self.z-b.z)
def dot(self,b):
return (self.x*b.x+self.y*b.y+self.z*b.z)
def cross(self,b):
x=self.y*b.z-self.z*b.y
y=self.z*b.x-self.x*b.z
z=self.x*b.y-self.y*b.x
return Vec3d(x,y,z)
def len(self):
return [Link]((self.x)**2+(self.y)**2+(self.z)**2)
def norm(self):
l=[Link]()
return Vec3d(self.x/l,self.y/l,self.z/l)
def main():
print("-----enter first vector-----:")
x1=float(input("enter the x coordinate:"))
y1=float(input("enter the y coordinate:"))
z1=float(input("enter the z coordinate:"))
v1=Vec3d(x1,y1,z1)
print("\n-----enter second vector-----:")
x2=float(input("enter the x coordinate:"))
y2=float(input("enter the y coordinate:"))
z2=float(input("enter the z coordinate:"))
v2=Vec3d(x2,y2,z2)
print("\nvector1 is:",v1)
print("vector2 is:",v2)
print("\naddition is:",[Link](v2))
print("subtraction is:",[Link](v2))
print("dot product is :",[Link](v2))
print("cross product is:",[Link](v2))
print("length is:",[Link]())
print("normalform is:",[Link]())
if __name__=="__main__":
main()
Question [Link]
import math
class circularlength:
def __init__(self,radius=0,angle=0):
[Link]=radius #in meter
[Link]=angle
def calculate_arc_length(self):
rad=[Link]*[Link]/180
l=[Link]*rad
print("arc length is:",l)
def __del__(self):
print("object distroyed.")
def main():
radius=float(input("enter the radius:"))
angle=float(input("enter the value of angle(in degree):"))
a=circularlength(radius,angle)
a.calculate_arc_length()
del a
if __name__=="__main__":
main()
Question [Link]
import math
class shape:
def area(self):
pass
def perimeter(self):
pass
class circle(shape):
def __init__(self,radius):
[Link]=radius
def area(self):
area=[Link]*([Link]**2)
print("area of the circle is:",area)
def perimeter(self):
perimeter=2*[Link]*[Link]
print("perimeter of the circle is:",perimeter)
class hexagon(shape):
def __init__(self,side):
[Link]=side
def area(self):
area=(3*[Link](3)*[Link]**2)/2
print("Area of the hexagon is(in [Link]):",area)
def perimeter(self):
perimeter=6*[Link]
print("perimeter of the hexagon is:",perimeter)
def main():
shape=input("what shape it is:")
if shape=="circle":
r=float(input("enter radius of circle:"))
c=circle(r)
[Link]()
[Link]()
elif shape=="hexagon":
a=float(input("enter side of hexagon:"))
h=hexagon(a)
[Link]()
[Link]()
else:
print("only circle and hexagon is valid here!")
if __name__=="__main__":
main()
Question [Link]
def readData():
data = []
print("Enter float numbers (type 'done' to stop):")
while True:
value = input("Enter number: ")
if [Link]() == 'done':
break
try:
num = float(value)
[Link](num)
except ValueError:
print("Invalid input! Please enter a float number.")
return data
def bubbleSort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return lst
def saveSortedList(lst, filename):
try:
with open(filename, 'w') as file:
for item in lst:
[Link](str(item) + "\n")
print(f"Sorted list saved to '{filename}' successfully.")
except Exception as e:
print("Error while saving file:", e)
def main():
data = readData()
if not data:
print("No data entered.")
return
print("Original list:", data)
sorted_list = bubbleSort([Link]())
print("Sorted list:", sorted_list)
filename = input("Enter filename (with .txt extension): ")
saveSortedList(sorted_list, filename)
if __name__ == "__main__":
main()
Question [Link]
import numpy as np
import [Link] as plt
P0 = [Link]([2, 2, 0])
P1 = [Link]([2, 3, 0])
P2 = [Link]([3, 3, 0])
P3 = [Link]([3, 2, 0])
def bezier_curve(P0, P1, P2, P3, num_points=100):
t_values = [Link](0, 1, num_points)
curve = []
for t in t_values:
B_t = ((1 - t)**3) * P0 + \
3 * ((1 - t)**2) * t * P1 + \
3 * (1 - t) * (t**2) * P2 + \
(t**3) * P3
[Link](B_t)
return [Link](curve)
def main():
curve = bezier_curve(P0, P1, P2, P3)
x = curve[:, 0]
y = curve[:, 1]
[Link](x, y, label="Bezier Curve")
control_x = [P0[0], P1[0], P2[0], P3[0]]
control_y = [P0[1], P1[1], P2[1], P3[1]]
[Link](control_x, control_y, 'o--', label="Control Points")
[Link]("Cubic Bezier Curve")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
[Link]()
[Link]()
if __name__ == "__main__":
main()
Question [Link]
import numpy as np
def f(x):
return x[0]**2 + x[1]**2
def simplex():
# Initial simplex (3 points for 2D)
s = [[Link]([1.0, 1.0]),
[Link]([1.5, 1.0]),
[Link]([1.0, 1.5])]
for _ in range(50):
s = sorted(s, key=lambda x: f(x)) # sort points
best, worst = s[0], s[-1]
# Centroid of best two
centroid = (s[0] + s[1]) / 2
# Reflection
xr = centroid + (centroid - worst)
if f(xr) < f(best):
s[-1] = xr # accept better point
else:
# Contraction
s[-1] = (worst + centroid) / 2
return s[0]
# Run
res = simplex()
print("Minimum point:", res)
print("Minimum value:", f(res))
Question [Link]
def f(x):
return x**3 - x - 2 # Example function
def df(x):
return 3*x**2 - 1 # Derivative of f(x)
def newton_raphson(x0, tol=1e-6, max_iter=100):
for i in range(max_iter):
x1 = x0 - f(x0)/df(x0)
if abs(x1 - x0) < tol:
print("Root:", x1)
print("Iterations:", i+1)
return
x0 = x1
print("Did not converge")
# Initial guess
x0 = float(input("Enter initial guess: "))
newton_raphson(x0)
Question [Link]
import numpy as np
import [Link] as plt
x = [Link](-2*[Link], 2*[Link], 1000)
# Functions
y_sin = [Link](x)
y_cos = [Link](x)
y_tan = [Link](x)
y_cot = 1/[Link](x)
# SIN
[Link]()
[Link](x, y_sin,color='blue')
[Link]("sin(x)")
[Link]("x")
[Link]("sin(x)")
[Link]()
[Link](True)
[Link]()
# COS
[Link]()
[Link](x, y_cos,color='black')
[Link]("cos(x)")
[Link]("x")
[Link]("cos(x)")
[Link]()
[Link](True)
[Link]()
# TAN (limit values to avoid infinity spikes)
[Link]()
[Link](x, y_tan,color='orange')
[Link](-10, 10)
[Link]("tan(x)")
[Link]("x")
[Link]("tan(x)")
[Link]()
[Link](True)
[Link]()
# COT
[Link]()
[Link](x, y_cot,color='green')
[Link](-10, 10)
[Link]("cot(x)")
[Link]("x")
[Link]("cot(x)")
[Link]()
[Link](True)
[Link]()
[Link]()
[Link](x, y_sin, label="sin(x)")
[Link](x, y_cos, label="cos(x)")
[Link](x, y_tan, label="tan(x)")
[Link](x, y_cot, label="cot(x)")
[Link](-10, 10)
[Link]("Trigonometric Functions")
[Link]("x")
[Link]("Value")
[Link]()
[Link]()
[Link]()
fig, axs = [Link](2, 2, figsize=(10, 8))
# SIN
axs[0, 0].plot(x, y_sin,color='blue')
axs[0, 0].set_title("sin(x)")
axs[0, 0].set_xlabel("x")
axs[0, 0].set_ylabel("sin(x)")
axs[0, 0].grid()
# COS
axs[0, 1].plot(x, y_cos,color='black')
axs[0, 1].set_title("cos(x)")
axs[0, 1].set_xlabel("x")
axs[0, 1].set_ylabel("cos(x)")
axs[0, 1].grid()
# TAN
axs[1, 0].plot(x, y_tan,color='orange')
axs[1, 0].set_ylim(-10, 10)
axs[1, 0].set_title("tan(x)")
axs[1, 0].set_xlabel("x")
axs[1, 0].set_ylabel("tan(x)")
axs[1, 0].grid()
# COT
axs[1, 1].plot(x, y_cot,color='green')
axs[1, 1].set_ylim(-10, 10)
axs[1, 1].set_title("cot(x)")
axs[1, 1].set_xlabel("x")
axs[1, 1].set_ylabel("cot(x)")
axs[1, 1].grid()
plt.tight_layout()
[Link]()
Question [Link]
import tkinter as tk
def click(val):
[Link]([Link], val)
def clear():
[Link](0, [Link])
def calculate():
try:
result = eval([Link]())
[Link](0, [Link])
[Link](0, result)
except:
[Link](0, [Link])
[Link](0, "Error")
root = [Link]()
[Link]("Calculator")
entry = [Link](root, width=20, font=("Arial", 18))
[Link](row=0, column=0, columnspan=4)
buttons = [
'7','8','9','/',
'4','5','6','*',
'1','2','3','-',
'0','C','=','+'
]
row, col = 1, 0
for b in buttons:
if b == 'C':
cmd = clear
elif b == '=':
cmd = calculate
else:
cmd = lambda x=b: click(x)
[Link](root, text=b, width=5, height=2, command=cmd).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
[Link]()