با سلام خدمت خوانندگان عزیز ؛ در این مقاله قصد داریم تعدادی از مثال ها / کد ها و سورس های زبان برنامه نویسی 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_far
در این کد، 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 = [۱۰, ۱۱, ۱۲, ۱۳, ۱۴, ۱۵] print(Reverse(lst)) |
معکوس کردن لیست با روشی دیگر
۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ |
# Reversing a tuple using slicing technique # New tuple is created def Reverse(tuples): new_tup = tuples[::-۱] 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 = "(۱, ۳, ۴), (۵, ۶, ۴), (۱, ۳, ۶)" # 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 : (۱, ۳, ۴), (۵, ۶, ۴), (۱, ۳, ۶) List after conversion from string : [(۱, ۳, ۴), (۵, ۶, ۴), (۱, ۳, ۶) |
محاصبه مصاحت دایره با پایتون:
۱ ۲ |
s = (a+b+c)/۲ area = √(s(s-a)*(s-b)*(s-c)) |
کد برنامه
۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ ۱۰ ۱۱ ۱۲ ۱۳ ۱۴ ۱۵ ۱۶ ۱۷ |
# Python Program to find the area of triangle a = ۵ b = ۶ c = ۷ # 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) / ۲ # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** ۰.۵ print('The area of the triangle is %0.2f' %area) |
Output
۱ |
<samp>The area of the triangle is</samp> |
فاکتوریل با پایتون
۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ ۱۰ ۱۱ ۱۲ ۱۳ ۱۴ ۱۵ ۱۶ ۱۷ |
# change the value for a different result num = ۷ # To take input from the user #num = int(input("Enter a number: ")) factorial = ۱ # check if the number is negative, positive or zero if num < ۰: print("Sorry, factorial does not exist for negative numbers") elif num == ۰: print("The factorial of 0 is 1") else: for i in range(۱,num + ۱): 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 = ۰, ۱ count = ۰ # check if the number of terms is valid if nterms <= ۰: print("Please enter a positive integer") elif nterms == ۱: 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 += ۱ |
مثله ۸ وزیر با پایتون (ملکه)
۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ ۱۰ ۱۱ ۱۲ ۱۳ ۱۴ ۱۵ ۱۶ ۱۷ ۱۸ ۱۹ ۲۰ ۲۱ ۲۲ ۲۳ ۲۴ ۲۵ ۲۶ ۲۷ ۲۸ |
BOARD_SIZE = ۸ class BailOut(Exception): pass def validate(queens): left = right = col = queens[-۱] for r in reversed(queens[:-۱]): left, right = left-۱, right+۱ 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-۱) 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(۱۶۳) # read the 2 bytes a = img_file.read(۲) # calculate height height = (a[۰] << ۸) + a[۱] # next 2 bytes is width a = img_file.read(۲) # calculate width width = (a[۰] << ۸) + a[۱] print("The resolution of the image is",width,"x",height) jpeg_res("img1.jpg") |
Output
۱ |
<samp>The resolution of the image is ۲۸۰ x ۲۸۰</samp> |
کد بازی حدس زدن شماره با پایتون
۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ ۱۰ ۱۱ ۱۲ ۱۳ ۱۴ ۱۵ ۱۶ ۱۷ ۱۸ ۱۹ ۲۰ ۲۱ ۲۲ ۲۳ ۲۴ ۲۵ ۲۶ ۲۷ ۲۸ |
import random guesses_made = ۰ name = input('Hello! What is your name?\n') number = random.randint(۱, ۲۰) print ('Well, {0}, I am thinking of a number between 1 and 20.'.format(name)) while guesses_made < ۶: guess = int(input('Take a guess: ')) guesses_made += ۱ 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)) |
شاید این مطلب هم برای شما جالب باشد:
کتاب تمرینات پایتون

All Comments:
سلام، میخواستم از سایت خوبتون تشکر کنم
ممنون که مارو حماییت میکنین
محاصبه مصاحت!!!!!!!!!!واقعاا😂😂
سلام خسته نباشید ببخشید میخواستم سورس کد ها رو ذخیره کنیم، میشه آپ برای دخیره بهم معرفی کنید