Jump to content
أوفيسنا

امثلة من مصادر شتى للبايثون


Recommended Posts

السلام عليكم 

رغم ان اهل الخبرات في البرمجة يعتبروا البايثون من اسهل اللغات تعلما

الا اني وجدت صعوبة في تعلمها واعتبر نفسي مبتديء فيها وعندي مخزون من الامثلة 

التي اخذتها من مصادر شتى فاحييت ان اشارككم قيها لعل احد يستفيد منها

 قبل كل شيء افضل من وجدته شرخ البايثون للنبتدئين اليوتيوبر احمد عز

البايثون من الصفر

 افضل موقع لطرح الاسئل والتفاعل

وجدته على التيليجرام

عربي هناك حواي 10000مشترك

https://t.me/arabipython

انجليزي هناك حوالي 80000مشترك

https://t.me/Python

نعود للامثلة

المثال الاول 

للفرز التصاعدي للارقام استخدم

def selectionsort(alist):
    for i in range(len(alist)):
        minpos= i
        for j in range(i+1,len(alist)):
            if alist[minpos] > alist[j]:
                minpos= j
        alist[i], alist[minpos] = alist[minpos], alist[i]
    
    return alist
print(selectionsort([8,9,7,0,22.55,87,34]))

 

Link to post
Share on other sites

مثال 2

سبع محاولات لتخمين الرقم من1 الى 99

import random
#قم باستيراد مكتبة random
y=0
n = random.randint(1, 99)
guess = int(input("معك سبع محاولات لتخمن الرقم من 1الى 99 "))
while n != "guess" :
    y+= 1
    if y ==7:
        print("لقد استنفدت محاولاتك السبع")
        break
    if guess < n:
        print ("اختر رقم اكبر")
        guess = int(input("Enter an integer from 1 to 99: "))
    elif guess > n:
        print ("اختر رقم اصغر")
        guess = int(input("Enter an integer from 1 to 99: "))
    else:
        print ("لقد نجحت في معرفة الرقم")
        break

 

Link to post
Share on other sites

طرق اسيدال االكلمات والاحرف

#1
s="ayman"
e=  s.replace('ay', 'mr.ay')       # string in S with another
print(e)
#-------------------------------------
#2
o='Hello, ayman!'.translate(str.maketrans(',!', ';>' ))#استبدال الحرفالاول بالثاني
print(o)
#-------------
#3
tr = str.maketrans(',s', ';d', '!')#استبدال الحرف االاول بالثاني وحذف الثالث
z='Hello,sr ayman!'.translate(tr)
print(z)
#--------------------------------------------------------
#4
p='Hello,s ayman!'.translate(str.maketrans({',': '>>>>>','s': 'mrs',}))#استبدال الحرف باكثر من حرف
print(p)


 

Link to post
Share on other sites

ادخال علامات الطلاب واخراج النتائج 


l2 = []
l1 =[]
final=0
for _ in range(int(input("كم عدد الطلاب المراد ادخالهم:"))):


        name = input("اسم الطالب:")
        marks = float(input("علامة الرياضيات"))
        marks1 = float(input("علامة الفيزياء"))
        marks2 = float(input("علامة الكيمياء"))
        calc=(marks+marks1+marks2)/3
        final = '{0:.3g}'.format(calc)
        l2.append(name)
        l2.append(final)

        l1.append([name,final])

        l2.clear()

print("*"*11+"النتائج"+"*"*11)
print(l1)

كمثال

الادخالات

كم عدد الطلاب المراد ادخالهم:3
اسم الطالب:ايمن
علامة الرياضيات99
علامة الفيزياء91.6
علامة الكيمياء95.8
اسم الطالب:عماد
علامة الرياضيات66.8
علامة الفيزياء61
علامة الكيمياء62
اسم الطالب:سامر
علامة الرياضيات88
علامة الفيزياء88.6
علامة الكيمياء81
المخرجات

***********النتائج***********
[['ايمن', '95.5'], ['عماد', '63.3'], ['سامر', '85.9']]
 

Link to post
Share on other sites

المثالي التالي يخص الاحتمالات

فمثلا كلمة جبر يمكن كتابة الاحرف الخاصةبها-جبر-جرب-رجي-ربج-بجر-برج

في الاحصاء=مضروب الرقم

يعني جبر 3 احرف

مضروبها 3*2*1

الاجابة ستة احتمالات 

في البايثون نستطيع طباعة احتمالات لاي كلمة باستخدام مكتبة

from itertools import permutations
def allPermutations(str):
    # Get all permutations of string 'ABC'
    permList = permutations(str)
    # print all permutations==

    tt=0
    for perm in list(permList):
        tt=tt+1
        print(tt,''.join(perm))
str = 'ايمن'
allPermutations(str)

المخرجات

ايمن 4 احرف مضروب ال 4 

4*3*2*1

24 احتمال

ستراها عند تطبيق المثال

Link to post
Share on other sites
  • 2 weeks later...

 لعبة حجر ورقة مقص

تلعب ثلاثةجولا ت مع الكمبيوتر 

 

# -*- coding:utf-8 -*-
import random
ywins = 0
cwins = 0
i = 1
print("لديك ثلاثة جولات مع الكمبيوتر للعب")
# functions for printing
def you_won():
    print("لقد فزت بالجولة ")
    global ywins
    ywins = ywins + 1
def c_won():
    print("لقد فاز الكمبيوتر بالجولة")
    global cwins
    cwins = cwins + 1

def you_l():
    print("\nلقد خسرت اللعبة")
def c_l():
    print("\nلقد فزت باللعبة")
#logic
while(i<=3):
    you = input("\nاختر 1 = حجر, 2 = ورقة , 3 = مقص:")
    if you == "1":
         print("لقد اخترت حجر")
    if you == "2":
        print("لقد اخترت ورقة")
    if you == "3":
        print("لقد اخترت مقص")
    options = ["حجر","ورقة","مقص"]
    computer = random.choice(options)
    print("الكمبيوتر اختار",computer)
    if computer == "حجر" and you == "1" or computer == "ورقة" and you == "2" or computer == "مقص" and you == "3":
        print("تعادل")
    elif computer == "حجر" and you == "2":
        you_won()
    elif computer == "حجر" and you == "3":
        c_won()
    elif computer == "ورقة" and you == "1":
        c_won()
    elif computer == "ورقة" and you == "3":
        you_won()
    elif computer == "مقص" and you == "1":
        you_won()
    elif computer == "مقص" and you == "2":
        c_won()
    else:
        print("ادخال خاطيء اختر (1) او (2) او (3) فقط")
        continue

    i = i + 1

#results
print("\nلقد فاز الكمبيوتر",cwins,"عدد من المرات")
print("لقد فزت",ywins,"عدد من المرات")

#declaration
if cwins > ywins:
    you_l()
elif ywins > cwins:
    c_l()

 

Link to post
Share on other sites

لعبة اكس  او


#VALUE!
import random
#VALUE!
def drawBoard(board):
    # This function prints out the board that it was passed.
#VALUE!
    # "board" is a list of 10 strings representing the board (ignore index 0)
#VALUE!
    print('   |   |')
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
    print('   |   |')
#VALUE!
def inputPlayerLetter():
    # Let's the player type which letter they want to be.
    # Returns a list with the player's letter as the first item, and the computer's letter as the second.
#VALUE!
    letter = ''
    while not (letter == 'X' or letter == 'O'):
        print('اختر ان تكون X او O؟')
        letter = input().upper()
#VALUE!
    # the first element in the list is the player's letter, the second is the computer's letter.
#VALUE!
    if letter == 'X':
        return ['X', 'O']
    else:
        return ['O', 'X']
#VALUE!
def whoGoesFirst():
    # Randomly choose the player who goes first.
    if random.randint(0, 1) == 0:
        return 'computer'
    else:
        return 'player'
#VALUE!
def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
#VALUE!
    print('هل تريد اعادة اللعبة؟ (yes or no)')
    return input().lower().startswith('y')
#VALUE!
def makeMove(board, letter, move):
    board[move] = letter
#VALUE!
def isWinner(bo, le):
    # Given a board and a player's letter, this function returns True if that player has won.
#VALUE!
    # We use bo instead of board and le instead of letter so we don't  have to type as much.
#VALUE!
    return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
#VALUE!
   (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
#VALUE!
    (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
#VALUE!
    (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
#VALUE!
    (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
    (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
#VALUE!
    (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
    (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
#VALUE!
def getBoardCopy(board):
    # Make a duplicate of the board list and return it the duplicate.
    dupeBoard = []
#VALUE!
    for i in board:
        dupeBoard.append(i)
#VALUE!
    return dupeBoard
#VALUE!
def isSpaceFree(board, move):
    # Return true if the passed move is free on the passed board.
    return board[move] == ' '
#VALUE!
def getPlayerMove(board):
    # Let the player type in his move.
    move = ' '
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
#VALUE!
        print('اختر من 1-9 بحيث يبدأ ترتيب المربعات الاول1 اسفل الشمال والاخير اول يمين9')
        move = input()
    return int(move)
#VALUE!
def chooseRandomMoveFromList(board, movesList):
    # Returns a valid move from the passed list on the passed board.
    # Returns None if there is no valid move.
    possibleMoves = []
    for i in movesList:
        if isSpaceFree(board, i):
            possibleMoves.append(i)
#VALUE!
    if len(possibleMoves) != 0:
        return random.choice(possibleMoves)
    else:
        return None
#VALUE!
def getComputerMove(board, computerLetter):
    # Given a board and the computer's letter, determine where to move and return that move.
#VALUE!
    if computerLetter == 'X':
        playerLetter = 'O'
    else:
        playerLetter = 'X'
#VALUE!
    # Here is our algorithm for our Tic Tac Toe AI:
    # First, check if we can win in the next move
    for i in range(1, 10):
        copy = getBoardCopy(board)
        if isSpaceFree(copy, i):
            makeMove(copy, computerLetter, i)
            if isWinner(copy, computerLetter):
                return i
#VALUE!
    # Check if the player could win on his next move, and block them.
    for i in range(1, 10):
        copy = getBoardCopy(board)
        if isSpaceFree(copy, i):
            makeMove(copy, playerLetter, i)
            if isWinner(copy, playerLetter):
                return i
#VALUE!
    # Try to take one of the corners, if they are free.
    move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
    if move != None:
        return move
#VALUE!
    # Try to take the center, if it is free.
    if isSpaceFree(board, 5):
        return 5
#VALUE!
    # Move on one of the sides.
    return chooseRandomMoveFromList(board, [2, 4, 6, 8])
#VALUE!
def isBoardFull(board):
    # Return True if every space on the board has been taken. Otherwise return False.
#VALUE!
    for i in range(1, 10):
        if isSpaceFree(board, i):
            return False
    return True
#VALUE!
#VALUE!
print('Welcome to Tic Tac Toe!')
#VALUE!
while True:
    # Reset the board
    theBoard = [' '] * 10
    playerLetter, computerLetter = inputPlayerLetter()
    turn = whoGoesFirst()
    print('The ' + turn + ' will go first.')
    gameIsPlaying = True
#VALUE!
    while gameIsPlaying:
        if turn == 'player':
            # Player's turn.
            drawBoard(theBoard)
            move = getPlayerMove(theBoard)
            makeMove(theBoard, playerLetter, move)
#VALUE!
            if isWinner(theBoard, playerLetter):
                drawBoard(theBoard)
                print('لقد ربحت!')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('النتيجة تعادل!')
                    break
                else:
                    turn = 'computer'
#VALUE!
        else:
            # Computer's turn.
            move = getComputerMove(theBoard, computerLetter)
            makeMove(theBoard, computerLetter, move)
#VALUE!
            if isWinner(theBoard, computerLetter):
                drawBoard(theBoard)
                print('الكمبيوتر ربح.')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('النتيجة تعادل!')
                    break
                else:
                    turn = 'player'
#VALUE!
    if not playAgain():
        break

 

Link to post
Share on other sites

 لمعرفة مالك الموقع الالكنروني تستخدم whois

يجب ان تنزل المكتبة من cmd

pip install python-whois

 

دعونا ننظركمثال الموقع اوفيسنا

import whois
print(whois.whois('www.officena.net'))

النتيجة

{
  "domain_name": [
    "OFFICENA.NET",
    "officena.net"
  ],
  "registrar": "Onlinenic Inc",
  "whois_server": "whois.onlinenic.com",
  "referral_url": null,
  "updated_date": [
    "2020-08-12 08:56:12",
    "2020-08-12 04:56:00"
  ],
  "creation_date": [
    "2008-11-01 07:56:39",
    "2008-11-01 04:00:00"
  ],
  "expiration_date": [
    "2021-11-01 08:56:39",
    "2021-11-01 04:00:00"
  ],
  "name_servers": [
    "NS1.OFFICENA.NET",
    "NS2.OFFICENA.NET",
    "ns1.officena.net",
    "ns2.officena.net"
  ],
  "status": "clientTransferProhibited https://icann.org/epp#clientTransferProhibited",
  "emails": [
    "abuse@onlinenic.com",
    "mtarafa2@gmail.com"
  ],
  "dnssec": "unsigned",
  "name": "Mohamed Arafa",
  "org": "officena",
  "address": "pobox 36953 Dubai UAE",
  "city": "Dubai",
  "state": "Dubai",
  "zipcode": "36953",
  "country": "AE"
}

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...