Saturday, February 8, 2025

 Python Deli Prof

import numpy as np
import sympy as sp
import decimal
from decimal import Decimal, getcontext
import matplotlib.pyplot as plt

# Sayısal Integral Hesaplama Fonksiyonu
def numerical_integral():
func_expr = input("Enter the function f(x) to integrate: ")
try:
func = eval("lambda x: " + func_expr, {"__builtins__": None},
{"np": np, "sin": np.sin, "cos": np.cos, "exp": np.exp, "log": np.log, "sqrt": np.sqrt})
a = float(input("Enter the lower limit of integration (a): "))
b = float(input("Enter the upper limit of integration (b): "))
x = np.linspace(a, b, 1000)
y = func(x)
integral_value = np.trapz(y, x)
print(f"The integral of the function from {a} to {b} is approximately {integral_value}")
except Exception as e:
print(f"Error in evaluating the function: {e}")

# Sembolik Integral Hesaplama Fonksiyonu
def symbolic_integral():
x = sp.symbols('x')
function_expr = input("Enter the function f(x) to integrate: ")
try:
func = sp.sympify(function_expr)
integral = sp.integrate(func, x)
print(f"The integral of {sp.pretty(func)} with respect to x is:")
print(sp.pretty(integral))
except Exception as e:
print(f"Error in evaluating the function: {e}")

# Asal Sayıları Bulma Fonksiyonu
def find_primes():
start = int(input("Enter the starting number of the range: "))
end = int(input("Enter the ending number of the range: "))
primes = []
for num in range(start, end + 1):
is_prime = all(num % i != 0 for i in range(2, int(num ** 0.5) + 1))
if is_prime and num > 1:
primes.append(num)
print(f"Prime numbers between {start} and {end} are: {primes}")

# İkiz Asal Sayıları Bulma Fonksiyonu
def find_twin_primes():
start = int(input("Enter the starting number of the range: "))
end = int(input("Enter the ending number of the range: "))
twin_primes = []
primes = []
for num in range(start, end + 1):
is_prime = all(num % i != 0 for i in range(2, int(num ** 0.5) + 1))
if is_prime and num > 1:
primes.append(num)
for i in range(len(primes) - 1):
if primes[i + 1] - primes[i] == 2:
twin_primes.append((primes[i], primes[i + 1]))
print(f"Twin prime numbers between {start} and {end} are: {twin_primes}")
# Kuvvet Hesaplama Fonksiyonu
def high_precision_power():
base = Decimal(input("Enter the base number: "))
exponent = Decimal(input("Enter the exponent: "))
precision = int(input("Enter the number of decimal places: "))
getcontext().prec = precision + 2 # Ekstra iki hane daha doğru sonuçlar için
result = base ** exponent
print(f"The result of {base} raised to the power of {exponent} to {precision} decimal places is:")
print(f"{result:.{precision}f}")

# Kök Bulma (Root Finding) Fonksiyonu
def root_finding():
x = sp.symbols('x')
function_expr = input("Enter the function f(x): ")
func = sp.sympify(function_expr)
initial_guess = float(input("Enter an initial guess: "))
root = sp.nsolve(func, x, initial_guess)
print(f"A root of the function is: {root}")

# İstatistiksel Analiz Fonksiyonu
def statistical_analysis():
data = list(map(float, input("Enter the data set (comma-separated): ").split(',')))
mean = np.mean(data)
median = np.median(data)
std_dev = np.std(data)
print(f"Mean: {mean}, Median: {median}, Standard Deviation: {std_dev}")
# Eğri Uydurma (Curve Fitting) Fonksiyonu
def curve_fitting():
x_data = list(map(float, input("Enter the x data points (comma-separated): ").split(',')))
y_data = list(map(float, input("Enter the y data points (comma-separated): ").split(',')))
degree = int(input("Enter the degree of the polynomial to fit: "))
coeffs = np.polyfit(x_data, y_data, degree)
poly = np.poly1d(coeffs)
print(f"Fitted polynomial: {poly}")

# Diferansiyel Denklemler Çözme Fonksiyonu
def solve_differential_equation():
x = sp.symbols('x')
y = sp.Function('y')
eq = input("Enter the differential equation (in terms of y(x)): ")
deqn = sp.sympify(eq)
solution = sp.dsolve(deqn, y(x))
print(f"The solution is: {solution}")

# Matris İşlemleri Fonksiyonu
def matrix_operations():
rows = int(input("Enter the number of rows for the matrix: "))
cols = int(input("Enter the number of columns for the matrix: "))
print("Enter the elements of the matrix row-wise:")
matrix = [[float(input()) for _ in range(cols)] for _ in range(rows)]
mat = np.array(matrix)
determinant = np.linalg.det(mat)
inverse = np.linalg.inv(mat) if determinant != 0 else None
print(f"Determinant: {determinant}")
print(f"Inverse: {inverse}" if inverse is not None else "Inverse does not exist.")
# Kompleks Sayı İşlemleri Fonksiyonu
def complex_number_operations():
z1 = complex(input("Enter the first complex number (in the form a+bj): "))
z2 = complex(input("Enter the second complex number (in the form a+bj): "))
print(f"Sum: {z1 + z2}")
print(f"Difference: {z1 - z2}")
print(f"Product: {z1 * z2}")
print(f"Quotient: {z1 / z2}")

# Fonksiyon Grafikleme Fonksiyonu
def plot_function():
x = sp.symbols('x')
func_expr = input("Enter the function f(x) to plot: ")
func = sp.sympify(func_expr)
f = sp.lambdify(x, func, modules=['numpy'])
x_vals = np.linspace(-10, 10, 400)
y_vals = f(x_vals)
plt.plot(x_vals, y_vals)
plt.title(f'Plot of {func_expr}')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.show()

# Rasgele Sayı Üretimi Fonksiyonu
def random_number_generation():
dist = input("Enter the distribution (uniform/normal): ")
n = int(input("Enter the number of random numbers to generate: "))
if dist == "uniform":
low = float(input("Enter the lower bound: "))
high = float(input("Enter the upper bound: "))
random_numbers = np.random.uniform(low, high, n)
elif dist == "normal":
mean = float(input("Enter the mean: "))
std_dev = float(input("Enter the standard deviation: "))
random_numbers = np.random.normal(mean, std_dev, n)
else:
print("Invalid distribution.")
return
print(f"Generated random numbers: {random_numbers}")


# Fourier ve Laplace Dönüşümleri Fonksiyonu
def fourier_laplace_transforms():
x = sp.symbols('x')
t = sp.symbols('t', real=True)
func_expr = input("Enter the function f(t) for Fourier and Laplace transforms: ")
func = sp.sympify(func_expr)

fourier_transform = sp.fourier_transform(func, t, x)
laplace_transform = sp.laplace_transform(func, t, x)

print(f"Fourier Transform: {sp.pretty(fourier_transform)}")
print(f"Laplace Transform: {sp.pretty(laplace_transform[0])}")


# Finansal Hesaplamalar Fonksiyonu
def financial_calculations():
print("\nChoose a financial calculation to perform:")
print("1: Simple Interest")
print("2: Compound Interest")
choice = input("Enter your choice: ")

if choice == '1':
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (in %): "))
time = float(input("Enter the time (in years): "))
simple_interest = (principal * rate * time) / 100
print(f"Simple Interest: {simple_interest}")

elif choice == '2':
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (in %): "))
time = float(input("Enter the time (in years): "))
n = int(input("Enter the number of times interest applied per year: "))
compound_interest = principal * (1 + rate / (n * 100)) ** (n * time)
print(f"Compound Interest: {compound_interest}")

else:
print("Invalid choice.")


# Graf Teorisi Fonksiyonu
def graph_theory():
import networkx as nx
G = nx.Graph()
n = int(input("Enter the number of nodes: "))
print("Enter the edges (format: node1 node2): ")
for _ in range(n):
u, v = map(int, input().split())
G.add_edge(u, v)

nx.draw(G, with_labels=True)
plt.show()


# Kriptografi Fonksiyonu
def cryptography():
print("\nChoose a cryptographic function:")
print("1: Caesar Cipher")
print("2: RSA Encryption")
choice = input("Enter your choice: ")

if choice == '1':
text = input("Enter the text to encrypt: ")
shift = int(input("Enter the shift value: "))
encrypted = ''.join([chr((ord(char) + shift - 97) % 26 + 97) if char.islower() else char for char in text])
print(f"Encrypted Text: {encrypted}")

elif choice == '2':
import rsa
(pubkey, privkey) = rsa.newkeys(512)
message = input("Enter the message to encrypt: ").encode('utf8')
encrypted = rsa.encrypt(message, pubkey)
print(f"Encrypted Message: {encrypted}")
decrypted = rsa.decrypt(encrypted, privkey).decode('utf8')
print(f"Decrypted Message: {decrypted}")

else:
print("Invalid choice.")


# Birim Dönüşümleri Fonksiyonu
def unit_conversion():
print("\nChoose a unit conversion:")
print("1: Length")
print("2: Mass")
print("3: Volume")
choice = input("Enter your choice: ")

if choice == '1':
value = float(input("Enter the length in meters: "))
print(f"{value} meters is {value * 100} centimeters")
print(f"{value} meters is {value / 1000} kilometers")

elif choice == '2':
value = float(input("Enter the mass in kilograms: "))
print(f"{value} kilograms is {value * 1000} grams")
print(f"{value} kilograms is {value / 1000} metric tons")

elif choice == '3':
value = float(input("Enter the volume in liters: "))
print(f"{value} liters is {value * 1000} milliliters")
print(f"{value} liters is {value / 1000} cubic meters")

else:
print("Invalid choice.")


# Olasılık Hesaplamaları Fonksiyonu
def probability_calculations():
print("\nChoose a probability calculation:")
print("1: Binomial Probability")
print("2: Normal Distribution Probability")
choice = input("Enter your choice: ")

if choice == '1':
n = int(input("Enter the number of trials: "))
p = float(input("Enter the probability of success: "))
k = int(input("Enter the number of successes: "))
binom_prob = sp.binomial(n, k) * (p ** k) * ((1 - p) ** (n - k))
print(f"Binomial Probability: {binom_prob}")

elif choice == '2':
mean = float(input("Enter the mean: "))
std_dev = float(input("Enter the standard deviation: "))
x = float(input("Enter the value: "))
normal_prob = (1 / (std_dev * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((x - mean) / std_dev) ** 2)
print(f"Normal Distribution Probability: {normal_prob}")

else:
print("Invalid choice.")
# Program Seçim Fonksiyonu
def choose_program():
print("\nChoose a program to run:")
print("1: Numeric Integration")
print("2: Symbolic Integration")
print("3: Prime Numbers within Range")
print("4: Twin Prime Numbers within Range")
print("5: Solve N-Variable Linear Equations")
print("6: Matrix Multiplication")
print("7: High Precision Power Calculation")
print("8: Root Finding")
print("9: Statistical Analysis")
print("10: Curve Fitting")
print("11: Solve Differential Equations")
print("12: Matrix Operations")
print("13: Complex Number Operations")
print("14: Plot Functions")
print("15: Random Number Generation")
print("16: Fourier and Laplace Transforms")
print("17: Financial Calculations")
print("18: Graph Theory")
print("19: Cryptography")
print("20: Unit Conversions")
print("21: Probability Calculations")
print("22: Exit")
choice = input("Enter your choice: ")
return choice

# Ana Program Döngüsü
def solve_linear_equations():
pass


def matrix_multiplication():
pass


def main():
while True:
choice = choose_program()

if choice.isdigit():
choice = int(choice)
else:
print("Invalid input. Please enter a number.")
continue

if choice == 1:
numerical_integral()

elif choice == 2:
symbolic_integral()

elif choice == 3:
find_primes()

elif choice == 4:
find_twin_primes()

elif choice == 5:
solve_linear_equations()

elif choice == 6:
matrix_multiplication()

elif choice == 7:
high_precision_power()

elif choice == 8:
root_finding()

elif choice == 9:
statistical_analysis()

elif choice == 10:
curve_fitting()

elif choice == 11:
solve_differential_equation()

elif choice == 12:
matrix_operations()

elif choice == 13:
complex_number_operations()

elif choice == 14:
plot_function()

elif choice == 15:
random_number_generation()

elif choice == 16:
fourier_laplace_transforms()

elif choice == 17:
financial_calculations()

elif choice == 18:
graph_theory()

elif choice == 19:
cryptography()

elif choice == 20:
unit_conversion()

elif choice == 21:
probability_calculations()

elif choice == 22:
print("Exiting the program.")
break

else:
print("Invalid choice. Please select a valid program number.")

if __name__ == "__main__":
main()

No comments:

Post a Comment