آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
Photo
از این به بعد کد های بیشتری قرار میدم برای هر بخش که راحت بتونید کپی کنین و استفاده کنید . اگر دوست دارید حتما ری اکشن بزنید. 💕
# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # Output: apple, banana, cherry
# Looping through a string
for char in "hello":
print(char) # Output: h, e, l, l, o
# Using range to repeat a loop 5 times
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
# Looping with break
for num in range(10):
if num == 5:
break
print(num) # Output: 0 to 4
# Looping with continue
for i in range(5):
if i == 2:
continue
print(i) # Output: 0, 1, 3, 4
#code
#python
💻@voidcompile
❤28👍25💯1
آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
🧠🎲 الگوریتم مونت کارلو (Monte Carlo Simulation) – شبیهسازی تصادفی برای حل مسائل پیچیده ✅معرفی الگوریتم قسمت۸ 📌 یکی از پرکاربردترین روشهای محاسباتی در علم داده، یادگیری ماشین، فیزیک، آمار و تحلیل ریسک، الگوریتم شبیهسازی مونتکارلو است. این الگوریتم با…
🎯 سناریو:
فرض کنیم پروژهای داری که زمان تحویلش به ۳ عامل وابستهست:
زمان خوشبینانه (Optimistic time)
زمان واقعگرایانه (Most likely time)
زمان بدبینانه (Pessimistic time)
برای هر تسک، زمان مورد انتظار با توزیع شبهسهگانه (مثل توزیع PERT) تخمین زده میشه.
ما از شبیهسازی مونتکارلو استفاده میکنیم تا هزاران بار پروژه رو شبیهسازی کنیم و بفهمیم چه زمانی بیشترین احتمال رو برای پایان داره.
✅ کد پایتون: شبیهسازی ریسک زمان تحویل پروژه
#code
💻@voidcompile
فرض کنیم پروژهای داری که زمان تحویلش به ۳ عامل وابستهست:
زمان خوشبینانه (Optimistic time)
زمان واقعگرایانه (Most likely time)
زمان بدبینانه (Pessimistic time)
برای هر تسک، زمان مورد انتظار با توزیع شبهسهگانه (مثل توزیع PERT) تخمین زده میشه.
ما از شبیهسازی مونتکارلو استفاده میکنیم تا هزاران بار پروژه رو شبیهسازی کنیم و بفهمیم چه زمانی بیشترین احتمال رو برای پایان داره.
✅ کد پایتون: شبیهسازی ریسک زمان تحویل پروژه
import numpy as np
import matplotlib.pyplot as plt
# Define tasks with their optimistic, most likely, and pessimistic durations (in days)
tasks = [
{"name": "Requirements Analysis", "optimistic": 2, "most_likely": 4, "pessimistic": 6},
{"name": "Software Design", "optimistic": 3, "most_likely": 5, "pessimistic": 9},
{"name": "Implementation", "optimistic": 5, "most_likely": 10, "pessimistic": 15},
{"name": "Testing & Review", "optimistic": 2, "most_likely": 3, "pessimistic": 5}
]
# Number of Monte Carlo simulations
n_simulations = 10000
project_durations = []
# Run the Monte Carlo simulation
for _ in range(n_simulations):
total_duration = 0
for task in tasks:
o = task["optimistic"]
m = task["most_likely"]
p = task["pessimistic"]
# Generate a duration using triangular distribution
duration = np.random.triangular(o, m, p)
total_duration += duration
project_durations.append(total_duration)
# Calculate probability of finishing under 25 days
deadline = 25
prob = np.mean(np.array(project_durations) <= deadline)
# Plot the histogram
plt.figure(figsize=(10, 6))
plt.hist(project_durations, bins=50, color="#336699", alpha=0.85, edgecolor='black')
plt.title("Monte Carlo Simulation – Estimated Project Duration (10K Runs)", fontsize=14)
plt.xlabel("Project Duration (days)")
plt.ylabel("Frequency")
plt.grid(True)
plt.axvline(x=deadline, color='red', linestyle='--',
label=f'Deadline = {deadline} days\nP ≈ {prob*100:.2f}%')
plt.legend()
plt.tight_layout()
plt.show()
✅💡تصویر بالا نتیجه خروجی کد است.
📌 خروجی چی میده؟
یه نمودار هیستوگرام که نشون میده پراکندگی زمان تحویل پروژه چطوریه
عددی که احتمال رسیدن به ددلاین ۲۵ روزه رو میگه
با افزایش تعداد شبیهسازی (مثلاً 100,000)، دقت بالاتر میره
#code
💻@voidcompile
❤24👍23💯1
آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
🔹 آموزش پایتون – قسمت ۹ (جزوه + کد) کار با لیستها (List) – مدیریت مجموعهای از دادهها لیستها (List) یکی از ساختارهای دادهای پایه و قدرتمند در پایتون هستن که بهت اجازه میدن مجموعهای از آیتمها رو ذخیره، ویرایش و پردازش کنی. در این قسمت با روش ساخت، دسترسی،…
کد آموزش قسمت نهم
#Code
💻@voidcompile
# Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
# Accessing elements by index
print(fruits[1]) # Output: banana
# Changing an element
fruits[0] = "grape"
print(fruits) # Output: ['grape', 'banana', 'cherry']
# Adding an item
fruits.append("orange")
print(fruits) # Output: ['grape', 'banana', 'cherry', 'orange']
# Removing an item
fruits.remove("banana")
print(fruits) # Output: ['grape', 'cherry', 'orange']
# Looping through a list
for fruit in fruits:
print(fruit) # Output: grape \n cherry \n orange
# Checking membership
print("cherry" in fruits) # Output: True
#Code
💻@voidcompile
👍29❤21💯1
آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
👨💻 آموزش پایتون – قسمت ۱۱: ساخت پروژه To-Do List ساده توی این بخش از آموزش زبان برنامه نویسی پایتون، یه پروژه کاربردی و کوتاه طراحی کردیم که مناسب مبتدیها و علاقهمندان به شروع پروژههای واقعی با پایتونه. ✅ چی یاد میگیری؟ 🔸 ساخت لیست وظایف با استفاده…
👨💻 کد قسمت ۱۱: ساخت پروژه To-Do List ساده
#python
#code
💻@voidcompile
# Create an empty list to store tasks
tasks = []
# Function to add a new task to the list
def add_task(task):
tasks.append(task)
print("Task added:", task)
# Function to display all tasks in the list
def show_tasks():
print("\nYour To-Do List:")
for i, task in enumerate(tasks, 1): # Enumerate starts from 1
print(f"{i}. {task}")
# Main loop to run the menu
while True:
print("\n1. Add Task\n2. Show Tasks\n3. Exit")
choice = input("Enter your choice: ") # Ask the user for an option
if choice == "1":
task = input("Enter a new task: ") # Get task input from user
add_task(task) # Call function to add the task
elif choice == "2":
show_tasks() # Show all tasks
elif choice == "3":
print("Exiting the program.") # Exit message
break # Exit the loop
else:
print("Invalid choice. Please try again.") # Handle wrong input
#python
#code
💻@voidcompile
👍42💯41❤30🏆1
کد قسمت نهم آموزش الگورتیم .
#code
💻@voidcompile
اگر دوست داشتید میتونیم روی مثال های واقعی تر تمرکز کنیم ، برای این کار ری اکشن یادتون نره .
راستی میتونید بقیه الگوریتم هارو هم مشاهده کنین.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.cluster import DBSCAN
# تولید دادههای هلالیشکل با نویز
X, _ = make_moons(n_samples=300, noise=0.1, random_state=0)
# اعمال الگوریتم DBSCAN
db = DBSCAN(eps=0.2, min_samples=5)
labels = db.fit_predict(X)
# رنگبندی بر اساس لیبلها
unique_labels = set(labels)
colors = ['purple', 'gold', 'gray']
# رسم تصویر
plt.figure(figsize=(8, 6))
for k in unique_labels:
color = 'gray' if k == -1 else colors[k % len(colors)]
class_member_mask = (labels == k)
xy = X[class_member_mask]
plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=color, markeredgecolor='k', markersize=8, label=f'Cluster {k}' if k != -1 else 'Noise')
plt.title("DBSCAN clustering on moon-shaped data", fontsize=14)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
#code
💻@voidcompile
1❤51👍41💯20🏆13
آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
آموزش پایتون – قسمت ۱۲: ساخت برنامه دفترچه مخاطبین (Contact Manager) توی این قسمت، با استفاده از تمام چیزایی که تا الان یاد گرفتیم (مثل لیست، حلقه، شرط، توابع و ورودی کاربر)، یه پروژه واقعی و ساده میسازیم: برنامه مدیریت مخاطبین ✅ توی این تمرین یاد میگیری:…
کد آموزش پایتون قسمت ۱۲ قابل کپی
#code
💻@voidcompile
# Create an empty list to store contact dictionaries
contacts = []
# Define a function to add a new contact to the list
def add_contact(name, phone):
# Append a dictionary with name and phone number to the list
contacts.append({"name": name, "phone": phone})
# Print confirmation message
print(f"Contact {name} added.")
# Define a function to show all saved contacts
def show_contacts():
# Check if the list is empty
if not contacts:
print("No contacts yet.") # Inform the user there's no data
else:
print("\nContact List:") # Heading
# Loop through the list and display each contact
for i, c in enumerate(contacts, 1):
print(f"{i}. {c['name']} - {c['phone']}") # Print contact with number
# Define a function to search for a contact by name
def search_contact(name):
found = False # Flag to track if any contact is found
# Loop through contacts to search for a match
for c in contacts:
if c["name"].lower() == name.lower(): # Case-insensitive comparison
print(f"Found: {c['name']} - {c['phone']}") # Print matched contact
found = True
# If not found, notify the user
if not found:
print("Contact not found.")
# Main program loop to display menu and handle user choices
while True:
# Show menu options
print("\n1. Add Contact\n2. Show All\n3. Search\n4. Exit")
# Get user input for menu choice
choice = input("Choose an option: ")
# Handle user's choice
if choice == "1":
# Get contact name and phone from user
name = input("Enter name: ")
phone = input("Enter phone: ")
# Call function to add contact
add_contact(name, phone)
elif choice == "2":
# Call function to show all contacts
show_contacts()
elif choice == "3":
# Get name to search
name = input("Enter name to search: ")
# Call search function
search_contact(name)
elif choice == "4":
# Exit message
print("Goodbye!")
break # Exit the loop and stop the program
else:
# Handle invalid menu choices
print("Invalid option. Try again.")
#code
💻@voidcompile
👍50❤35💯27🏆13
آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
🪨✂️📄 آموزش ساخت بازی سنگ کاغذ قیچی با پایتون – پروژهای ساده اما کاربردی برای مبتدیها! ✅قسمت ۱۶ ام آموزش پایتون در این آموزش با استفاده از زبان برنامهنویسی پایتون یک بازی کلاسیک و جذاب طراحی میکنیم: سنگ، کاغذ، قیچی – بازیای که نه تنها مفاهیم پایهای…
کد آموزش ساخت بازی سنگ کاغذ قیچی با پایتون
توضیح کد:
خط 1: کتابخانه random برای انتخاب تصادفی توسط کامپیوتر وارد میشه.
خط 4: لیستی از گزینههای بازی تعریف شده: rock، paper، scissors.
خط 9-10: پیغام خوشآمدگویی و دستور خروج از بازی نمایش داده میشود.
خط 13-14: حلقه اصلی بازی؛ ورودی کاربر دریافت میشود.
خط 17-19: بررسی میکنیم اگر کاربر کلمه "quit" وارد کرده باشد، بازی متوقف شود.
خط 22-24: در صورتی که ورودی کاربر در لیست گزینهها نباشد، پیغام خطا داده میشود و حلقه ادامه پیدا میکند.
خط 27: کامپیوتر بهصورت تصادفی یکی از گزینهها را انتخاب میکند.
خط 30-39: براساس قوانین بازی، نتیجهی بازی محاسبه و نمایش داده میشود.
#code
💻@voidcompile
ری اکشن یادتون نره ممنوون
import random
# Define the possible choices
choices = ["rock", "paper", "scissors"]
print("Welcome to Rock, Paper, Scissors!")
print("Type 'quit' to exit the game.\n")
# Main game loop
while True:
# Get user input and convert to lowercase
user_choice = input("Enter your choice (rock, paper, scissors): ").lower()
# Exit condition
if user_choice == "quit":
print("Game over! Thanks for playing.")
break
# Validate user choice
if user_choice not in choices:
print("Invalid choice, please try again.\n")
continue
# Computer randomly selects one of the choices
computer_choice = random.choice(choices)
print(f"Computer chose: {computer_choice}")
# Determine the outcome
if user_choice == computer_choice:
print("It's a tie!\n")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "scissors" and computer_choice == "paper") or \
(user_choice == "paper" and computer_choice == "rock"):
print("You win!\n")
else:
print("You lose!\n")
توضیح کد:
خط 1: کتابخانه random برای انتخاب تصادفی توسط کامپیوتر وارد میشه.
خط 4: لیستی از گزینههای بازی تعریف شده: rock، paper، scissors.
خط 9-10: پیغام خوشآمدگویی و دستور خروج از بازی نمایش داده میشود.
خط 13-14: حلقه اصلی بازی؛ ورودی کاربر دریافت میشود.
خط 17-19: بررسی میکنیم اگر کاربر کلمه "quit" وارد کرده باشد، بازی متوقف شود.
خط 22-24: در صورتی که ورودی کاربر در لیست گزینهها نباشد، پیغام خطا داده میشود و حلقه ادامه پیدا میکند.
خط 27: کامپیوتر بهصورت تصادفی یکی از گزینهها را انتخاب میکند.
خط 30-39: براساس قوانین بازی، نتیجهی بازی محاسبه و نمایش داده میشود.
#code
💻@voidcompile
🔥60❤50💯44👍40🏆17
آموزش پایتون | هوش مصنوعی | برنامه نویسی | voidcompile
از قوانین فوقالعاده ساده، رفتارهای پیچیده و شگفتانگیز بهوجود میاد (Glider، Oscillator، Still Life و ...). import numpy as np # وارد کردن numpy برای کار با آرایهها import matplotlib.pyplot as plt # وارد کردن matplotlib برای نمایش تصویری…
🕒 کد ساعت دیجیتال با پایتون ⏰
با این کد ساده میتونی یک ساعت دیجیتال زنده داخل ترمینال خودت داشته باشی!
کافیه اجراش کنی و هر ثانیه ساعت بهروز میشه.
📌 مفاهیم آموزشی داخل کد:
ماژول time برای گرفتن ساعت سیستم
ماژول os برای پاککردن ترمینال
کار با حلقهی بینهایت و توقف با Ctrl+C
💡 این پروژهی کوچیک هم فان هست، هم بهت کمک میکنه با زمان در پایتون کار کنی.
#LearnPython@voidcompile
#code
💻@voidcompile
با این کد ساده میتونی یک ساعت دیجیتال زنده داخل ترمینال خودت داشته باشی!
کافیه اجراش کنی و هر ثانیه ساعت بهروز میشه.
📌 مفاهیم آموزشی داخل کد:
ماژول time برای گرفتن ساعت سیستم
ماژول os برای پاککردن ترمینال
کار با حلقهی بینهایت و توقف با Ctrl+C
💡 این پروژهی کوچیک هم فان هست، هم بهت کمک میکنه با زمان در پایتون کار کنی.
import time
import os
def clear():
os.system("cls" if os.name == "nt" else "clear")
while True:
clear()
print("⏰ ساعت دیجیتال پایتون ⏰\n")
print(time.strftime("%H:%M:%S"))
time.sleep(1)
#LearnPython@voidcompile
#code
💻@voidcompile
2👍21🤩15🔥11💯10❤9