اذهب الي المحتوي
أوفيسنا

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


محب العقيدة

الردود الموصى بها

السلام عليكم 

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

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

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

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

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

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

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

عربي هناك حواي 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]))

 

رابط هذا التعليق
شارك

مثال 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

 

رابط هذا التعليق
شارك

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

#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)


 

رابط هذا التعليق
شارك

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


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']]
 

رابط هذا التعليق
شارك

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

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

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

يعني جبر 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 احتمال

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

رابط هذا التعليق
شارك

  • 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()

 

رابط هذا التعليق
شارك

لعبة اكس  او


#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

 

رابط هذا التعليق
شارك

 لمعرفة مالك الموقع الالكنروني تستخدم 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"
}

 

  • Thanks 1
رابط هذا التعليق
شارك

للتاكيد من الخروج من التطبيق او البرنامج

# -*- coding:utf-8 -*-
def check_if_user_has_finished():

  ok_to_finish = True
  user_input_accepted = False
  while not user_input_accepted:
        user_input = input('هل تريدالخروج من البرنامج (نعم/لا): ')
        if user_input == 'نعم':
           user_input_accepted = True
           exit()
        elif user_input == 'لا':
           ok_to_finish = False
           user_input_accepted =  True

        else:
            print('اكتب (نعم اولا),اعد من فضلك ')
  return ok_to_finish
check_if_user_has_finished()
print("انت باق في البرنامج")

 

رابط هذا التعليق
شارك

كيفية التامل مع الملفات النصية من انشاء وقراءة ونقلها

obFichier = open('abc.txt','a')
obFichier.write("انا من موقع اوفيسنا !\n")
obFichier.write("منتدى بايثون امثلة متعددة للبايثون ")
obFichier.close()
ofi = open('abc.txt', 'r')#انشاءملف نصي abc
t = ofi.read(7)#طباعة اول 7 احرف من الملف
print(t)
t = ofi.read(5)#طباعة ال5 احرف التالية
print(t)
t=ofi.readline()#قراءة ما تبقى من السطر
print(t)
ofi.close()
def copy(source="abc.txt", destination="abcde.txt"):# نقل الملفabc الى ملف abcde
    fs = open(source, 'r')
    fd = open(destination, 'w')
    while 1:
        txt = fs.read(5)#كل مرة نفل 5 حرف

        if txt =="":
            break

        fd.write(txt)
    fs.close()
    fd.close()
    return
copy()

 

رابط هذا التعليق
شارك


  import pytube

video_url = 'https://www.youtube.com/watch?v=MJkDD1nK7l8' # ضع الرابط
youtube = pytube.YouTube(video_url)
video = youtube.streams.first()
video.download(r'C:\Users\aymjan\PycharmProjects\example') # ضع مكان التنزبل.

للتنزيل من اليوتيوب بدون برامج

  • Thanks 1
رابط هذا التعليق
شارك

 فك الملف المضغوط

اذا كان عليه كلمة سر ونسيتها

هنا مثال بسيط لالية عمل قائمة كلمات المرور وتمريها على الملف لمحاولة فتحه

في المرفقات ملف نصي وملف مضغوط وهناك كلمةمرور وهي

1111177777

كون المنتدى لا يقبل في المرفقات ملف نصي 

قمت بضغطه

1قم بفك الصغط عن الملف النصي

2ضع الملفين TT.zip & dictionary.txt

في نفس البروجكت اوالمشروع 

اتشئ ملف بايثون في المشروع وضع الكود التالي

# -*- coding:utf-8 -*-
import zipfile
zFile = zipfile.ZipFile('TT.zip')
passFile = open('dictionary.txt')
for line in passFile.readlines():
 password = line.strip('\n')
 try:
   zFile.extractall(pwd=bytes(password, 'utf-8'))
   print ('[+] كلمة المرور هي = ' + password + '\n')
   exit(0)
 except Exception as e:
     pass
 if len(password)==0:
     print("كلمة غير موجودة")

طبعا هنا يقرا الكلمات في الملف النصي كلمة تلو الاخرى

هناك كود اخر لقراة الملف برمته

اذا اردتموه ارفقه لكم

 

TT.zip dictionary.zip

  • Thanks 1
رابط هذا التعليق
شارك

  • 3 weeks later...

مثال على اخطاء الادخال

exception

# -*- coding:utf-8 -*-
import math
t=2
while t==2:
   try:
     y=float(input('ادخل الرقم لاول'))
     r=float(input('ادخل الرقم الثاني'))
     t=1
   except ValueError:
     print('يسمح بادخال رقم فقط جرب مرة اخرى')

try:
   z=float(y)/float(r)
except ZeroDivisionError as err:#اذا كانت القسمة على صفر
   z='خطا القسمة على صفر لقد كان الرقم الثاني قيمته صفر '
print('نتيجة قسمة',y,'على',r,'=',z)

 

رابط هذا التعليق
شارك

تلوين المخرجات باستخدام مكتبة colorama

# -*- coding:utf-8 -*-
from colorama import init, Fore, Back, Style
init(autoreset=True)

messages =   [
    'ايمن',
    (Fore.RED + Style.BRIGHT
        +  'انتبه!!!'),
    (Fore.GREEN + Style.BRIGHT
        +  'انتبه!!!')
]

for m in messages:
    print(m)

 

رابط هذا التعليق
شارك

هذا اهم مثال للذين لا يعرفون وظيفة الconstractor

وكيفة اخذ المعلومات المستقبلة وفلترتها

# -*- coding:utf-8 -*-
class Person:
 def __init__(self, name, age):
 self._name = name
 self._age = age
 def get_age(self):
 return self._age
 def set_age(self, new_age):
 if (isinstance(new_age,int) and new_age > 0 and new_age < 120): self._age =
new_age
 def get_name(self):
 return self._name
 def set_name(self,new_name):
 if str.isalpha(new_name):
 self._name=new_name
 def __str__(self):
 return 'Person[' + str(self._name) +'] is ' +str(self._age)
person = Person("AYMAN",33)
طباعةالعمر ولاسم القدیم#(person(print
person.set_age(75)#120 و الصفر بین لانھ العمر سیاخذ ھنا person.set_name("33")#
لن یاخذ الاسم الجدید لانھ رقم ولیس نص
print(person)
person = Person("AYMAN",33)
لن یاخذھنا سیاخذ العمر الجدید لانھ لیس بین الصفر و 120)#125(age_set.person
ایمن")# یاخذ الاسم الجدید لانھ رقم ولیس نصن")name_set.person
print(person)
person = Person("AYMAN",33)
لن یاخذھنا سیاخذ العمر الجدید لانھ لیس بین الصفر و 120)#200(age_set.person
لن یاخذھنا سیاخذ العمر الجدید لانھ لیس بین الصفر و 120")#77("name_set.person
print(person)

 

New Document.pdf

  • Thanks 1
رابط هذا التعليق
شارك

  • 3 weeks later...

لنفرض عمل برنامج لمطعم

# -*- coding:utf-8 -*-
MENU = {'sandwich': 10, 'tea': 7, 'salad': 9}

def restaurant():
 total = 0
 while True:
    order = input('Order: ').strip()
    if not order:
        break
    if order in MENU:
         price = MENU[order]
         total += price
         print(f'{order} is ${price}, المجموع الفرعي {total}$')

    else:
         print(f'الصنف {order} غير معرف ')

 print(f'المجموع {total}')
restaurant()

للتجربة ننفذ


Order: tea
tea is $7, المجموع الفرعي 7$
Order: sandwish
الصنف sandwish غير معرف 
Order: sandwich
sandwich is $10, المجموع الفرعي 17$
Order: 
المجموع 17

طبعا تستطيع حفظ البيانات في جدول

csv

او

json

رابط هذا التعليق
شارك

  • 2 weeks later...

اسنخراج اعلى او ادنى درجات التفييبم

# -*- coding:utf-8 -*-
import numpy as np
books = np.array([['ayman','Coffee Break NumPy', 4.6]
                     ,['sami','Lord of the Rings', 5.0]
                     ,['majid','Harry Potter', 4.3]
                     ,['amin','Winnie-the-Pooh', 3.9]
                     ,['talal','The earth', 5]
                     ,['ouda','Coffee Break Python', 4.7]])
predict_bestseller = lambda x, y : x[x[:,2].astype(float) > y]
print(predict_bestseller(books, 4.9))#اسماءالكتب التي خصلت على اعلى من 4.9

النتيجة

[['sami' 'Lord of the Rings' '5.0']
 ['talal' 'The earth' '5']]
 


inst = np.array([[23, "@instagram"],
[133, "@selenagomez"],
[59,"@victoriassecret"],
[76,"@nike"]])
superstars = inst[inst[:,0].astype(float) >= 133, 1]
print(superstars)
النتيجة
['@selenagomez']

 

للتاكد من كلمة هي نفسها فقط خدث خلط للاحرف

abc = lambda x1, x2: sorted(x1) == sorted(x2)


print(abc("slive", "lives"))
print(abc("elvise", "elives"))
print(abc("elvis", "elvi"))

النتيجة

True
True
False

رابط هذا التعليق
شارك

اسنخراج كلمة بعدد احرف مغين من نص

مثلا اكبر او تساوي10

text = '''
Call me Ishmael Some years ago - never mind how long precisel - having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and ...
. It is a way I have of driving-off the ..., and regulating
...'''

## One-Liner
w = [[x for x in line.split() if len(x)>=10] for line in text.split('\n')]

## Result
print(w)

النتيجة

[[], [], ['particular'], [], ['driving-off', 'regulating'], []]

رابط هذا التعليق
شارك

On 12/29/2020 at 8:56 PM, محب العقيدة said:

تلوين المخرجات باستخدام مكتبة colorama


# -*- coding:utf-8 -*-
from colorama import init, Fore, Back, Style
init(autoreset=True)

messages =   [
    'ايمن',
    (Fore.RED + Style.BRIGHT
        +  'انتبه!!!'),
    (Fore.GREEN + Style.BRIGHT
        +  'انتبه!!!')
]

for m in messages:
    print(m)

 

 

  • Thanks 1
رابط هذا التعليق
شارك

  • 3 weeks later...

لاستبدال النص باخر

# -*- coding:utf-8 -*-
import re

text = '''ذهب الرجل الى بيته و ركب الرجل سيارته '''
updated_text = re.sub("الرجل(?!')", 'ايمن امين', text)
print(updated_text)

النتيجة

ذهب ايمن امين الى بيته و ركب ايمن امين سيارته 

  • Like 1
رابط هذا التعليق
شارك

للتاكد من ادخل وقت صحيح اوخاطئ

# -*- coding:utf-8 -*-
import re
inputs = ['18:29', '24:59', 'UU', '02:01', '18:299', '99:99']
input_ok = lambda x: re.fullmatch('([01][0-9]|2[0-3]):[0-5][0-9]', x) != None
for x in inputs:
    print(input_ok(x))

النيجة

True
False
False
True
False
False

 

رابط هذا التعليق
شارك

مضروب العدد

n = 4
ay = lambda n: n * ay(n-1) if n > 1 else 1
print(ay(n))

النتيجة

24

 عرض جميع الاحتمالات

from functools import reduce
s = {1, 2, 3,4}
ps = lambda s: reduce(lambda P, x:P + [subset | {x} for subset in P], s,[set()])
print(ps(s))

النتيجة

[set(), {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}, {4}, {1, 4}, {2, 4},

{1, 2, 4}, {3, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}]

 

 

رابط هذا التعليق
شارك

Join the conversation

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

زائر
اضف رد علي هذا الموضوع....

×   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.

  • تصفح هذا الموضوع مؤخراً   0 اعضاء متواجدين الان

    • لايوجد اعضاء مسجلون يتصفحون هذه الصفحه
×
×
  • اضف...

Important Information