تمرینات پایتون + سورس کد
تمرینات پایتون – با سلام خدمت خوانندگان عزیز ؛ در این مقاله قصد داریم تعدادی از مثال ها / کد ها و سورس های زبان برنامه نویسی python را به علاقه مندان این زبان برنامه نویسی قرار دهیم.
پیادهسازی الگوریتم A* برای جستجوی بهینه مسیر در یک شبکه.
الگوریتم A* یک الگوریتم جستجوی بهینه است که برای پیدا کردن مسیر کوتاهترین میان دو نقطه در یک شبکه استفاده میشود. در این الگوریتم، هر گره یا نقطه در شبکه دارای یک هزینه تخصیص داده میشود که معمولاً شامل هزینه حرکت از گره فعلی به گره هدف و هزینه تخصیص داده شده به گره فعلی است. برای پیادهسازی این الگوریتم در پایتون، میتوانید از کد زیر استفاده کنید:
import heapq
def astar(graph, start, goal):
"""
الگوریتم A* برای پیدا کردن مسیر کوتاهترین میان دو نقطه در یک شبکه.
"""
frontier = []
heapq.heappush(frontier, (0, start))
came_from = {}
cost_so_far = {}
came_from[start] = None
cost_so_far[start] = 0
while frontier:
current = heapq.heappop(frontier)[1]
if current == goal:
break
for next_node in graph.neighbors(current):
new_cost = cost_so_far[current] + graph.cost(current, next_node)
if next_node not in cost_so_far or new_cost < cost_so_far[next_node]:
cost_so_far[next_node] = new_cost
priority = new_cost + graph.heuristic(next_node, goal)
heapq.heappush(frontier, (priority, next_node))
came_from[next_node] = current
return came_from, cost_so_fa
r
در این کد، graph یک شیء از کلاس Graph است که شبکه را نمایش میدهد. start و goal نقاط شروع و پایان مسیر به ترتیب هستند. الگوریتم A* با استفاده از دو دیکشنری came_from و cost_so_far مسیر کوتاهترین میان دو نقطه را پیدا میکند. came_from نشان میدهد که هر گره از کجا آمده است و cost_so_far هزینه مسیر کوتاهترین میان دو نقطه را نشان میدهد.
برای استفاده از این الگوریتم، شما باید یک کلاس Graph بنویسید که شبکه را نمایش دهد و دو تابع neighbors و cost را برای آن پیادهسازی کنید. neighbors باید لیستی از همه گرههای مجاور به یک گره داده شده را برگرداند و cost باید هزینه حرکت از یک گره به گره دیگر را بازگرداند. به عنوان مثال، برای یک شبکه مربعی با ابعاد n، میتوانید کد زیر را برای پیادهسازی کلاس Graph استفاده کنید:
class SquareGrid: def __init__(self, width, height): self.width = width self.height = height self.walls = [] def in_bounds(self, node): (x, y) = node return 0 <= x < self.width and 0 <= y < self.height def passable(self, node): return node not in self.walls def neighbors(self, node): (x, y) = node results = [(x+1, y), (x, y-1), (x-1, y), (x, y+1)] if (x + y) % 2 == 0: results.reverse() # aesthetics results = filter(self.in_bounds, results) results = filter(self.passable, results) return results def cost(self, current, next): return 1
در این کد، walls یک لیست از گرههایی است که قابل عبور نیستند. تابع in_bounds بررسی میکند که یک گره در محدوده شبکه قرار دارد یا خیر، و تابع passable بررسی میکند که یک گره قابل عبور است یا خیر. تابع neighbors لیستی از همه گرههای مجاور به یک گره را برمیگرداند و تابع cost هزینه حرکت از یک گره به گره دیگر را بازمیگرداند که در این مثال برابر با یک است.
بعد از پیادهسازی کلاس Graph، میتوانید از الگوریتم A* برای پیدا کردن مسیر کوتاهترین میان دو نقطه در شبکه استفاده کنید. به عنوان مثال، شما میتوانید از کد زیر برای پیدا کردن مسیر کوتاهترین میان دو نقطه در یک شبکه مربعی با ابعاد n استفاده کنید:
n = 10
g = SquareGrid(n, n)
g.walls = [(1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (3, 4), (2, 4)]
start = (1, 2)
goal = (8, 8)
came_from, cost_so_far = astar(g, start, goal)
در این مثال، یک شبکه مربعی با ابعاد n=10 ایجاد میشود و تعدادی گره به عنوان دیوار مشخص شدهاند. سپس گره شروع و پایان مشخص شده و الگوریتم A* برای پیدا کردن مسیر کوتاهترین میان دو نقطه اجرا میشود. خروجی این الگوریتم شامل دو دیکشنری came_from و cost_so_far است که مسیر کوتاهترین میان دو نقطه را نشان میدهند.
معکوس کردن لیست
# Reversing a list using reversed() def Reverse(lst): return [ele for ele in reversed(lst)] # Driver Code lst = [10, 11, 12, 13, 14, 15] print(Reverse(lst))
معکوس کردن لیست با روشی دیگر
# Reversing a tuple using slicing technique
# New tuple is created
def Reverse(tuples):
new_tup = tuples[::-1]
return new_tup
# Driver Code
tuples = ('z','a','d','f','g','e','e','k')
print(Reverse(tuples))
Output:
('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')
تبدیل رشته به دیکشنری در پایتون
# Python3 code to demonstrate working of
# Convert String to tuple list
# using loop + replace() + split()
# initializing string
test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)"
# printing original string
print("The original string is : " + test_str)
# Convert String to tuple list
# using loop + replace() + split()
res = []
temp = []
for token in test_str.split(", "):
num = int(token.replace("(", "").replace(")", ""))
temp.append(num)
if ")" in token:
res.append(tuple(temp))
temp = []
# printing result
print("List after conversion from string : " + str(res))
Output :
The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6) List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)
محاصبه مصاحت دایره با پایتون:
s = (a+b+c)/2 area = √(s(s-a)*(s-b)*(s-c))
کد برنامه
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Output
The area of the triangle is
فاکتوریل با پایتون
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
چاپ فیبوناچی اعداد
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
مثله 8 وزیر با پایتون (ملکه)
BOARD_SIZE = 8
class BailOut(Exception):
pass
def validate(queens):
left = right = col = queens[-1]
for r in reversed(queens[:-1]):
left, right = left-1, right+1
if r in (left, col, right):
raise BailOut
def add_queen(queens):
for i in range(BOARD_SIZE):
test_queens = queens + [i]
try:
validate(test_queens)
if len(test_queens) == BOARD_SIZE:
return test_queens
else:
return add_queen(test_queens)
except BailOut:
pass
raise BailOut
queens = add_queen([])
print (queens)
print ("\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens))
پیدا کردن Resolution تصایر با پایتون
Source Code of Find Resolution of JPEG Image
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
Output
The resolution of the image is 280 x 280
کد بازی حدس زدن شماره با پایتون
import random
guesses_made = 0
name = input('Hello! What is your name?\n')
number = random.randint(1, 20)
print ('Well, {0}, I am thinking of a number between 1 and 20.'.format(name))
while guesses_made < 6:
guess = int(input('Take a guess: '))
guesses_made += 1
if guess < number:
print ('Your guess is too low.')
if guess > number:
print ('Your guess is too high.')
if guess == number:
break
if guess == number:
print ('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made))
else:
print ('Nope. The number I was thinking of was {0}'.format(number))
الگوریتم merge sort در پایتون
from __future__ import annotations
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, new_data: int) -> None:
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printLL(self) -> None:
temp = self.head
if temp == None:
return 'Linked List is empty'
while temp.next:
print(temp.data, '->', end='')
temp = temp.next
print(temp.data)
return
# Merge two sorted linked lists
def merge(left, right):
if not left:
return right
if not right:
return left
if left.data < right.data:
result = left
result.next = merge(left.next, right)
else:
result = right
result.next = merge(left, right.next)
return result
# Merge sort for linked list
def merge_sort(head):
if not head or not head.next:
return head
# Find the middle of the list
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
left = head
right = slow.next
slow.next = None
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
if __name__ == "__main__":
ll = LinkedList()
print("Enter the space-separated values of numbers to be inserted in the linked list prompted below:")
arr = list(map(int, input().split()))
for num in arr:
ll.insert(num)
print("Linked list before sorting:")
ll.printLL()
ll.head = merge_sort(ll.head)
print('Linked list after sorting:')
ll.printLL()
الگوریتم heap sort در پایتون
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def print_list(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
def heapify(self, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
current = self.head
for _ in range(i):
current = current.next
if left < n and current.data < current.next.data:
largest = left
if right < n and current.data < current.next.data:
largest = right
if largest != i:
self.swap(i, largest)
self.heapify(n, largest)
def swap(self, i, j):
current_i = self.head
current_j = self.head
for _ in range(i):
current_i = current_i.next
for _ in range(j):
current_j = current_j.next
current_i.data, current_j.data = current_j.data, current_i.data
def heap_sort(self):
n = 0
current = self.head
while current:
n += 1
current = current.next
for i in range(n // 2 - 1, -1, -1):
self.heapify(n, i)
for i in range(n - 1, 0, -1):
self.swap(0, i)
self.heapify(i, 0)
# Example usage:
linked_list = LinkedList()
linked_list.push(12)
linked_list.push(11)
linked_list.push(13)
linked_list.push(5)
linked_list.push(6)
linked_list.push(7)
print("Original Linked List:")
linked_list.print_list()
linked_list.heap_sort()
print("Sorted Linked List:")
linked_list.print_list()
بازی دوز در پایتون به صورت گرافیکی با هوش مصنوعی
AI Tic Tac Toe Game
بازی Tic Tac Toe یا نوعی بازی ایکس و صفحه (X and O) است که با استفاده از یک صفحه 3×3 یا گاهی بزرگتر، بازی میشود. هدف این بازی، قرار دادن سه نماد یا علامت مشابه (معمولاً ایکس یا صفحه) در یک خط افقی، عمودی یا قطری بر روی صفحه است.
بازیکنان به طور متوالی نوبتها را بازی میکنند و در هر نوبت، یکی از آنها یک نماد را در یکی از خانههای صفحه قرار میدهد. بازی ادامه مییابد تا زمانی که یکی از بازیکنان سه نماد مشابه را در یک خط به صورت افقی، عمودی یا قطری قرار دهد و برنده شود، یا صفحه پر شود و مساوی شود.
Tic Tac Toe یک بازی ساده است که قوانین آن بسیار ساده و قابل فهم هستند. اما استراتژیهای مختلفی برای بردن این بازی وجود دارد و بازیکنان میتوانند با تمرین، بهبود مهارتهای خود را در این بازی ارتقا دهند.
import tkinter as tk
from tkinter import messagebox
import random
def check_winner(board, player):
# Check rows, columns, and diagonals for a win
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True
return False
def is_board_full(board):
return all(all(cell != ' ' for cell in row) for row in board)
def minimax(board, depth, is_maximizing):
if check_winner(board, 'X'):
return -1
if check_winner(board, 'O'):
return 1
if is_board_full(board):
return 0
if is_maximizing:
max_eval = float('-inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
eval = minimax(board, depth + 1, False)
board[i][j] = ' '
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
eval = minimax(board, depth + 1, True)
board[i][j] = ' '
min_eval = min(min_eval, eval)
return min_eval
def best_move(board):
best_val = float('-inf')
best_move = None
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
move_val = minimax(board, 0, False)
board[i][j] = ' '
if move_val > best_val:
best_val = move_val
best_move = (i, j)
return best_move
def make_move(row, col):
if board[row][col] == ' ':
board[row][col] = 'X'
buttons[row][col].config(text='X')
if check_winner(board, 'X'):
messagebox.showinfo("Tic-Tac-Toe", "You win!")
root.quit()
elif is_board_full(board):
messagebox.showinfo("Tic-Tac-Toe", "It's a draw!")
root.quit()
else:
ai_move()
else:
messagebox.showerror("Error", "Invalid move")
def ai_move():
row, col = best_move(board)
board[row][col] = 'O'
buttons[row][col].config(text='O')
if check_winner(board, 'O'):
messagebox.showinfo("Tic-Tac-Toe", "AI wins!")
root.quit()
elif is_board_full(board):
messagebox.showinfo("Tic-Tac-Toe", "It's a draw!")
root.quit()
root = tk.Tk()
root.title("Tic-Tac-Toe")
board = [[' ' for _ in range(3)] for _ in range(3]
buttons = []
for i in range(3):
row_buttons = []
for j in range(3):
button = tk.Button(root, text=' ', font=('normal', 30), width=5, height=2, command=lambda row=i, col=j: make_move(row, col))
button.grid(row=i, column=j)
row_buttons.append(button)
buttons.append(row_buttons)
root.mainloop()
شاید این مطلب هم برای شما جالب باشد:
کتاب تمرینات پایتون



