مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

طبقه بندی موضوعی
بایگانی

یک لیست داریم که میخواهیم به صورت انتخابی مرتب سازی اش کنیم. پس از اجرای برنامه سعی کنید برنامه را به گونه ای تغییر دهید که لیست را از کاربر بگیرد و مرتب اش کند.

# Selection sort in Python
# time complexity O(n*n)
#sorting by finding min_index
def selectionSort(array, size):
	
	for ind in range(size):
		min_index = ind

		for j in range(ind + 1, size):
			# select the minimum element in every iteration
			if array[j] < array[min_index]:
				min_index = j
		# swapping the elements to sort the array
		(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2, 45, 0, 11, -9,88,-97,-202,747]
size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)

موفق و پیروز باشید - سعید دامغانیان

۰ نظر موافقین ۰ مخالفین ۰ ۱۱ دی ۰۱ ، ۱۰:۴۰
سعید دامغانیان

برنامه ای بنویسید که یک عدد از کاربر گرفته و اگر تمامی ارقام این عدد مجزا بودند عبارت is lucky را چاپ کند و در غیر اینصورت is not lucky را چاپ کند. به عنوان مثال عدد 8596 باید خروجی is lucky برگرداند زیرا تمامی ارقام آن مجزا هستند ولی عدد 3663 بعلت تکرار ارقام خروجی is not lucky را برمیگرداند. اعدادی که تمامی ارقام آنها مجزا باشند را Lucky Number مینامیم.

# python program to check if a
# given number is lucky

import math

# This function returns true
# if n is lucky
def isLucky(n):
	
	# Create an array of size 10
	# and initialize all elements
	# as false. This array is
	# used to check if a digit
	# is already seen or not.
	ar = [0] * 10
	
	# Traverse through all digits
	# of given number
	while (n > 0):
		
		#Find the last digit
		digit = math.floor(n % 10)

		# If digit is already seen,
		# return false
		if (ar[digit]):
			return 0

		# Mark this digit as seen
		ar[digit] = 1

		# REmove the last digit
		# from number
		n = n / 10
	
	return 1

# Driver program to test above function.
arr = [1291, 897, 4566, 1232, 80, 700]
n = len(arr)

for i in range(0, n):
	k = arr[i]
	if(isLucky(k)):
		print(k, " is Lucky ")
	else:
		print(k, " is not Lucky ")
	
#SaeedDmn

برای تست فانکشنی که نوشتیم یک لیست از اعداد به عنوان ورودی تعریف کردیم. برنامه را به گونه ای تغییر دهید که عدد را از کاربر بگیرد.

۰ نظر موافقین ۰ مخالفین ۰ ۱۱ دی ۰۱ ، ۱۰:۳۶
سعید دامغانیان

برنامه ای که یک لیست اعداد (که درون خود برنامه تعریف شده اند) را به صورت درجی مرتب سازی میکند. سعی کنید برنامه را به گونه ای تغییر دهید که اعداد را از کاربر بگیرد. #پایتون 

# Python program for implementation of Insertion Sort
 
# Function to do insertion sort
def insertionSort(arr):
     
    if (n := len(arr)) <= 1:
      return
    for i in range(1, n):
         
        key = arr[i]
 
        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >=0 and key < arr[j] :
                arr[j+1] = arr[j]
                j -= 1
        arr[j+1] = key
 
 
#sorting the array [12, 11, 13, 5, 6] using insertionSort
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)

موفق و پیروز باشید - سعید دامغانیان

۰ نظر موافقین ۰ مخالفین ۰ ۱۱ دی ۰۱ ، ۱۰:۲۹
سعید دامغانیان

در این برنامه کاربردی به زبان پایتون یک bubble sort را پیاده سازی نموده ایم.

# Python program for implementation of Bubble Sort
 
def bubbleSort(arr):
    n = len(arr)
    # optimize code, so if the array is already sorted, it doesn't need
    # to go through the entire process
    swapped = False
    # Traverse through all array elements
    for i in range(n-1):
        # range(n) also work but outer loop will
        # repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n-i-1):
 
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1]:
                swapped = True
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
         
        if not swapped:
            # if we haven't needed to make a single swap, we
            # can just exit the main loop.
            return
 
 
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
 
bubbleSort(arr)
 
print("Sorted array is:")
for i in range(len(arr)):
    print("% d" % arr[i], end=" ")

به عنوان تمرین برنامه را به گونه ای تغییر دهید که اعداد را از کاربر دریافت کند. در برنامه بالا لیست اعداد درون خود برنامه تعریف شده است.

موفق و پیروز باشید. سعید دامغانیان

۰ نظر موافقین ۰ مخالفین ۰ ۱۱ دی ۰۱ ، ۱۰:۲۳
سعید دامغانیان

کد زیر یک عدد  رو از ورودی میگیره و جمله خواسته شده  سری فیبونانچی رو چاپ میکنه. دقت کنید که به صورت بازگشتی نوشته شده. سعی کنید روش غیر بازگشتی همین کد رو شما بنویسید.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


# Function for nth Fibonacci number 

  

def Fibonacci(n): 

    if n<0: 

        print("Incorrect input") 

    # First Fibonacci number is 0 

    elif n==1: 

        return 0

    # Second Fibonacci number is 1 

    elif n==2: 

        return 1

    else: 

        return Fibonacci(n-1)+Fibonacci(n-2) 

  

# Driver Program 


n=int(input("Pleas Enter n: "))  

print(Fibonacci(n)) 

  


#------------Telegram: @Ghoghnous_Iran-----------------------




b444745_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۳۹
سعید دامغانیان

برنامه ای نوشتم که تعدادی عدد رو داخل خود برنامه تعریف کرده و ســــپس با روش مرتب سازی حبابی مرتبشون کنه. حالا شما سعی کنید برنامه ای بنویسید که همین اعداد رو از ورودی گرفته و مرتب کنه. میتونید یک شرط بگذارید که اگه کاربر کاراکتر خاصی رو وارد کرد به معنای پایان اعداد  وارد شده باشه. یا میتونید اعداد رو یکجا بگیرید و پردازش کنید. اگه سوالی بود در خدمت هستم.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


def bubbleSort(arr):

    n = len(arr)

 

    # Traverse through all array elements

    for i in range(n):

 

        # Last i elements are already in place

        for j in range(0, n-i-1):

 

            # traverse the array from 0 to n-i-1

            # Swap if the element found is greater

            # than the next element

            if arr[j] > arr[j+1] :

                arr[j], arr[j+1] = arr[j+1], arr[j]

 

# Driver code to test above

arr = [64, 34, 25, 12, 22, 11, 90]

 

bubbleSort(arr)

 

print ("Sorted array is:")

for i in range(len(arr)):

    print ("%d" %arr[i])


#------------Telegram: @Ghoghnous_Iran-----------------------



a887838_Untitled.png


۰ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۲۸
سعید دامغانیان

برنامه زیر ضرائب معادله درجه 2 را گرفته و معادله را حل نموده و جوابهای معادله را در صورت حقیقی بودن نمایش می‌دهد. سعی کنید برنامه‌ای بنویسید که جوابهای موهمومی معادله را نیز محاسبه و چاپ کند.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


import math

a=int(input("Please Enter a: "))

b=int(input("Please Enter b: "))

c=int(input("Please Enter c: "))

delta=b*b-4*a*c

if delta==0 :

    x=(-b + math.sqrt(delta))

    print("Moadele Yek javab darad. X=",x)

elif delta<0:

    print("Moadele javabe haghighi nadarad!")

else :    

    x1=(-b + math.sqrt(delta))/(2*a)

    x2=(-b - math.sqrt(delta))/(2*a)

    print("Moadele 2 javab darad.\n X1= ",x1, "\nX2= " , x2)


#------------Telegram: @Ghoghnous_Iran-----------------------


 

h909262_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۰۵
سعید دامغانیان

در این پست آموزشی قصد دارم که ارسال ُ نوشتن و ویرایش یک پست الکترونیک را با هم ببینیم و همچنین بعد با پروتکلها و استاندارهایی همچون MIME  و ارسال نامه به این سبک را آموزش دهم. با من (سعید دامغانیان) همراه باشید...

در قطعه کد زیر اولاْ ارسال یک ایمیل ساده را بررسی کنید :

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

حال با استاندارد RFC822 آشنا شده و سپس کد زیر را بررسی کنید :

# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

حال نوبت رسیده کمی فراتر رفته و به استاندارد MIME بپردازیم. نوبت شماست ...

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

در قطعه کد زیر فصد داریم محتویات یک دایرکتوری را به استاندارد MIME ارسال کنیم...

#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)


if __name__ == '__main__':
    main()
در اینجا طریقه باز کردن ایمیل دریافتی مشابه بالا را در همان استاندارد بررسی خواهیم نمود 
#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()

در اینجا یک مثال که نحوه ایجاد یک پیام HTML با یک نسخه متنی ساده است را نوشته ایم. برای ایجاد چیزهای کمی جالب تر، ما یک تصویر مربوط به آن را در بخش HTML می نویسیم و یک کپی از آنچه که ما می خواهیم برای ارسال به دیسک داریم، و همچنین ارسال آن را ذخیره کرده ایم...

#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!</p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:{asparagus_cid}" />
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

اگر پیام از آخرین نمونه ای که نوشتم ارسال شد، در اینجا یکی از راه هایی است که می توانیم آن را پردازش کنیم:

import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser

# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser

# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = {}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display {}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display {}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    # The magic_html_parser has to rewrite the href="cid:...." attributes to
    # point to the filenames in partfiles.  It also has to do a safety-sanitize
    # of the html.  It could be written using html.parser.
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.

خروجی قطعه کد بالا را در ذیل ببینید :

To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>
Subject: Ayons asperges pour le déjeuner

Salut!

Cela ressemble à un excellent recipie[1] déjeuner.
۰ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۳:۳۲
سعید دامغانیان

  turtle و math  کدی نوشتم که شکل یک لانه ی زنبور را ترسیم کند. با استفاده از


# Hive

# By: Saeed Damghanian


from turtle import *

from math import *


def line(x, y, x2, y2):

    ''' Draw a line from (x, y) to (x2, y2) '''

    penup()

    goto(x, y)

    pendown()

    goto(x2, y2)



def draw_tree(x, y, size, angle,n):

    ''' Draw a tree of given size and angle at (x, y) '''

    if n==1:

        return

    if size < 4:

        return

    x2 = x + size * cos(radians(angle))

    y2 = y + size * sin(radians(angle))

    line(x, y, x2, y2)

    draw_tree(x2, y2, size , angle + 60,n-1)

    draw_tree(x2, y2, size , angle - 60,n-1)



# main program

#tracer(0,0)


#speed(10)

#delay(2)

draw_tree(0, 0, 50, 90,10)

mainloop()


u544287_Untitled.png

۲ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۱:۰۷
سعید دامغانیان

کدی که در ذیل مشاهده می‌کنید یک خورشید را به صورت خطهای هندسی رسم کرده و رنگ میزند. #جالبناک


from turtle import *

color('blue', 'yellow')

begin_fill()

while True:

    forward(200)

    left(100)

    if abs(pos()) < 1:

        break

end_fill()

done()


خروجی کد بالا شکلی مطابق ذیل است. با ما همراه شوید.. . مدرسه پایتون

n488379_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۰:۵۲
سعید دامغانیان