100% found this document useful (1 vote)
12 views464 pages

3 Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views464 pages

3 Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 464

Programare in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
Curs python complet
2.2 Tipuri de dateFişier
2.3 OperatoriFişier
2.4 Citiri. Scrieri
2.5 Structura secventiala
3.1 Instructiunea de decizie
Capitolul 4 - Instrucțiuni repetitive

4.1. Instructiunea While


4.2 Instructiunea For
Capitolul 5 - Tipuri structurate de date

5.1. Siruri de caractere


5.2 Lista
5.3 Tupluri
5.4 Dicționare
5.5. Fisiere
6.1 Subprogram
6.2 Modulul
Capitolul 7 - Programarea pe obiecte

7.1 POO_Notiuni de baza


7.2 Clasa
Capitolul 8 - Biblioteci

8.1 Biblioteci
9.1 Recursivitate
Instalarea programului python

1
2
3
4
Instalare Visual studio 15
tbe_ms_visual_studio_enterprise_x64_x86_with_update1

5
6
Se va activa

7
8
9
10
11
rularea unui program
Etapa 1
Configurarea visual studio v15

12
sa fiu conectat la internet

13
skip

14
Am ales versiunea 2.7 ca sa ruleze codul

15
update

16
click dreapta

17
SAU

18
19
20
IN VISUAL STUDIO 2013 AVEM

aleg open interactive windows din dreapta

21
22
23
Aplicatiile
Cu tasta enter se executa programul

24
APLICATII
Operatii cu numere
Python interactive window. Type $help for a list of commands.
>>> 2 + 2
4
>>> (50 - 5*6) / 4
5
>>> 17 // 3
5
>>> 17 % 3
2
>>> 5 ** 2
25
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
>>>
Stergerea ecranului

25
Siruri de caractere
>>> 'spam eggs'
'spam eggs'
>>> '"Yes," they said.'
'"Yes," they said.'
>>> '"Yes," they said.'
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'
>>> s
'First line.\nSecond line.'
>>> print(s)
First line.
Second line.
>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name
>>> # 3 times 'un', followed by 'ium'
...
>>> 3 * 'un' + 'ium'
'unununium'
>>> 'Py' 'thon'
'Python'

>>> prefix = 'Py'


>>> prefix + 'thon'
'Python'
>>> word = 'Python'
>>> word[0]
'P'
>>> word[-6]
'P'

26
>>> word[0:2]
'Py'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
>>> word[-2:]
'on'
>>> word[4:42]
'on'
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

>>> squares = [1, 4, 9, 16, 25]


>>> squares[0]
1
>>> squares[-3:]
[9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> cubes = [1, 8, 27, 65, 125]
>>> 4 ** 3
64
>>> cubes[3] = 64
>>> cubes
[1, 8, 27, 64, 125]
>>> cubes.append(216)
>>> cubes.append(7 ** 3)
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = []
>>> letters
[]
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

27
>>> i = 256*256
>>> print('The value of i is', i)
('The value of i is', 65536)

28
29
Setare pentru executare programe in python

30
C:\Python27

31
Envirnment variance

32
33
Aplicatii minimale

Aleg sa execut cu Pyton 2.7


Apasam de 2 ori enter pentru executarea sectiunii de program

34
>>> if x == 24:
... # un comentariu
... print "Salutari de pe www.invata-programare.ro."
...

Executia este mai jos


Salutari de pe www.invata-programare.ro.
>>>

Stergem ecranul

>>> sirdecaractere = 'Salut Invata-Programare'


>>> print sirdecaractere # scrie tot sirul de caractere pe ecran
Salut Invata-Programare
>>> print sirdecaractere [0] # scrie primul caracter din sir
S

35
>>> print sirdecaractere [2:5] # scrie pe ecran cracterele dintre pozitiile 3 si 5
lut
>>> print sirdecaractere [2:] # scrie pe cran toate caracterele incepand cu al 3-
lea
lut Invata-Programare
>>> print sirdecaractere * 2 # scrie sirul de caractere de 2 ori
Salut Invata-ProgramareSalut Invata-Programare
>>> print sirdecaractere + "TEST" # concateneaza sirurile de caractere
Salut Invata-ProgramareTEST
>>>
Liste
>>> lista = [ 'abcd', 123, 3.14, 'mihai', 2.81 ]
>>> listamica = [123, 'invata-programare']
>>> print lista # afiseaza toata lista pe ecran
['abcd', 123, 3.14, 'mihai', 2.81]
>>> print lista[0] # afiseaza primul element pe ecran
abcd
>>> print lista[1:3] # afiseaza elementele de la 2 pana la 3
[123, 3.14]
>>> print lista[2:] # afiseaza toate elementele incepand cu al 3-lea
[3.14, 'mihai', 2.81]
>>> print listamica * 2 # afiseaza lista de 2 ori
[123, 'invata-programare', 123, 'invata-programare']
>>> print lista + listamica # afiseaza listele concatenate
['abcd', 123, 3.14, 'mihai', 2.81, 123, 'invata-programare']
>>>
Dictionare

>>> dictionar = {}
>>> dictionar['unu'] = "Primul dictionar"
>>> dictionar[2] = "Urmatorul dictionar"
>>> dictionarmic = {'nume': 'mihai','varsta':23, 'site': 'www.cmconline.xyz'}
>>> print dictionar['unu'] # afiseaza valoarea acestui dictionar
Primul dictionar
>>> print dictionar[2] # afiseaza valoarea acestui dictionar
Urmatorul dictionar
>>> print dictionarmic # afiseaza tot dictionarul
{'nume': 'mihai', 'site': 'www.cmconline.xyz', 'varsta': 23}
>>> print dictionarmic.keys() # afiseaza cheile acestui dictionar
['nume', 'site', 'varsta']
>>> print dictionarmic.values() # afiseaza valoarile acestui dictionar
['mihai', 'www.cmconline.xyz', 23]
>>>
Siruri de caractere

>>> variabila1 = 'Salut'


>>> print "Noul sir de caractere: ", variabila1 + ' www.invata-programare.ro'
Noul sir de caractere: Salut www.invata-programare.ro
>>>
>>> variabila1 = 'Salut'
>>> print "Noul sir de caractere: ", variabila1 + ' www.invata-programare.ro'
Noul sir de caractere: Salut www.invata-programare.ro
>>> string_mare = """this is a long string that is made up of
... several lines and non-printable characters such as
... TAB ( \t ) and they will show up that way when displayed.
... NEWLINEs within the string, whether explicitly given like
... this within the brackets [ \n ], or just a NEWLINE within
... the variable assignment will also show up.
... """

36
...
>>> print string_mare
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.

>>>
print("Word counter")
sentence = input("Please enter a sentence to count the number of words. Press ENTER to
end the sentence:")
print("In this sentence, the number of words is:")
print(len(sentence.split(' ')))

REZULTA

Word counter
Please enter a sentence to count the number of words. Press ENTER to end the sentence:
In this sentence, the number of words is:
1

Structura decizionala

>>> var = 23
>>> if ( var == 23 ) : print "Salut!"
...
...
Salut!
>>> print "Pa!"
Pa!
>>>
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


return x / y

print("Python Calculator:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("What are we calculating today? (1, 2, 3, or 4):")


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))

37
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

REZULTA

Python Calculator:
1. Add
2. Subtract
3. Multiply
4. Divide
What are we calculating today? (1, 2, 3, or 4):1
Enter first number: 1
Enter second number: 2
1 + 2 = 3

Resetare in caz de eroare sau ciclu infinit

38
Adaugare si stergere dintr-o lista

>>> agenda = {'Andrew Parson':8806336,


... 'Emily Everett':6784346, 'Peter Power':7658344,
... 'Lewis Lame':1122345}
...
>>> print agenda['Lewis Lame']
1122345
>>> agenda['Gingerbread Man'] = 1234567
>>> del agenda['Andrew Parson']
>>>

>>> lunile_anului = ('Ianuarie','Februarie','Martie','Aprilie','Mai','Iunie',\


... 'Iulie','August','Septembrie','Octombrie','Noiembrie',' Decembrie')
...
>>> pisici = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
>>> print pisici[2]
Kitty
>>> pisici.append('Catherine')
>>> del pisici[1]
>>>
Instructiunea ciclica FOR

>>> newList = [45, 'mananca', 90210, "Buna dimineata", -67]


>>> # creeaza bucla:
... # Parcurge newList si pune fiecare element
... # in variabila value si afiseaz-o
... for value in newList:
... print value
...
45
mananca
90210
Buna dimineata
-67
>>>

39
def main():
# define a list of days in English and French
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
daysFr = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]

# use iter to create an iterator over a collection


i = iter(days)
print(next(i)) # Sun
print(next(i)) # Mon
print(next(i)) # Tue

# iterate using a function and a sentinel


with open("testfile.txt", "r") as fp:
for line in iter(fp.readline, ''):
print(line)

# use regular interation over the days


for m in range(len(days)):
print(m+1, days[m])

# using enumerate reduces code and provides a counter


for i, m in enumerate(days, start=1):
print(i, m)

# use zip to combine sequences


for m in zip(days, daysFr):
print(m)

for i, m in enumerate(zip(days, daysFr), start=1):


print(i, m[0], "=", m[1], "in French")

if __name__ == "__main__":
main()

REZULTA

Sun
Mon
Tue
This is line 1

This is line 2

This is line 3

This is line 4

This is line 5

This is line 6

(1, 'Sun')
(2, 'Mon')
(3, 'Tue')
(4, 'Wed')
(5, 'Thu')
(6, 'Fri')
(7, 'Sat')
(1, 'Sun')

40
(2, 'Mon')
(3, 'Tue')
(4, 'Wed')
(5, 'Thu')
(6, 'Fri')
(7, 'Sat')
('Sun', 'Dim')
('Mon', 'Lun')
('Tue', 'Mar')
('Wed', 'Mer')
('Thu', 'Jeu')
('Fri', 'Ven')
('Sat', 'Sam')
(1, 'Sun', '=', 'Dim', 'in French')
(2, 'Mon', '=', 'Lun', 'in French')
(3, 'Tue', '=', 'Mar', 'in French')
(4, 'Wed', '=', 'Mer', 'in French')
(5, 'Thu', '=', 'Jeu', 'in French')
(6, 'Fri', '=', 'Ven', 'in French')
(7, 'Sat', '=', 'Sam', 'in French')

def main():
# use any() and all() to test sequences for boolean values
list1 = [1, 2, 3, 0, 5, 6]

# any will return true if any of the sequence values are true
print(any(list1))

# all will return true only if all values are true


print(all(list1))

# min and max will return minimum and maximum values in a sequence
print("min: ", min(list1))
print("max: ", max(list1))

# Use sum() to sum up all of the values in a sequence


print("sum: ", sum(list1))

if __name__ == "__main__":
main()

REZULTA

True
False
min: 0
max: 6
sum: 17

n1 = 0
n2 = 1
count = 0

while count < 20:


print(n1)
n3 = n1 + n2
n1 = n2
n2 = n3
count += 1

41
REZULTA
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181

42
Rularea programelor ca module se face astfel
Click dreapta pe programul editat si salvat cu extensia .py

43
Deplasez paginile ca sa vad rezultatul rularii
Exersam sirul lui Fibonacci
n1 = 0
n2 = 1
count = 0

while count < 20:


print(n1)
n3 = n1 + n2
n1 = n2
n2 = n3
count += 1

44
C:\kit python\nou\python-course-downloads\python_course\functions\lessons

def get_name():
"""Get and return a name"""
name = input('What is your name? ')
return name

Determinarea daca un numar este impar

def is_odd(number):
"""Determine if a number is odd."""
if number % 2 == 0:
return False
else:
return True

print(is_odd(7))

============
sau
============

def odd_or_even(number):
"""Determine if a number is odd or even."""
if number % 2 == 0:
return 'Even'
else:
return 'Odd'

odd_or_even_string = odd_or_even(7)
print(odd_or_even_string)

45
Initiazarea se face si direct la apelul unei proceduri
def say_hi(first, last='Doe'):
print('Hi {} {}!'.format(first, last))

say_hi('Jane')
say_hi('John', 'Coltrane')

def say_hi(first, last):


print('Hi {} {}!'.format(first, last))

say_hi(first = 'Jane', last = 'Doe')


say_hi(last = 'Doe', first = 'John')

46
def say_hi(first, last):
print('Hi {} {}!'.format(first, last))

say_hi('Jane', 'Doe')

def say_hi(name = 'there'):


print('Hi {}!'.format(name))

say_hi()
say_hi('Jason')

47
def say_hi(name):
print('Hi {}!'.format(name))

say_hi('Jason')
say_hi('everybody')

def say_hi():
print('Hi!')

say_hi()

48
Apelul unei proceduri

def display_facts(facts):
"""Displays facts"""
for fact in facts:
print('{}: {}'.format(fact, facts[fact]))
print()

facts = {
'Jason': 'Can fly an airplane.',
'Jeff': 'Is afraid of clowns.',

49
'David': 'Plays the piano.'
}

display_facts(facts)

facts['Jeff'] = 'Is afraid of heights.'


facts['Jill'] = 'Can hula dance.'

display_facts(facts)

VARIALILE GLOBALE SI LOCALE IN CADRUL PROCEDURILOR

def demo_print_greeting():
print("TIK SI ADY!!")

def demo_local_variable():
a_variable = 7
a_variable ="TYK 007"
print(a_variable)

name = "NU CUNOSC"


def demo_global_variable():
global name
name = "TIK"
print(name + "aDy")

def main():
#demo_print_greeting()
#demo_local_variable()
demo_global_variable(); print(name)

50
if __name__ =="__main__":
main()

import math
# This is a single-line comment

This is an
example of a
multi-line comment

def demo_print_greeting():
print("Rise & Shine!!")

def demo_local_variable():

51
a_variable = 7
a_variable ="The name is 007"
print(a_variable)

name = "Unknown"
def demo_global_variable():
global name
name = "Paul"
print(name + "y")

def demo_arithmetic():
print("\nDemo Arithmetic\n")
print("7 + 2 =", 7+2)
print("7 - 2 =", 7-2)
print("7 * 2 =", 7*2)
print("7 / 2 =", 7/2)
print("7 % 2 =", 7%2)
print("7 ** 2 =", 7**2) #Power
print("7 // 2 =", 7//2) #Floor

print("math.floor(7/2) =", math.floor(7/2))


print("math.ceil(7/2) =", math.ceil(7/2))

def demo_order_of_operations():
print("\nDemo Order of Operations\n")
print("5+7-3*2 =", 5+7-3*2)
print("5+(7-3)*2 =", 5+(7-3)*2)

def main():
#demo_print_greeting()
#demo_local_variable()
#demo_global_variable(); print(name)
demo_arithmetic()
demo_order_of_operations()

if __name__ =="__main__":
main()

52
import math
# This is a single-line comment

This is an
example of a
multi-line comment

def demo_print_greeting():
print("Rise & Shine!!")

def demo_local_variable():
a_variable = 7
a_variable ="The name is 007"

53
print(a_variable)

name = "Unknown"
def demo_global_variable():
global name
name = "Paul"
print(name + "y")

def demo_arithmetic():
print("\nDemo Arithmetic\n")
print("7 + 2 =", 7+2)
print("7 - 2 =", 7-2)
print("7 * 2 =", 7*2)
print("7 / 2 =", 7/2)
print("7 % 2 =", 7%2)
print("7 ** 2 =", 7**2) #Power
print("7 // 2 =", 7//2) #Floor

print("math.floor(7/2) =", math.floor(7/2))


print("math.ceil(7/2) =", math.ceil(7/2))

def demo_order_of_operations():
print("\nDemo Order of Operations\n")
print("5+7-3*2 =", 5+7-3*2)
print("5+(7-3)*2 =", 5+(7-3)*2)

def demo_function_params(first,last):
print("The name is " + first + " " + last)

def demo_function_return(first, last):


full_name = first + " " + last
return "The full name is " + full_name

def demo_function_default(first = "Someone", last = "UnknownLast"):


full_name = first + " " + last
return "The full name is " + full_name

def demo_function_calls():
demo_function_params("James", "Bond") # executes function
print(demo_function_return("James", "Bond")) # prints returned value
print(demo_function_default(last="Bond")) # uses default value for 'first'
print(demo_function_return) # print object

def main():
#demo_print_greeting()
#demo_local_variable()
#demo_global_variable(); print(name)
#demo_arithmetic()
#demo_order_of_operations()
demo_function_calls()

54
if __name__ =="__main__":
main()

Ciclicitatea cu conditie de filtrare dintr-un vector de tip enumerare


contacts = {
'Jason': {
'phone': '555-0123',
'email': '[email protected]'
},
'Carl': {

55
'phone': '555-0987',
'email': '[email protected]'
}
}

for contact in contacts:


print("{}'s contact info:".format(contact))
print(contacts[contact]['phone'])
print(contacts[contact]['email'])

Enumerarea unor date referitoare la o entitate


contacts = {'Jason': '555-0123', 'Carl': '555-0987'}
for person, phone_number in contacts.items():
print('The number for {0} is {1}.'.format(person, phone_number))

56
Afisarea datelor unei structuri
contacts = {
'Jason': '555-0123',
'Carl': '555-0987'
}
for contact in contacts:
print('The number for {0} is {1}.'.format(contact, contacts[contact]))

Aparteneta unui element la o multime


contacts = {
'Jason': ['555-0123', '555-0000'],
'Carl': '555-0987'
}

print ('555-0987' in contacts.values())

57
Instructiunea conditionala de filtrare
contacts = {
'Jason': ['555-0123', '555-0000'],
'Carl': '555-0987'
}

if 'Jason' in contacts.keys():
print("Jason's phone number is:")
print(contacts['Jason'][0])

if 'Tony' in contacts.keys():
print("Tony's phone number is:")
print(contacts['Tony'][0])

58
Filtrare conditionala simpla
contacts = {
'Jason': ['555-0123', '555-0000'],
'Carl': '555-0987'
}

for number in contacts['Jason']:


print('Phone: {}'.format(number))

contacts = {
'Jason': ['555-0123', '555-0000'],
'Carl': '555-0987'
}
print('Jason:')
print(contacts['Jason'])
print('Carl:')
print(contacts['Carl'])

59
contacts = {'Jason': '555-0123', 'Carl': '555-0987'}
del contacts['Jason']
print(contacts)

contacts = {'Jason': '555-0123', 'Carl': '555-0987'}


contacts['Tony'] = '555-0570'
print(contacts)
print(len(contacts))

60
contacts = {'Jason': '555-0123', 'Carl': '555-0987'}
contacts['Jason'] = '555-0000'
jasons_phone = contacts['Jason']
print('Dial {} to call Jason.'.format(jasons_phone))

contacts = {'Jason': '555-0123', 'Carl': '555-0987'}


jasons_phone = contacts['Jason']
carls_phone = contacts['Carl']

print('Dial {} to call Jason.'.format(jasons_phone))


print('Dial {} to call Carl.'.format(carls_phone))

61
Instructiunea IF

age = 31
if age >= 35:
print('1.')
elif age >= 30:
print('2')
else:
print('3')

print('4!')

62
age = 31
if age >= 35:
print('1')
else:
print('2')

print('3!')

age = 31
if age >= 35:
print('You are old enough to be the President.')

print('Have a nice day!')

63
if 37 < 40:
print('Thirty-seven is less than forty.')

Instructiunea conditionala compusa

a_boolean = True
the_other_boolean = False
print(a_boolean)
print(the_other_boolean)

64
Rularea alegand visual studio

65
open active window

66
copiez in ferastra mica
apas enter si rulez

# Use special methods to compare objects to each other

class Employee():
def __init__(self, fname, lname, level, yrsService):
self.fname = fname
self.lname = lname
self.level = level
self.seniority = yrsService

# implement comparison functions by emp level


def __ge__(self, other):
if self.level == other.level:

67
return self.seniority >= other.seniority
return self.level >= other.level

def __gt__(self, other):


if self.level == other.level:
return self.seniority > other.seniority
return self.level > other.level

def __lt__(self, other):


if self.level == other.level:
return self.seniority < other.seniority
return self.level < other.level

def __le__(self, other):


if self.level == other.level:
return self.seniority <= other.seniority
return self.level <= other.level

def __eq__(self, other):


return self.level == other.level

def main():
# define some employees
dept = []
dept.append(Employee("Tim", "Sims", 5, 9))
dept.append(Employee("John", "Doe", 4, 12))
dept.append(Employee("Jane", "Smith", 6, 6))
dept.append(Employee("Rebecca", "Robinson", 5, 13))
dept.append(Employee("Tyler", "Durden", 5, 12))

# Who's more senior?


print(bool(dept[0] > dept[2]))
print(bool(dept[4] < dept[3]))

# sort the items


emps = sorted(dept)
for emp in emps:
print(emp.lname)

if __name__ == "__main__":
main()

68
Apoi rularea programelor se face astfel

69
# customize string representations of objects

class myColor():
def __init__(self):
self.red = 50
self.green = 75
self.blue = 100

# use getattr to dynamically return a value


def __getattr__(self, attr):
if attr == "rgbcolor":
return (self.red, self.green, self.blue)
elif attr == "hexcolor":
return "#{0:02x}{1:02x}{2:02x}".format(self.red, self.green, self.blue)
else:
raise AttributeError

# use setattr to dynamically return a value


def __setattr__(self, attr, val):
if attr == "rgbcolor":
self.red = val[0]
self.green = val[1]
self.blue = val[2]
else:
super().__setattr__(attr, val)

# use dir to list the available properties


def __dir__(self):
return ("rgbolor", "hexcolor")

70
def main():
# create an instance of myColor
cls1 = myColor()
# print the value of a computed attribute
print(cls1.rgbcolor)
print(cls1.hexcolor)

# set the value of a computed attribute


cls1.rgbcolor = (125, 200, 86)
print(cls1.rgbcolor)
print(cls1.hexcolor)

# access a regular attribute


print(cls1.red)

# list the available attributes


print(dir(cls1))

if __name__ == "__main__":
main()

REZULTATUL

71
# define enumerations using the Enum base class

from enum import Enum, unique, auto

@unique
class Fruit(Enum):
APPLE = 1
BANANA = 2
ORANGE = 3
TOMATO = 4
PEAR = auto()

72
def main():
# enums have human-readable values and types
print(Fruit.APPLE)
print(type(Fruit.APPLE))
print(repr(Fruit.APPLE))

# enums have name and value properties


print(Fruit.APPLE.name, Fruit.APPLE.value)

# print the auto-generated value


print(Fruit.PEAR.value)

# enums are hashable - can be used as keys


myFruits = {}
myFruits[Fruit.BANANA] = "Come Mr. Tally-man"
print(myFruits[Fruit.BANANA])

if __name__ == "__main__":
main()

REZULTATUL

73
# give objects number-like behavior

class Point():
def __init__(self, x, y):
self.x = x
self.y = y

def __repr__(self):
return "<Point x:{0},y:{1}>".format(self.x, self.y)

# implement addition
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)

74
# implement subtraction
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)

# implement in-place addition


def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self

def main():
# Declare some points
p1 = Point(10, 20)
p2 = Point(30, 30)
print(p1, p2)

# Add two points


p3 = p1 + p2
print(p3)

# subtract two points


p4 = p2 - p1
print(p4)

# Perform in-place addition


p1 += p2
print(p1)

if __name__ == "__main__":
main()

REZULTATUL ESTE

75
# give objects number-like behavior

class Point():
def __init__(self, x, y):
self.x = x
self.y = y

def __repr__(self):
return "<Point x:{0},y:{1}>".format(self.x, self.y)

# TODO: implement addition


def __add__(self, other):
pass

76
# TODO: implement subtraction
def __sub__(self, other):
pass

# TODO: implement in-place addition


def __iadd__(self, other):
pass

def main():
# Declare some points
p1 = Point(10, 20)
p2 = Point(30, 30)
print(p1, p2)

# TODO: Add two points

# TODO: subtract two points

# TODO: Perform in-place addition

if __name__ == "__main__":
main()

REZULATATUL
<Point x:10,y:20> <Point x:30,y:30>
# customize string representations of objects

class Person():
def __init__(self):
self.fname = "Joe"
self.lname = "Marini"
self.age = 25

# use __repr__ to create a string useful for debugging


def __repr__(self):
return "<Person Class - fname:{0}, lname:{1}, age{2}>".format(self.fname, self.lname,
self.age)

# use str for a more human-readable string


def __str__(self):
return "Person ({0} {1} is {2})".format(self.fname, self.lname, self.age)

# use bytes to convert the informal string to a bytes object


def __bytes__(self):
val = "Person:{0}:{1}:{2}".format(self.fname, self.lname, self.age)

77
return bytes(val.encode('utf-8'))

def main():
# create a new Person object
cls1 = Person()

# use different Python functions to convert it to a string


print(repr(cls1))
print(str(cls1))
print("Formatted: {0}".format(cls1))
print(bytes(cls1))

if __name__ == "__main__":
main()

REZULTATUL ESTE

<Person Class - fname:Joe, lname:Marini, age25>


Person (Joe Marini is 25)
Formatted: Person (Joe Marini is 25)
b'Person:Joe:Marini:25'

from collections import defaultdict

def main():
# define a list of items that we want to count
fruits = ['apple', 'pear', 'orange', 'banana',
'apple', 'grape', 'banana', 'banana']

# use a dictionary to count each element


fruitCounter = defaultdict(int)

# Count the elements in the list


for fruit in fruits:
fruitCounter[fruit] += 1

# print the result


for (k, v) in fruitCounter.items():
print(k + ": " + str(v))

if __name__ == "__main__":
main()

78
REZULTATUL
apple: 2
pear: 1
orange: 1
banana: 3
grape: 1

import collections
import string

def main():
# initialize a deque with lowercase letters
d = collections.deque(string.ascii_lowercase)

# deques support the len() function


print("Item count: " + str(len(d)))

# deques can be iterated over


for elem in d:
print(elem.upper(), end=",")

# manipulate items from either end


d.pop()
d.popleft()
d.append(2)
d.appendleft(1)
print(d)

# rotate the deque


print(d)
d.rotate(1)
print(d)

if __name__ == "__main__":
main()

REZULTAT

Item count: 26
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,deque([1, 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 2])
deque([1, 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 2])
deque([2, 1, 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y'])

FUNCTII

79
def myFunction(arg1, arg2=None):
print(arg1, arg2)

def main():
print(myFunction.__doc__)

if __name__ == "__main__":
main()

REZULTA

None
def myFunction(arg1, arg2, *, suppressExceptions=False):
print(arg1, arg2, suppressExceptions)

def main():
# try to call the function without the keyword
# myFunction(1, 2, True)
myFunction(1, 2, suppressExceptions=True)

if __name__ == "__main__":
main()

REZULTA
1 2 True

def CelsisusToFahrenheit(temp):
return (temp * 9/5) + 32

def FahrenheitToCelsisus(temp):
return (temp-32) * 5/9

def main():
ctemps = [0, 12, 34, 100]
ftemps = [32, 65, 100, 212]

# Use regular functions to convert temps


print(list(map(FahrenheitToCelsisus, ftemps)))

80
print(list(map(CelsisusToFahrenheit, ctemps)))

# Use lambdas to accomplish the same thing


print(list(map(lambda t: (t-32) * 5/9, ftemps)))
print(list(map(lambda t: (t * 9/5) + 32, ctemps)))

if __name__ == "__main__":
main()

REZULTA
[0.0, 18.333333333333332, 37.77777777777778, 100.0]
[32.0, 53.6, 93.2, 212.0]
[0.0, 18.333333333333332, 37.77777777777778, 100.0]
[32.0, 53.6, 93.2, 212.0]

liste

def demo_if():
testGrade = 95

# Ex: if
if testGrade>85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: elif
if testGrade > 94:
print("You did awesome!")
elif testGrade > 85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: multiple operators


if ((testGrade >= 90) and (testGrade <= 95)):
print("You almost reached excellence!")

def demo_lists():
#Create, print entire list & just first friend
print('Create, print entire list & just first friend')
print('---------------------------------------------')
friend_list = ['Sky', 'Marcel', 'Robin',
'Khaleel', 'Connie']
print('All Friends =', friend_list)
print('First Friend =', friend_list[0])

#Change value

81
friend_list[0] = "Taylor"
print('First Friend with name change =', friend_list[0])

#Print partial list


print('Partial list of friends =' + str(friend_list[2:5]))

#List within lists


family_list = ['Mom', 'Dad', 'Cousin']
people_list = [friend_list,family_list]
print('\nWrite out people_list:')
print('-----------------------')
print(people_list)
print('\nWrite 3rd element from 2nd list:')
print('-----------------------------------')
print('Third person in 2nd list is:' + (people_list[1][2]))

def main():
#demo_if()
demo_lists()

if __name__ =="__main__":
main()

82
def demo_if():
testGrade = 95

# Ex: if
if testGrade>85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: elif
if testGrade > 94:

83
print("You did awesome!")
elif testGrade > 85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: multiple operators


if ((testGrade >= 90) and (testGrade <= 95)):
print("You almost reached excellence!")

def demo_lists():
#Create, print entire list & just first friend
print('Create, print entire list & just first friend')
print('---------------------------------------------')
friend_list = ['Sky', 'Marcel', 'Robin',
'Khaleel', 'Connie']
print('All Friends =', friend_list)
print('First Friend =', friend_list[0])

#Change value
friend_list[0] = "Taylor"
print('First Friend with name change =', friend_list[0])

#Print partial list


print('Partial list of friends =' + str(friend_list[2:5]))

#List within lists


family_list = ['Mom', 'Dad', 'Cousin']
people_list = [friend_list,family_list]
print('\nWrite out people_list:')
print('-----------------------')
print(people_list)
print('\nWrite 3rd element from 2nd list:')
print('-----------------------------------')
print('Third person in 2nd list is:' + (people_list[1][2]))

def demo_for_loops():
#Print from 0 to 4
print("\n*Print from 0 to 4")
for i in range(0,5):
print(i, ' ', end="")

#Print list using 'for'


print("\n*Print list using 'for'")
friend_list = ['Sky', 'Marcel', 'Robin','Khaleel', 'Connie']
for list in friend_list:
print(list)

#List within list aka 2-dimensional array


print("\n*Printing nested loop")

84
array_of_people = [["Robin", "Khaleel", "Connie"],["Mom","Dad","Sister"]]
for x in range(0,2):
for y in range(0,3):
print(array_of_people[x][y])

#Continue, Break
my_items = ['answer', 'amazon', 'banana', 'badger', 'clementine',
'camel']
print("\n*Ex: 'continue' from list: " + str(my_items))

for item in my_items:


if item.startswith('b'):
continue
print(item)

print("\n*Ex: 'break' from list: " + str(my_items))


for item in my_items:
if item.startswith('b'):
break
print(item)

def main():
#demo_if()
#demo_lists()
demo_for_loops()

if __name__ =="__main__":
main()

85
def demo_if():
testGrade = 95

# Ex: if
if testGrade>85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: elif
if testGrade > 94:
print("You did awesome!")

86
elif testGrade > 85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: multiple operators


if ((testGrade >= 90) and (testGrade <= 95)):
print("You almost reached excellence!")

def demo_lists():
#Create, print entire list & just first friend
print('Create, print entire list & just first friend')
print('---------------------------------------------')
friend_list = ['Sky', 'Marcel', 'Robin',
'Khaleel', 'Connie']
print('All Friends =', friend_list)
print('First Friend =', friend_list[0])

#Change value
friend_list[0] = "Taylor"
print('First Friend with name change =', friend_list[0])

#Print partial list


print('Partial list of friends =' + str(friend_list[2:5]))

#List within lists


family_list = ['Mom', 'Dad', 'Cousin']
people_list = [friend_list,family_list]
print('\nWrite out people_list:')
print('-----------------------')
print(people_list)
print('\nWrite 3rd element from 2nd list:')
print('-----------------------------------')
print('Third person in 2nd list is:' + (people_list[1][2]))

def demo_for_loops():
#Print from 0 to 4
print("\n*Print from 0 to 4")
for i in range(0,5):
print(i, ' ', end="")

#Print list using 'for'


print("\n*Print list using 'for'")
friend_list = ['Sky', 'Marcel', 'Robin','Khaleel', 'Connie']
for list in friend_list:
print(list)

#List within list aka 2-dimensional array


print("\n*Printing nested loop")
array_of_people = [["Robin", "Khaleel", "Connie"],["Mom","Dad","Sister"]]

87
for x in range(0,2):
for y in range(0,3):
print(array_of_people[x][y])

#Continue, Break
my_items = ['answer', 'amazon', 'banana', 'badger', 'clementine',
'camel']
print("\n*Ex: 'continue' from list: " + str(my_items))

for item in my_items:


if item.startswith('b'):
continue
print(item)

print("\n*Ex: 'break' from list: " + str(my_items))


for item in my_items:
if item.startswith('b'):
break
print(item)

def demo_while_loops():
print("\n*While loop demo")
x=0
while (x < 5):
print("Today, I've got time, son!")
x=x+1

def main():
#demo_if()
#demo_lists()
#demo_for_loops()
demo_while_loops()

if __name__ =="__main__":
main()

88
def demo_if():
testGrade = 95

# Ex: if
if testGrade>85:
print("You did good!")
else:
print("You did not work hard!")

# Ex: elif
if testGrade > 94:
print("You did awesome!")
elif testGrade > 85:

89
print("You did good!")
else:
print("You did not work hard!")

# Ex: multiple operators


if ((testGrade >= 90) and (testGrade <= 95)):
print("You almost reached excellence!")

def demo_lists():
#Create, print entire list & just first friend
print('Create, print entire list & just first friend')
print('---------------------------------------------')
friend_list = ['Sky', 'Marcel', 'Robin',
'Khaleel', 'Connie']
print('All Friends =', friend_list)
print('First Friend =', friend_list[0])

#Change value
friend_list[0] = "Taylor"
print('First Friend with name change =', friend_list[0])

#Print partial list


print('Partial list of friends =' + str(friend_list[2:5]))

#List within lists


family_list = ['Mom', 'Dad', 'Cousin']
people_list = [friend_list,family_list]
print('\nWrite out people_list:')
print('-----------------------')
print(people_list)
print('\nWrite 3rd element from 2nd list:')
print('-----------------------------------')
print('Third person in 2nd list is:' + (people_list[1][2]))

def demo_for_loops():
#Print from 0 to 4
print("\n*Print from 0 to 4")
for i in range(0,5):
print(i, ' ', end="")

#Print list using 'for'


print("\n*Print list using 'for'")
friend_list = ['Sky', 'Marcel', 'Robin','Khaleel', 'Connie']
for list in friend_list:
print(list)

#List within list aka 2-dimensional array


print("\n*Printing nested loop")
array_of_people = [["Robin", "Khaleel", "Connie"],["Mom","Dad","Sister"]]
for x in range(0,2):

90
for y in range(0,3):
print(array_of_people[x][y])

#Continue, Break
my_items = ['answer', 'amazon', 'banana', 'badger', 'clementine',
'camel']
print("\n*Ex: 'continue' from list: " + str(my_items))

for item in my_items:


if item.startswith('b'):
continue
print(item)

print("\n*Ex: 'break' from list: " + str(my_items))


for item in my_items:
if item.startswith('b'):
break
print(item)

def demo_while_loops():
print("\n*While loop demo")
x=0
while (x < 5):
print("Today, I've got time, son!")
x=x+1

def demo_dictonary():
favorite_movie = {'Reynald' : 'Titanic',
'Marcel' : 'Enter the Dragon',
'Khaleel' : 'The Notebook',
'Connie' : 'Superman'}

print("No shame, Reynald's fav movie is " + favorite_movie['Reynald'])

print(favorite_movie) #print entire dictionary


del favorite_movie['Connie'] #delete value
favorite_movie['Khaleel'] = "Star Wars" #replace value

print("\nReprinting dictionary after modifications")


print(favorite_movie) #reprint entire dictionary

def main():
#demo_if()
#demo_lists()
#demo_for_loops()
#demo_while_loops()
demo_dictonary()

91
if __name__ =="__main__":
main()

import random
import sys
import os

# Chapter 4
def demoIf():
#Traditional if/else
age = 35
if age !=35:
print("A value was given ")

92
name = "Reynald"
if not name:
print("The 'if' condition evaluated to true")
else:
print("The 'if' condition evaluated to false")

#Ternary operator
isAgeGreaterThan25 = True if age > 24 else False
print("isAgeGreaterThan25=" + str(isAgeGreaterThan25))

def demoLists():
#Create, print entire list & just first friend
friend_list = ['Sky', 'Marcel', 'Robin',
'Khaleel', 'Connie']
print('All Friends =', friend_list)
print('First Friend =', friend_list[0])

#Change value
friend_list[0] = "Taylor"
print('First Friend with name change =', friend_list[0])

#Print partial list


print('Partial list of friends =' + str(friend_list[2:5]))

#list within lists


family_list = ['Mom', 'Dad', 'Cousin']
people_list = [friend_list,family_list]
print(people_list)
print('Third person in 2nd list is: ' + str((people_list[1][2])))

def demoForLoops():
#Print from 0 to 4
print("\n*Print from 0 to 4")
for i in range(0,5):
print(i, ' ', end="")

#Print list using 'for'


print("\n*Print list using 'for'")
friend_list = ['Sky', 'Marcel', 'Robin','Khaleel', 'Connie']
for list in friend_list:
print(list)

#List within list aka 2-dimensional array


print("\n*Printing nested loop")
arrayOfPeople = [["Robin", "Khaleel", "Connie"],["Mom","Dad","Sister"]]
for x in range(0,2):
for y in range(0,3):
print(arrayOfPeople[x][y])

def demoWhileLoops():

93
print("\n*While loop demo")
x=0
while x < 5:
print("Today, I've got time, son.")
x=x+1
def demoDictionary():
favorite_movie = {'Reynald' : 'Titanic',
'Marcel' : 'Enter the Dragon',
'Khaleel' : 'The Notebook',
'Connie' : 'Superman'}

print("No shame, Reynald's fav movie is " + favorite_movie['Reynald'])

print(favorite_movie) #print entire dictionary


del favorite_movie['Connie'] #delete value
favorite_movie['Khaleel'] = "Star Wars" #replace value

print("\nReprinting dictionary after modifications")


print(favorite_movie) #reprint entire dictionary

def main():
#demoIf()
#demoLists()
#demoForLoops()
#demoWhileLoops()
demoDictionary()

if __name__== "__main__":
main()

94
APLICATII DIVERSE
MULTIMI

Created on Mar 31, 2018

# ------------ Sets ------------

95
number_set = {1, 2, 3, 4} # sets use curly braces for creation
letter_set = {'a', 'b', 'c', 'd'}
mixed_set = {1, 'a', 2, (1, 2, 3)} # types must be "hashable", i.e. immutable
empty_set = set() # have to use the set() function, cannot use = {}

print(number_set)
print(letter_set)
print(mixed_set)
print(empty_set) # returns: set(). {} would be a dict, not a set

print(type(number_set)) # <class 'set'>

number_set_unique = {1, 2, 3, 4, 2, 3, 4} # sets only store unique values


print(number_set_unique) # {1, 2, 3, 4}, ignores dupes

number_set.add(5) # add an item to the set


print(number_set)

number_set.add(4) # try to add existing item to the set


number_set.add(5) # try to add existing item to the set
print(number_set) # no duplicates, nothing got added

number_set.remove(1) # remove an item from the set


print(number_set)

try: # if the item is not in the set


number_set.remove(98) # KeyError: 98
except Exception as e:
print('** caught Exception:', e)

# use the 'in' keyword


print(98 in number_set) # False
print(5 in number_set) # True

96
Created on Mar 31, 2018

# ------------ Lists ------------

number_list = [1, 2, 3, 4] # lists use square brackets for creation

97
letter_list = ['a', 'b', 'c', 'd']
mixed_list = [1, 'a', 2, [1, 2, 3, 4]] # can also nest lists within lists

print(number_list)
print(letter_list)
print(mixed_list)

print(type(number_list)) # <class 'list'>

original_value = number_list[0] # save value at index 0


number_list[0] = 9 # lists are mutable, can change items once assigned
print(number_list)
number_list[0] = original_value # reassign original value
print(number_list)

number_list.append(5) # add item to list via append


print(number_list)

number_list += [6] # add item to list via operator


print(number_list)

new_number_list = number_list[:] # copy entire list via slicing


print(new_number_list)
print(id(number_list)) # different ids
print(id(new_number_list))
print()

other_number_list = number_list # create second reference to same list object


print(id(number_list)) # same ids
print(id(other_number_list)) # pointing to the same object

number_list.append(99) # append to first list


print(other_number_list) # second list also shows the new value

print(number_list[:]) # slice operator - entire list


print(number_list[1:3]) # start at element 1, end at 3 (exclusive)
print(number_list[3:]) # start at element 3 until the end (inclusive)

98
Created on Mar 31, 2018

# ------------ Tuples ------------

number_tuple = (1, 2, 3, 4) # tuples use parentheses for creation


letter_tuple = ('a', 'b', 'c', 'd')
mixed_tuple = (1, 'a', 2, 'b', [88, 99]) # can mix different types

99
print(number_tuple)
print(letter_tuple)
print(mixed_tuple)

print(type(number_tuple)) # <class 'tuple'>

try:
number_tuple[0] = 9 # tuples are immutable, can't change items once
assigned
except Exception as e:
print('** caught Exception:', e) # TypeError: 'tuple' object does not support item
assignment

try: # try to add item to tuples by creating a new tuple


new_number_tuple = number_tuple + (5) # TypeError: can only concatenate tuple (not
"int") to tuple
except Exception as e:
print('** caught Exception:', e)

new_number_tuple = number_tuple + (5,) # have to add a comma to make it a tuple


print(new_number_tuple)

number_tuple = number_tuple + (5,) # if we reassign to original tuple value,


print(number_tuple) # it appears as if we are updating it

print(id(number_tuple)) # but they are two different objects


number_tuple = number_tuple + (6,)
print(id(number_tuple)) # the variable name is now pointing to a new object

print(number_tuple[:]) # slice operator - entire tuple


print(number_tuple[1:3]) # start at element 1, end at 3 (exclusive)
print(number_tuple[3:]) # start at element 3 until the end (inclusive)

100
101
102
APAS ATCH

103
104
SE POATE SI DIRECT

SAU CLICK DREAPTA

105
GRAFICA
import turtle
t = turtle.Pen()

106
import turtle
t = turtle.Pen()
t.forward(50)

import turtle
t = turtle.Pen()
t.forward(50)
t.left(90)

107
import turtle
t = turtle.Pen()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)

import turtle
t = turtle.Pen()
t.forward(50)

108
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.clear()

import turtle
t = turtle.Pen()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.clear()
t.reset()
t.backward(100)
t.right(90)
t.up()
t.down()

109
import time
print(time.localtime())
import time
print(time.localtime())
t = time.localtime()
print(time.asctime(t))

import time
print(time.localtime())
t = time.localtime()
print(time.asctime(t))
print(time.asctime(time.localtime()))
GRAFICA

110
import turtle
t = turtle.Pen()
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)

import turtle
t = turtle.Pen()
t.color(1,0,0)
t.begin_fill()
t.forward(100)
t.left(90)
t.forward(20)
t.left(90)
t.forward(20)
t.right(90)
t.forward(20)
t.left(90)
t.forward(60)
t.left(90)
t.forward(20)
t.right(90)
t.forward(20)
t.left(90)
t.forward(20)
t.end_fill()
t.color(0,0,0)
t.up()
t.forward(10)
t.down()
t.begin_fill()

111
t.circle(10)
t.end_fill()
t.setheading(0)
t.up()
t.forward(90)
t.right(90)
t.forward(10)
t.setheading(0)
t.begin_fill()
t.down()
t.circle(10)
t.end_fill()

import turtle
t = turtle.Pen()
t.color(1,1,0)
t.begin_fill()
t.circle(50)
t.end_fill()

112
import turtle
t = turtle.Pen()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(5)

113
programare pe obiecte
CLASE

# Step 1 - Create abstract base class


class employee():
def determine_weekly_salary(self, weeklyHours, wage):
raise NotImplementedError("This abstract method must be implmented by subclass")

# Step 2 - Inherit from base & define calculation for permanent employee
class permanent(employee):
def determine_weekly_salary(self, weeklyHours, wage):
salary = 40 * wage
print("\nThis ANGRY EMPLOYEE worked " + str(weeklyHours) +
" hrs. Paid for 40 hrs (no overtime) at $ " + str(wage) +
"/hr = $"+ str(salary) + " \n")

# Step 3 - Inherit from base & define calculation for contractor


class contractor(employee):
def determine_weekly_salary(self, weeklyHours, wage):
salary = weeklyHours * wage
print("\nThis HAPPY CONTRACTOR worked " + str(weeklyHours) +

114
" hrs. Paid for "+ str(weeklyHours) +" hrs (w/ overtime) at $ " +
str(wage) + "/hr = $"+ str(salary) + " \n")
# Step 4 - Create permanent / contractor objects & list
def get_employees():
some_permanent_employee = permanent()
some_contractor = contractor()
everyone = [some_permanent_employee,some_contractor]
return everyone

# Step 5 - Polymorphically calculate salaries


def main():
hours = 50; wage = 70
employees = get_employees()

for e in employees:
e.determine_weekly_salary(hours, wage)

if __name__== "__main__":
main()

115
class employee:
__name = "" # an attribute

# Constructor
def __init__(self, name):
self.__name = name

# Getter & Setter


@property
def employee_name(self):
return self.__name.upper()

@employee_name.setter
def employee_name(self, value):

116
self.__name = value + " (Name changed. Someone quit!)"

# Write employee name


def getIntro(self):
return "Name of employee is {}.".format(self.employee_name)

def demo_class():
#Create employee object
e = employee('James')
e.employee_name="rey"

print(e.getIntro())

def main():
demo_class()

if __name__ =="__main__":
main()

117
PROGRAM PRINCIPAL

# Chapter Sample

#TODO
def main():
print("Rise & Shine!!!")

if __name__== "__main__":
main()

118
import random
import sys
import os

# Chapter 5 - Creating & working w/ Classes


# Create the class
class Employee:
__name = "" # an attribute

# Constructor
def __init__(self, name):
self.__name = name #When values are passed in, define them.

# Getter & Setter


def set_name(self, name):

119
self.__name = name
def get_name(self):
return self.__name.upper()

# Write employee name


def getIntro(self):
return "Name of employee is {}. ".format(self.get_name())

def main():
#Create employee object
anEmployee = Employee('james')

# Execute code
print(anEmployee.getIntro())

if __name__== "__main__":
main()

120
121
122
ESTE ECHIVALENTUL Python

Created on Apr 20, 2018

import random
from pprint import pprint

123
suits = ['Clubs', 'Spades', 'Hearts', 'Diamonds']

deck = [ (suit, rank) for suit in suits for rank in range(1, 14) ] # list comprehension

pprint(deck)

random.shuffle(deck)

pprint(deck)

card = deck.pop()
print('card drawn from top of deck is: ', card)

random_card = deck.pop(random.randint(0, len(deck) -1))


print('random card drawn is: ', random_card)

executia este

[('Clubs', 1),
('Clubs', 2),
('Clubs', 3),
('Clubs', 4),
('Clubs', 5),
('Clubs', 6),
('Clubs', 7),
('Clubs', 8),
('Clubs', 9),
('Clubs', 10),
('Clubs', 11),
('Clubs', 12),
('Clubs', 13),
('Spades', 1),
('Spades', 2),
('Spades', 3),
('Spades', 4),
('Spades', 5),
('Spades', 6),
('Spades', 7),
('Spades', 8),
('Spades', 9),
('Spades', 10),
('Spades', 11),
('Spades', 12),
('Spades', 13),
('Hearts', 1),
('Hearts', 2),
('Hearts', 3),
('Hearts', 4),

124
('Hearts', 5),
('Hearts', 6),
('Hearts', 7),
('Hearts', 8),
('Hearts', 9),
('Hearts', 10),
('Hearts', 11),
('Hearts', 12),
('Hearts', 13),
('Diamonds', 1),
('Diamonds', 2),
('Diamonds', 3),
('Diamonds', 4),
('Diamonds', 5),
('Diamonds', 6),
('Diamonds', 7),
('Diamonds', 8),
('Diamonds', 9),
('Diamonds', 10),
('Diamonds', 11),
('Diamonds', 12),
('Diamonds', 13)]
[('Hearts', 12),
('Diamonds', 5),
('Spades', 6),
('Hearts', 9),
('Spades', 9),
('Hearts', 5),
('Spades', 5),
('Hearts', 1),
('Hearts', 13),
('Diamonds', 6),
('Hearts', 10),
('Diamonds', 9),
('Clubs', 1),
('Spades', 3),
('Diamonds', 10),
('Clubs', 11),
('Diamonds', 4),
('Hearts', 3),
('Spades', 7),
('Clubs', 3),
('Clubs', 5),
('Spades', 12),
('Hearts', 2),
('Diamonds', 12),
('Hearts', 7),
('Spades', 4),
('Diamonds', 11),
('Spades', 10),

125
('Diamonds', 7),
('Hearts', 6),
('Diamonds', 1),
('Spades', 8),
('Clubs', 2),
('Clubs', 10),
('Diamonds', 8),
('Spades', 13),
('Clubs', 8),
('Diamonds', 3),
('Hearts', 11),
('Hearts', 4),
('Clubs', 12),
('Clubs', 4),
('Clubs', 6),
('Diamonds', 2),
('Hearts', 8),
('Clubs', 9),
('Spades', 1),
('Clubs', 13),
('Spades', 2),
('Diamonds', 13),
('Clubs', 7),
('Spades', 11)]
card drawn from top of deck is: ('Spades', 11)
random card drawn is: ('Diamonds', 10)

Created on May 2, 2018

# single inheritance

class Building():
def __init__(self, type_of, name):
self.type_of_building = type_of
self.name_of_building = name

def build(self):
print('building a {}...'.format(self.type_of_building))

def visit(self):
print('Welcome to {}'.format(self.name_of_building))

def info(self):
return self.build(), self.visit()

126
class Cathedral(Building):
pass

class Cafe(Building):
pass

notre_dame = Cathedral('Cathedral', 'Notre-Dame de Paris')


notre_dame.info()
print()
Cafe('Cafe', 'The Java House').info()

127
Created on May 2, 2018

# Inheritance: 'is-a'
# Composition: 'has-a'

class Engine():
def __init__(self, engine_type='[unknown]'):
self.engine_type = engine_type

class Vehicle():
def __init__(self, seats=1):
self.number_of_seats = seats

class Airplane(Vehicle): # Airplane is-a Vehicle


def __init__(self, model, engine, seats=1):
super().__init__(seats)
self.airplane_model = model
self.airplane_engine = Engine(engine) # Airplane has an Engine

def airplane_info(self):
print('{} with \n{} type of engine and \n{} passenger seats\n'.\
format(self.airplane_model,
self.airplane_engine.engine_type,
self.number_of_seats))

boing = Airplane(model='Boing 787 Dreamliner',


engine='Rolls-Royce Trent 1000',
seats=300)

airbus = Airplane(model='Airbus A350',


engine='Rolls-Royce Trent XWB',
seats=299)

for plane in (boing, airbus):


plane.airplane_info()

128
programare vizuala cu obiecte

realizarea unei ferestre

Created on May 7, 2018

129
import tkinter
tkinter.Tk().mainloop()

Created on May 7, 2018

import tkinter as tk # alias tkinter as "tk"


from tkinter import ttk # ttk == "themed tk"

gui = tk.Tk() # create Tk() instance and assign to variable

ttk.Label(gui, text="Hello Label").\


grid(row=0, column=0) # create a themed tk label

ttk.Button(gui, text="Click Me!").\


grid(row=0, column=1) # gui is the parent for the widgets

tk.Entry(gui).\
grid(row=0, column=2) # using grid layout manager

gui.mainloop() # start the main event loop to display our gui

130
Created on May 7, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()

ttk.Label(gui, text="Hello Label").\


grid(row=0, column=0)

ttk.Button(gui, text="Click Me!").\


grid(row=0, column=1)

tk.Entry(gui, textvariable=tk.StringVar(value=" <default entry>")).\


grid(row=0, column=2)

gui.mainloop()

o ferestra cu titlu

Created on May 7, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()

131
gui.title("Our GUI Title")

ttk.Label(gui, text="Hello Label").\


grid(row=0, column=0)

ttk.Button(gui, text="Click Me!").\


grid(row=0, column=1)

tk.Entry(gui, textvariable=tk.StringVar(value=" <default entry>")).\


grid(row=0, column=2)

for child in gui.winfo_children(): # loop through gui children


child.grid_configure(padx=10, pady=10) # add x, y padding to each

gui.mainloop()

Created on May 7, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets") # gui is parent of frame


frame.pack(padx=10, pady=5)

ttk.Label(frame, text="Hello Label").\


grid(row=0, column=0) # frame is parent

ttk.Button(frame, text="Click Me!").\


grid(row=0, column=1)

132
tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry>")).\
grid(row=0, column=2)

for child in frame.winfo_children():


child.grid_configure(padx=10, pady=10)

gui.mainloop()

eticheta active

Created on May 7, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets")


frame.pack(padx=10, pady=5)

ttk.Label(frame, text="Hello Label").\


grid(row=0, column=0)

def button_callback():
entry.config(textvariable=tk.StringVar(value=' Button was clicked!'))

ttk.Button(frame, text="Click Me!", command=button_callback).\


grid(row=0, column=1)

entry = tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry>"))


entry.grid(row=0, column=2)

for child in frame.winfo_children():

133
child.grid_configure(padx=10, pady=10)

gui.mainloop()

Created on May 7, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets")


frame.pack(padx=10, pady=5)

entry_list = []
def button_callback(idx):
entry_list[idx].config(textvariable=tk.StringVar(value=' Button {} was clicked!'.\
format(idx)))

for idx in range(4):


ttk.Label(frame, text="Hello Label " + str(idx)).\
grid(row=idx, column=0)

ttk.Button(frame, text="Click Me " + str(idx), command= lambda cur_idx=idx:


button_callback(cur_idx)).\
grid(row=idx, column=1)

entry_var = "entry" + str(idx)


entry_var = tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry> " +
str(idx)))
entry_var.grid(row=idx, column=2)

134
entry_list.append(entry_var)

for child in frame.winfo_children():


child.grid_configure(padx=8, pady=3)

gui.mainloop()

Created on May 7, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets")


frame.pack(padx=10, pady=5)

entry_list = []
label_list = []
def button_callback(idx):
entry_list[idx].config(textvariable=tk.StringVar(value=' Button {} was clicked!'.\
format(idx)))
label_list[idx].config(foreground='red')

for idx in range(4):


lbl_var = "label" + str(idx)
lbl_var = ttk.Label(frame, text="Hello Label " + str(idx))
lbl_var.grid(row=idx, column=0)
label_list.append(lbl_var)

135
ttk.Button(frame, text="Click Me " + str(idx), command= lambda cur_idx=idx:
button_callback(cur_idx)).\
grid(row=idx, column=1)

entry_var = "entry" + str(idx)


entry_var = tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry> " +
str(idx)))
entry_var.grid(row=idx, column=2)
entry_list.append(entry_var)

for child in frame.winfo_children():


child.grid_configure(padx=8, pady=3)

gui.mainloop()

Created on May 7, 2018

136
import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets")


frame.pack(padx=10, pady=5)

entry_list = []
label_list = []
def button_callback(idx):
entry_list[idx].config(textvariable=tk.StringVar(value=' Button {} was clicked!'.\
format(idx)))
label_list[idx].config(foreground='red')
text.insert(tk.END, entry_list[idx].get() + '\n')

for idx in range(4):


lbl_var = "label" + str(idx)
lbl_var = ttk.Label(frame, text="Hello Label " + str(idx))
lbl_var.grid(row=idx, column=0)
label_list.append(lbl_var)

ttk.Button(frame, text="Click Me " + str(idx), command= lambda cur_idx=idx:


button_callback(cur_idx)).\
grid(row=idx, column=1)

entry_var = "entry" + str(idx)


entry_var = tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry> " +
str(idx)))
entry_var.grid(row=idx, column=2)
entry_list.append(entry_var)

for child in frame.winfo_children():


child.grid_configure(padx=8, pady=3)

frame_2 = ttk.LabelFrame(gui, text="Another frame")


frame_2.pack(padx=10, pady=5)

text = tk.Text(frame_2, height=15, width=40)


text.pack()
# text.grid(row=0, column=0) # use pack or grid layout mgr

gui.mainloop()

137
Created on May 8, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets")


frame.pack(padx=10, pady=5)

entry_list = []
label_list = []

def button_callback(idx):
entry_list[idx].config(textvariable=tk.StringVar(value=' Button {} was clicked!'.\

138
format(idx)))
label_list[idx].config(foreground='green')
text1.insert(tk.END, entry_list[idx].get() + '\n')
if idx == 0:
progress_bar.start()
text2.insert(tk.END, ' starting Progressbar...\n')
label_list[idx].config(text='Running...')
elif idx ==1:
progress_bar.stop()
text2.insert(tk.END, ' stopping Progressbar...\n')
label_list[idx].config(text='Stopped...')

button_names = [
'Start Progress',
'Stop Progress',
'Button 2',
'Button 3']

for idx in range(4):


lbl_var = "label" + str(idx)
lbl_var = ttk.Label(frame, text="Hello Label " + str(idx))
lbl_var.grid(row=idx, column=0)
label_list.append(lbl_var)

ttk.Button(frame, text=button_names[idx], command= lambda cur_idx=idx:


button_callback(cur_idx)).\
grid(row=idx, column=1)

entry_var = "entry" + str(idx)


entry_var = tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry> " +
str(idx)))
entry_var.grid(row=idx, column=2)
entry_list.append(entry_var)

for child in frame.winfo_children():


child.grid_configure(padx=8, pady=3)

frame_2 = ttk.LabelFrame(gui, text="Another frame")


frame_2.pack(padx=10, pady=5)

paned = tk.PanedWindow(frame_2, sashwidth=4, relief='solid',


orient='vertical')
paned.pack()

text1 = tk.Text(paned, height=8, width=40)


paned.add(text1)

139
text2 = tk.Text(paned, height=8, width=40)
paned.add(text2)

gui.update()
gui_width = gui.winfo_width()
progress_bar = ttk.Progressbar(gui, length=gui_width, mode='determinate')
progress_bar.pack()

gui.mainloop()

Created on May 8, 2018

import tkinter as tk

140
from tkinter import ttk

gui = tk.Tk()
gui.title("Our GUI Title")

frame = ttk.LabelFrame(gui, text="A frame surrounding widgets")


frame.pack(padx=10, pady=5)

entry_list = []
label_list = []

def button_callback(idx):
label_list[idx].config(foreground='green')
text1.insert(tk.END, entry_list[idx].get() + '\n')
if idx == 0:
progress_bar.start()
text2.insert(tk.END, ' starting Progressbar...\n')
label_list[idx].config(text='Running...')
elif idx ==1:
progress_bar.stop()
text2.insert(tk.END, ' stopping Progressbar...\n')
label_list[idx].config(text='Stopped...')

button_names = [
'Start Progress',
'Stop Progress',
'Button 2',
'Button 3']

for idx in range(4):


lbl_var = "label" + str(idx)
lbl_var = ttk.Label(frame, text="Hello Label " + str(idx))
lbl_var.grid(row=idx, column=0)
label_list.append(lbl_var)

ttk.Button(frame, text=button_names[idx], command= lambda cur_idx=idx:


button_callback(cur_idx)).\
grid(row=idx, column=1)

entry_var = "entry" + str(idx)


entry_var = tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry> " +
str(idx)))
entry_var.grid(row=idx, column=2)
entry_list.append(entry_var)

for child in frame.winfo_children():


child.grid_configure(padx=8, pady=3)

141
frame_2 = ttk.LabelFrame(gui, text="Another frame")
frame_2.pack(padx=10, pady=5)

paned = tk.PanedWindow(frame_2, sashwidth=4, relief='solid',


orient='vertical')
paned.pack()

text1 = tk.Text(paned, height=8, width=40)


paned.add(text1)

text2 = tk.Text(paned, height=8, width=40)


paned.add(text2)

gui.update()
gui_width = gui.winfo_width()
progress_bar = ttk.Progressbar(gui, length=gui_width, mode='determinate')
progress_bar.pack()

gui.mainloop()

Created on May 8, 2018

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("GUI")

tabs_frame = ttk.Frame(gui)
tabs_frame.grid(row=0, column=0, sticky='W')

display_area = ttk.Labelframe(gui, text=' Tab Display Area ')


display_area.grid(row=1, column=0, sticky='WE')

note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)

142
note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)

# create and add tabs to Notebooks


for tab_no in range(5):
tab1 = ttk.Frame(note1) # Create a tab for notebook 1
tab2 = ttk.Frame(note2) # Create a tab for notebook 2
note1.add(tab1, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 1
note2.add(tab2, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 2

gui.mainloop()

Created on May 8, 2018

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

# Callbacks
#------------------------------------------
def clear_display_area():
for widget in display_area.grid_slaves():
if int(widget.grid_info()["row"]) == 0:
widget.grid_forget()

def display_button(active_notebook, tab_no):


btn = ttk.Button(display_area, text=active_notebook +' - Tab '+ tab_no,
command= lambda: showinfo("Tab Display", "Tab: " + tab_no))
btn.grid(column=0, row=0, padx=8, pady=8)

def notebook_callback(event):

143
clear_display_area()

current_notebook = str(event.widget)
tab_no = str(event.widget.index("current") + 1)

if current_notebook.endswith('notebook'):
active_notebook = 'Notebook 1'
elif current_notebook.endswith('notebook2'):
active_notebook = 'Notebook 2'
else:
active_notebook = ''

display_button(active_notebook, tab_no)

# GUI Creation
#------------------------------------------
gui = tk.Tk()
gui.title("GUI")

tabs_frame = ttk.Frame(gui)
tabs_frame.grid(row=0, column=0, sticky='W')

display_area = ttk.Labelframe(gui, text=' Tab Display Area ')


display_area.grid(row=1, column=0, sticky='WE', padx=5, pady=5)

display_area_label = tk.Label(display_area, text="", height=2)


display_area_label.grid(column=0, row=0)

note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)

note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)

# create and add tabs to Notebooks


for tab_no in range(5):
tab1 = ttk.Frame(note1) # Create a tab for notebook 1
tab2 = ttk.Frame(note2) # Create a tab for notebook 2
note1.add(tab1, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 1
note2.add(tab2, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 2

# bind click-events to Notebooks


note1.bind("<ButtonRelease-1>", notebook_callback)
note2.bind("<ButtonRelease-1>", notebook_callback)

# display_button('Notebook 1', '1') # mimic tab click event

144
gui.mainloop()

Created on May 8, 2018

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

# Callback & functions


#------------------------------------------
def clear_display_area():
for widget in display_area.grid_slaves():
if int(widget.grid_info()["row"]) == 0:
widget.grid_forget()

def display_button(active_notebook, tab_no):


btn = ttk.Button(display_area, text=active_notebook +' - Tab '+ tab_no,
command= lambda: showinfo("Tab Display", "Tab: " + tab_no))
btn.grid(column=0, row=0, padx=8, pady=8)

def notebook_callback(event):
clear_display_area()

current_notebook = str(event.widget)
tab_no = str(event.widget.index("current") + 1)

if current_notebook.endswith('notebook'):
active_notebook = 'Notebook 1'
elif current_notebook.endswith('notebook2'):
active_notebook = 'Notebook 2'
else:
active_notebook = ''

145
display_button(active_notebook, tab_no)

# GUI Creation
#------------------------------------------
gui = tk.Tk()
gui.title("GUI")

tabs_frame = ttk.Frame(gui)
tabs_frame.grid(row=0, column=0, sticky='W')

display_area = ttk.Labelframe(gui, text=' Tab Display Area ')


display_area.grid(row=1, column=0, sticky='WE', padx=5, pady=5)

display_area_label = tk.Label(display_area, text="", height=2)


display_area_label.grid(column=0, row=0)

note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)

note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)

# create and add tabs to Notebooks


for tab_no in range(5):
tab1 = ttk.Frame(note1) # Create a tab for notebook 1
tab2 = ttk.Frame(note2) # Create a tab for notebook 2
note1.add(tab1, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 1
note2.add(tab2, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 2

# bind click-events to Notebooks


note1.bind("<ButtonRelease-1>", notebook_callback)
note2.bind("<ButtonRelease-1>", notebook_callback)

display_button('Notebook 1', '1') # mimic tab click event

gui.mainloop()

146
Created on May 8, 2018

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

# Callback & functions


#------------------------------------------
def new_text_callback(event):
x, y = event.widget.winfo_pointerxy()
btn = event.widget.winfo_containing(x, y)
try: btn.configure(text=event.widget.cget("text"))
except: pass

def drag_btn_text(btn):
btn.bind("<ButtonRelease-1>", new_text_callback)

def clear_display_area():
for widget in display_area.grid_slaves():
if int(widget.grid_info()["row"]) == 0:
widget.grid_forget()

def display_button(active_notebook, tab_no):


btn = ttk.Button(display_area, text=active_notebook +' - Tab '+ tab_no,
command= lambda: showinfo("Tab Display", "Tab: " + tab_no))
btn.grid(row=0, column=0, padx=8, pady=8)
drag_btn_text(btn)

def notebook_callback(event):
clear_display_area()

147
current_notebook = str(event.widget)
tab_no = str(event.widget.index("current") + 1)

if current_notebook.endswith('notebook'):
active_notebook = 'Notebook 1'
elif current_notebook.endswith('notebook2'):
active_notebook = 'Notebook 2'
else:
active_notebook = ''

display_button(active_notebook, tab_no)

# GUI Creation
#------------------------------------------
gui = tk.Tk()
gui.title("GUI")

tabs_frame = ttk.Frame(gui)
tabs_frame.grid(row=0, column=0, sticky='W')

display_area = ttk.Labelframe(gui, text=' Tab Display Area ')


display_area.grid(row=1, column=0, sticky='WE', padx=5, pady=5)

display_area_label = tk.Label(display_area, text="", height=2)


display_area_label.grid(column=0, row=0)

note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)

note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)

# create and add tabs to Notebooks


for tab_no in range(5):
tab1 = ttk.Frame(note1) # Create a tab for notebook 1
tab2 = ttk.Frame(note2) # Create a tab for notebook 2
note1.add(tab1, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 1
note2.add(tab2, text=' Tab {} '.format(tab_no + 1)) # Add tab notebook 2

# bind click-events to Notebooks


note1.bind("<ButtonRelease-1>", notebook_callback)
note2.bind("<ButtonRelease-1>", notebook_callback)

display_button('Notebook 1', '1') # mimic tab click event

btn0 = ttk.Button(display_area, text='Second Row')


btn0.grid(row=1, column=0, sticky='WE', padx=8, pady=2)

148
btn1 = ttk.Button(display_area, text='Drag here')
btn1.grid(row=1, column=1, sticky='WE', padx=8, pady=2)

drag_btn_text(btn0)
drag_btn_text(btn1)

gui.mainloop()

import tkinter as tk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)

gui.update()
print(gui.winfo_width())
print(gui.winfo_height())

gui.mainloop()

149
import tkinter as tk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)

label = tk.Label(gui, text='Hi there...', padx=100, pady=10)


label.pack()

gui.update()

150
print(gui.winfo_width())
print(gui.winfo_height())

gui.mainloop()

151
import tkinter as tk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)
gui.geometry("200x200")

label = tk.Label(gui, text='Hi there...')


label.pack()

152
gui.update()
print(gui.winfo_width())
print(gui.winfo_height())

gui.mainloop()

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)
gui.configure(background='Blue')

ttk.Button(gui, text='Hi there...').grid()


ttk.Button(gui, text='Hi there...').grid(column=1)
ttk.Button(gui, text='Hi there...').grid(column=2)

gui.mainloop()

153
import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)
gui.configure(background='blue')

tk.Button(gui, text='Hi there...', bg='orange', relief='flat', width=9).grid()


tk.Button(gui, text='Hi there...', bg='orange', relief='flat', width=9).grid(column=1)
tk.Button(gui, text='Hi there...', bg='orange', relief='flat', width=9).grid(column=2)

gui.mainloop()

import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)
gui.configure(background='blue')

style = ttk.Style()
style.configure('TButton', font=('', 12))

ttk.Button(gui, text='Hi there...').grid()


ttk.Button(gui, text='Hi there...').grid()
ttk.Button(gui, text='Hi there...').grid()

ttk.Label(gui, text='Hi there...', width=20, anchor='center').grid(row=0, column=1)


ttk.Label(gui, text='Hi there...', width=20, anchor='center').grid(row=1, column=1)
ttk.Label(gui, text='Hi there...', width=20, anchor='center').grid(row=2, column=1)

gui.mainloop()

154
import tkinter as tk
from tkinter import ttk

gui = tk.Tk()
gui.title("GUI")
gui.resizable(False, False)
gui.configure(background='blue')

style = ttk.Style()
style.configure('TButton', font=('', 12))
style.configure('TLabel', font=('', 12))

ttk.Button(gui, text='Hi there...').grid()


ttk.Button(gui, text='Hi there...').grid()
ttk.Button(gui, text='Hi there...').grid()

ttk.Label(gui, text='Hi there...', width=20, anchor='center').grid(row=0, column=1)


ttk.Label(gui, text='Hi there...', width=20, anchor='center').grid(row=1, column=1)
ttk.Label(gui, text='Hi there...', width=20, anchor='center').grid(row=2, column=1)

gui.mainloop()

APELURI DE FUNCTII
def example_function(x):
return x + 1

example_variable = 10
print(example_variable)

processed_variable = example_function(example_variable)
print(processed_variable) # this should be 11

def complicated_func(x, y):

def squared(z):
return z * z

x_squared = squared(x)
return x_squared + y * 3

155
x=5
y=3

print(complicated_func(x, y)) # 34

# List comprehensions
xs = [0, 1, 2, 3, 4, 5]
# target x_squared_s = [0, 1, 4, 9, 16, 25]

result = []
for x in xs:
result.append(x * x)

print(result)

result_alternative = [(x * x) for x in xs]

print(result_alternative)

156
157
# Write a small program to ask for a name and an age.
# When both values have been entered, check if the person
# is the right age to go on an 18-30 holiday (they must be
# over 18 and under 31).
# If they are, welcome them to the holiday, otherwise print
# a (polite) message refusing them entry.
name = input("Please enter your name: ")
age = int(input("How old are you, {0}? ".format(name)))

158
# if 18 <= age < 31:
if age >=18 and age <31:
print("Welcome to club 18-30 holidays, {0}".format(name))
else:
print("I'm sorry, our holidays are only for seriously cool people")

============= surse de la
mk:@MSITStore:C:\Users\tica1234ticabogd\Desktop\CARTI%20PYTHON\Python%
20Book%20Collection%20Pack%20PDF%20-
%20P2P\Python\Data%20Structures%20and%20Algorithms%20with%20Object-
Oriented%20Design%20Patterns%20in%20Python%20(2003).chm::/opus7/programs/index.ht
ml

suma ca si functie trebuie programul principal de apelare

159
def sum(n):
result = 0
i=1
while i <= n:
result += i
i += 1
return result

def Horner(a, n, x):


result = a[n]
i=n-1
while i >= 0:
result = result * x + a[i]
i -= 1
return result

def factorial(n):
if n == 0:
return 1
else:

160
return n * factorial(n - 1)

def findMaximum(a, n):


result = a[0]
i=1
while i < n:
if a[i] > result:
result = a[i]
i += 1
return result

def gamma():
result = 0.
i = 1
while i <= 500000:
result += 1.0/i - math.log((i + 1.0)/i)
i += 1
return result

def geometricSeriesSum(x, n):


sum = 0
i = 0
while i <= n:
prod = 1
j = 0
while j < i:
prod *= x
j += 1
sum += prod
i += 1
return sum

def geometricSeriesSum(x, n):


sum = 0
i = 0
while i <= n:
sum = sum * x + 1
i += 1
return sum

def power(x, n):


if n == 0:
return 1
elif n % 2 == 0: # n is even
return power(x * x, n / 2)
else: # n is odd

161
return x * power(x * x, n / 2)

def geometricSeriesSum(x, n):


return (power(x, n + 1) - 1) / (x - 1)

def Horner(a, n, x):


result = a[n]
i = n - 1
while i >= 0:
result = result * x + a[i]
i -= 1
return result

def prefixSums(a, n):


j = n - 1
while j >= 0:
sum = 0
i = 0
while i <= j:
sum += a[i]
i += 1
a[j] = sum
j -= 1
iterativ

def Fibonacci(n):
previous = -1
result = 1
i = 0
while i <= n:
sum = result + previous
previous = result
result = sum
i += 1
return result
recursiv

def Fibonacci(n):
if n == 0 or n == 1:
return n
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
def bucketSort(a, n, buckets, m):
for j in range(m):
buckets[j] = 0
for i in range(n):
buckets[a[i]] += 1
i = 0
for j in range(m):
for k in range(buckets[j]):
a[i] = j
i += 1
crearea claselor in proiect

162
ALGORITMI DE SORTARE FOLOSIND CLASE

163
class Sorter(Object):

def __init__(self):
super(Sorter, self).__init__()
self._array = None
self._n = 0

def _sort(self):
pass
_sort = abstractmethod(_sort)

def sort(self, array):


assert isinstance(array, Array)
self._array = array
self._n = len(array)
if self._n > 0:
self._sort()
self._array = None

def swap(self, i, j):


tmp = self._array[i]
self._array[i] = self._array[j]
self._array[j] = tmp
class StraightInsertionSorter(Sorter):

def __init__(self):
super(StraightInsertionSorter, self).__init__()

def _sort(self):
for i in xrange(1, self._n):
j = i
while j > 0 and self._array[j - 1] > self._array[j]:
self.swap(j, j - 1)
j -= 1
class BinaryInsertionSorter(Sorter):

def __init__(self):
super(BinaryInsertionSorter, self).__init__()

164
def _sort(self):
for i in xrange(1, self._n):
tmp = self._array[i]
left = 0
right = i
while left < right:
middle = (left + right) / 2
if tmp >= self._array[middle]:
left = middle + 1
else:
right = middle
j = i
while j > left:
self.swap(j - 1, j)
j -= 1
class BubbleSorter(Sorter):

def __init__(self):
super(BubbleSorter, self).__init__()

def _sort(self):
i = self._n
while i > 1:
for j in xrange(i - 1):
if self._array[j] > self._array[j + 1]:
self.swap(j, j + 1)
i -= 1
class QuickSorter(Sorter):

def __init__(self):
super(QuickSorter, self).__init__()

def selectPivot(self):
pass
selectPivot = abstractmethod(selectPivot)
class QuickSorter(Sorter):

CUTOFF = 2 # minimum cut-off

def quicksort(self, left, right):


if right - left + 1 > self.CUTOFF:
p = self.selectPivot(left, right)
self.swap(p, right)
pivot = self._array[right]
i = left
j = right - 1
while True:
while i < j and self._array[i] < pivot:
i += 1
while i < j and self._array[j] > pivot:
j -= 1
if i >= j:
break
self.swap(i, j)
i += 1
j -= 1
if self._array[i] > pivot:
self.swap(i, right)
if left < i:
self.quicksort(left, i - 1)
if right > i:

165
self.quicksort(i + 1, right)
class QuickSorter(Sorter):

def _sort(self):
self.quicksort(0, self._n - 1)
sorter = StraightInsertionSorter()
sorter.sort(self._array)
class MedianOfThreeQuickSorter(QuickSorter):

def __init__(self):
super(MedianOfThreeQuickSorter, self).__init__()

def selectPivot(self, left, right):


middle = (left + right) / 2
if self._array[left] > self._array[middle]:
self.swap(left, middle)
if self._array[left] > self._array[right]:
self.swap(left, right)
if self._array[middle] > self._array[right]:
self.swap(middle, right)
return middle
class StraightSelectionSorter(Sorter):

def __init__(self):
super(StraightSelectionSorter, self).__init__()

def _sort(self):
i = self._n
while i > 1:
max = 0
for j in xrange(i):
if self._array[j] > self._array[max]:
max = j
self.swap(i - 1, max)
i -= 1

class HeapSorter(Sorter):

def __init__(self):
super(HeapSorter, self).__init__()

def percolateDown(self, i, length):


while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] \
> self._array[j]:
j = j + 1
if self._array[i] \
>= self._array[j]:
break
self.swap(i, j)
i = j
class HeapSorter(Sorter):

def buildHeap(self):
i = self._n / 2
while i > 0:
self.percolateDown(i, self._n)
i -= 1
class HeapSorter(Sorter):

166
def _sort(self):
base = self._array.baseIndex
self._array.baseIndex = 1
self.buildHeap()
i = self._n
while i >= 2:
self.swap(i, 1)
self.percolateDown(1, i - 1)
i -= 1
self._array.baseIndex = base

class TwoWayMergeSorter(Sorter):

def __init__(self):
super(TwoWayMergeSorter, self).__init__()
self._tempArray = None
class TwoWayMergeSorter(Sorter):

def merge(self, left, middle, right):


i = left
j = left
k = middle + 1
while j <= middle and k <= right:
if self._array[j] < self._array[k]:
self._tempArray[i] = self._array[j]
i += 1
j += 1
else:
self._tempArray[i] = self._array[k]
i += 1
k += 1
while j <= middle:
self._tempArray[i] = self._array[j]
i += 1
j += 1
for i in xrange(left, k):
self._array[i] = self._tempArray[i]

class TwoWayMergeSorter(Sorter):

def _sort(self):
self._tempArray = Array(self._n)
self.mergesort(0, self._n - 1)
self._tempArray = None

def mergesort(self, left, right):


if left < right:
middle = (left + right) / 2
self.mergesort(left, middle)
self.mergesort(middle + 1, right)
self.merge(left, middle, right)

class BucketSorter(Sorter):

def __init__(self, m):


super(BucketSorter, self).__init__()
self._m = m
self._count = Array(self._m)
class BucketSorter(Sorter):

def _sort(self):
for i in xrange(self._m):

167
self._count[i] = 0
for j in xrange(self._n):
self._count[self._array[j]] += 1
j = 0
for i in xrange(self._m):
while self._count[i] > 0:
self._array[j] = i
j += 1
self._count[i] -= 1

class RadixSorter(Sorter):

r = 8
R = 1 << r
p = (32 + r - 1) / r

def __init__(self):
self._count = Array(self.R)
self._tempArray = None

class RadixSorter(Sorter):

def _sort(self):
self._tempArray = Array(self._n)
for i in xrange(self.p):
for j in xrange(self.R):
self._count[j] = 0
for k in xrange(self._n):
self._count[(self._array[k] \
>> (self.r*i)) & (self.R-1)] += 1
self._tempArray[k] = self._array[k]
pos = 0
for j in xrange(self.R):
tmp = pos
pos += self._count[j]
self._count[j] = tmp
for k in xrange(self._n):
j = (self._tempArray[k] \
>> (self.r*i)) & (self.R-1)
self._array[self._count[j]] = self._tempArray[k]
self._count[j] += 1

168
Instalez optiunile

169
170
171
172
Grafuri

173
174
175
class Vertex(Object):

def __init__(self):
super(Vertex, self).__init__()

def getNumber(self): pass


getNumber = abstractmethod(getNumber)
number = property(
fget = lambda self: self.getNumber())

def getWeight(self): pass


getWeight = abstractmethod(getWeight)

176
weight = property(
fget = lambda self: self.getWeight())

def getIncidentEdges(self): pass


getIncidentEdges = abstractmethod(getIncidentEdges)
incidentEdges = property(
fget = lambda self: self.getIncidentEdges())

def getEmanatingEdges(self): pass


getEmanatingEdges = abstractmethod(getEmanatingEdges)
emanatingEdges = property(
fget = lambda self: self.getEmanatingEdges())

def getPredecessors(self): pass


getPredecessors = abstractmethod(getPredecessors)
predecessors = property(
fget = lambda self: self.getPredecessors())

def getSuccessors(self): pass


getSuccessors = abstractmethod(getSuccessors)
successors = property(
fget = lambda self: self.getSuccessors())
class Edge(Object):

def __init__(self):
super(Edge, self).__init__()

def getV0(self): pass


getV0 = abstractmethod(getV0)
v0 = property(
fget = lambda self: self.getV0())

def getV1(self): pass


getV1 = abstractmethod(getV1)
v1 = property(
fget = lambda self: self.getV1())

def getWeight(self): pass


getWeight = abstractmethod(getWeight)
weight = property(
fget = lambda self: self.getWeight())

def getIsDirected(self): pass


getIsDirected = abstractmethod(getIsDirected)
isDirected = property(
fget = lambda self: self.getIsDirected())

def mateOf(self, vertex): pass


mateOf = abstractmethod(mateOf)

177
#
class Graph(Container):

def __init__(self, size):


super(Graph, self).__init__()
self._numberOfVertices = 0
self._numberOfEdges = 0
self._vertex = Array(size)
self._isDirected = False

class Vertex(Vertex):

def __init__(self, graph, number, weight):


super(Graph.Vertex, self).__init__()
self._graph = graph
self._number = number
self._weight = weight

class Edge(Edge):

def __init__(self, graph, v0, v1, weight):


super(Graph.Edge, self).__init__()
self._graph = graph
self._v0 = v0
self._v1 = v1
self._weight = weight

class Graph(Container):

def getNumberOfEdges(self): pass


getNumberOfEdges = abstractmethod(getNumberOfEdges)
numberOfEdges = property(
fget = lambda self: self.getNumberOfEdges())

def getNumberOfVertices(self): pass


getNumberOfVertices = abstractmethod(getNumberOfVertices)
numberOfVertices = property(
fget = lambda self: self.getNumberOfVertices())

def getIsDirected(self): pass


getIsDirected = abstractmethod(getIsDirected)
isDirected = property(
fget = lambda self: self.getIsDirected())

def getIsConnected(self): pass


getIsConnected = abstractmethod(getIsConnected)
isConnected = property(
fget = lambda self: self.getIsConnected())

178
def getIsCyclic(self): pass
getIsCyclic = abstractmethod(getIsCyclic)
isCyclic = property(
fget = lambda self: self.getIsCyclic())

def getVertices(self): pass


getVertices = abstractmethod(getVertices)
vertices = property(
fget = lambda self: self.getVertices())

def getEdges(self): pass


getEdges = abstractmethod(getEdges)
edges = property(
fget = lambda self: self.getEdges())

class Graph(Container):

def addVertex(self, *args): pass


addVertex = abstractmethod(addVertex)

def getVertex(self, v): pass


getVertex = abstractmethod(getVertex)

def addEdge(self, *args): pass


addEdge = abstractmethod(addEdge)

def getEdge(self, v, w): pass


getEdge = abstractmethod(getEdge)

def isEdge(self, v, w): pass


isEdge = abstractmethod(isEdge)

def depthFirstTraversal(self, visitor, start): pass


depthFirstTraversal = abstractmethod(depthFirstTraversal)

def breadthFirstTraversal(self, visitor, start): pass


breadthFirstTraversal = abstractmethod(breadthFirstTraversal)

def getIncidentEdges(self, v): pass


getIncidentEdges = abstractmethod(getIncidentEdges)

def getEmanatingEdges(self, v): pass


getEmanatingEdges = abstractmethod(getEmanatingEdges)

def __len__(self):
return self.numberOfVertices

def __getitem__(self, v):


return self.getVertex(v)

179
class Digraph(Graph):

def __init__(self, size):


super(Digraph, self).__init__(size)
self._isDirected = True

def getIsStronglyConnected(self): pass


getIsStronglyConnected = abstractmethod(
getIsStronglyConnected)
isStronglyConnected = property(
fget = lambda self: self.getIsStronglyConnected())

def topologicalOrderTraversal(self): pass


topologicalOrderTraversal = abstractmethod(
topologicalOrderTraversal)
class GraphAsMatrix(Graph):

def __init__(self, size):


super(GraphAsMatrix, self).__init__(size)
self._matrix = DenseMatrix(size, size)

class GraphAsLists(Graph):

def __init__(self, size):


super(GraphAsLists, self).__init__(size)
self._adjacencyList = Array(size)
for i in xrange(size):
self._adjacencyList[i] = LinkedList()

class Graph(Container):

def depthFirstTraversal(self, visitor, start):


assert isinstance(visitor, PrePostVisitor)
visited = Array(self._numberOfVertices)
for v in xrange(self._numberOfVertices):
visited[v] = False
self._depthFirstTraversal(visitor, self[start], visited)

def _depthFirstTraversal(self, visitor, v, visited):


if visitor.isDone:
return
visitor.preVisit(v)
visited[v.number] = True
for to in v.successors:
if not visited[to.number]:
self._depthFirstTraversal(visitor, to, visited)
visitor.postVisit(v)

180
class Graph(Container):

def breadthFirstTraversal(self, visitor, start):


assert isinstance(visitor, Visitor)
enqueued = Array(self._numberOfVertices)
for v in xrange(self._numberOfVertices):
enqueued[v] = False
queue = QueueAsLinkedList()
queue.enqueue(self[start])
enqueued[start] = True
while not queue.isEmpty and not visitor.isDone:
v = queue.dequeue()
visitor.visit(v)
for to in v.successors:
if not enqueued[to.number]:
queue.enqueue(to)
enqueued[to.number] = True

class Digraph(Graph):

def topologicalOrderTraversal(self, visitor):


inDegree = Array(self.numberOfVertices)
for v in xrange(self.numberOfVertices):
inDegree[v] = 0
for e in self.edges:
inDegree[e.v1.number] += 1
queue = QueueAsLinkedList()
for v in xrange(self.numberOfVertices):
if inDegree[v] == 0:
queue.enqueue(self[v])
while not queue.isEmpty and not visitor.isDone:
v = queue.dequeue()
visitor.visit(v)
for to in v.successors:
inDegree[to.number] -= 1
if inDegree[to.number] == 0:
queue.enqueue(to)

class Graph(Container):

class CountingVisitor(Visitor):

def __init__(self):
super(Graph.CountingVisitor, self).__init__()
self._count = 0

def visit(self, obj):


self._count += 1

def getCount(self):

181
return self._count

count = property(
fget = lambda self: self.getCount())

def getIsConnected(self):
visitor = self.CountingVisitor()
self.depthFirstTraversal(PreOrder(visitor), 0)
return visitor.count == self.numberOfVertices
class Digraph(Graph):

def getIsStronglyConnected(self):
for v in xrange(self.numberOfVertices):
visitor = self.CountingVisitor()
self.depthFirstTraversal(PreOrder(visitor), v)
if visitor.count != self.numberOfVertices:
return False
return True

class Digraph(Graph):

def getIsCyclic(self):
visitor = self.CountingVisitor()
self.topologicalOrderTraversal(visitor)
return visitor.count != self.numberOfVertices

class Algorithms(object):

class Entry(object):

def __init__(self):
self.known = False
self.distance = sys.maxint
self.predecessor = sys.maxint

class Algorithms(object):

def DijkstrasAlgorithm(g, s):


n = g.numberOfVertices
table = Array(n)
for v in xrange(n):
table[v] = Algorithms.Entry()
table[s].distance = 0
queue = BinaryHeap(g.numberOfEdges)
queue.enqueue(Association(0, g[s]))
while not queue.isEmpty:
assoc = queue.dequeueMin()
v0 = assoc.value
if not table[v0.number].known:
table[v0.number].known = True

182
for e in v0.emanatingEdges:
v1 = e.mateOf(v0)
d = table[v0.number].distance + e.weight
if table[v1.number].distance > d:

table[v1.number].distance = d
table[v1.number].predecessor = v0.number
queue.enqueue(Association(d, v1))
result = DigraphAsLists(n)
for v in xrange(n):
result.addVertex(v, table[v].distance)
for v in xrange(n):
if v != s:
result.addEdge(v, table[v].predecessor)
return result
DijkstrasAlgorithm = staticmethod(DijkstrasAlgorithm)

class Algorithms(object):

def FloydsAlgorithm(g):
n = g.numberOfVertices
distance = DenseMatrix(n, n)
for v in xrange(n):
for w in xrange(n):
distance[v, w] = sys.maxint
for e in g.edges:
distance[e.v0.number, e.v1.number] = e.weight
for i in xrange(n):
for v in xrange(n):
for w in xrange(n):
if distance[v, i] != sys.maxint and \
distance[i, w] != sys.maxint:
d = distance[v, i] + distance[i, w]
if distance[v, w] > d:
distance[v, w] = d
result = DigraphAsMatrix(n)
for v in xrange(n):
result.addVertex(v)
for v in xrange(n):
for w in xrange(n):
if distance[v, w] != sys.maxint:
result.addEdge(v, w, distance[v, w])
return result
FloydsAlgorithm = staticmethod(FloydsAlgorithm)
class Algorithms(object):

def PrimsAlgorithm(g, s):


n = g.numberOfVertices
table = Array(n)

183
for v in xrange(n):
table[v] = Algorithms.Entry()
table[s].distance = 0
queue = BinaryHeap(g.numberOfEdges)
queue.enqueue(Association(0, g[s]))
while not queue.isEmpty:
assoc = queue.dequeueMin()
v0 = assoc.value
if not table[v0.number].known:
table[v0.number].known = True
for e in v0.emanatingEdges:
v1 = e.mateOf(v0)
d = e.weight
if not table[v1.number].known and \
table[v1.number].distance > d:
table[v1.number].distance = d
table[v1.number].predecessor = v0.number
queue.enqueue(Association(d, v1))
result = GraphAsLists(n)
for v in xrange(n):
result.addVertex(v)
for v in xrange(n):
if v != s:
result.addEdge(v, table[v].predecessor)
return result
PrimsAlgorithm = staticmethod(PrimsAlgorithm)

class Algorithms(object):

def KruskalsAlgorithm(g):
n = g.numberOfVertices
result = GraphAsLists(n)
for v in xrange(n):
result.addVertex(v)
queue = BinaryHeap(g.numberOfEdges)
for e in g.edges:
weight = e.weight
queue.enqueue(Association(weight, e))
partition = PartitionAsForest(n)
while not queue.isEmpty and partition.count > 1:
assoc = queue.dequeueMin()
e = assoc.value
n0 = e.v0.number
n1 = e.v1.number
s = partition.find(n0)
t = partition.find(n1)
if s != t:
partition.join(s, t)
result.addEdge(n0, n1)
return result

184
KruskalsAlgorithm = staticmethod(KruskalsAlgorithm)

class Algorithms(object):

class EarliestTimeVisitor(Visitor):

def __init__(self, earliestTime):


super(Algorithms.EarliestTimeVisitor,self).__init__()
self._earliestTime = earliestTime

def visit(self, w):


t = self._earliestTime[0]
for e in w.incidentEdges:
t = max(t,
self._earliestTime[e.v0.number] + e.weight)
self._earliestTime[w.number] = t
class Algorithms(object):

def criticalPathAnalysis(g):
n = g.numberOfVertices

earliestTime = Array(n)
earliestTime[0] = 0
g.topologicalOrderTraversal(
Algorithms.EarliestTimeVisitor(earliestTime))

latestTime = Array(n)
latestTime[n - 1] = earliestTime[n - 1]
g.depthFirstTraversal(PostOrder(
Algorithms.LatestTimeVisitor(latestTime)), 0)

slackGraph = DigraphAsLists(n)
for v in xrange(n):
slackGraph.addVertex(v)
for e in g.edges:
slack = latestTime[e.v1.number] - \
earliestTime[e.v0.number] - e.weight
slackGraph.addEdge(
e.v0.number, e.v1.number, e.weight)
return Algorithms.DijkstrasAlgorithm(slackGraph, 0)
criticalPathAnalysis = staticmethod(criticalPathAnalysis)

185
Grafica

from turtle import *


color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()

186
Programarea bazelor de date
https://www.filehorse.com/download-python-32/20735/

187
https://www.filehorse.com/download-python-32/6427/

188
189
La toate aleg optiunea de mai jos

190
191
https://sourceforge.net/projects/mysql-python/files/

192
193
194
import MySQLdb
import MySQLdb as mysql
help(MySQLdb._mysql)
In visual studio rulam astfel

195
196
197
198
Caut pe internetutilitarele care le import ca sa ruleze aplicatiile

199
Crearea claselor si functiilor specifice
class Car:
'Common base class for all cars'
carCount = 0

def __init__(self, name, year):


self.name = name
self.year = year
Car.carCount += 1

def displayCount(self):
print ("Total Car %d" % Car.carCount)

200
def displayCar(self):
print ("Name : ", self.name, ", Year: ", self.year)

#This would create first object of Car class"


car1 = Car("Honda", 2000)
#This would create second object of Car class"
car2 = Car("BMW", 2017)
car1.displayCar()
car2.displayCar()
print ("Total Car %d" % Car.carCount)

class MyClass(object):
def __init__(self, number):
self.number = number

201
my_objects = []

for i in range(100):
my_objects.append(MyClass(i))

# later

for obj in my_objects:


print (obj.number)

class Car:
print("Car created")

202
class car(object):

def __init__(self):
self.__mileage = 16

def getMileage(self):
print(self.__mileage)

def setMileage(self,mileage):
self.__mileage = mileage

volvo = car()
volvo.getMileage()
volvo.setMileage(20)
volvo.getMileage()

203
class car:
"this is my first car"
a=10
def func(self):
print ("Nice Ride!")

204
class Man:
def sayHi(self,name=None):
if name is not None:
print("Hi " + name)
else:
print("Hi!")

obj = Man()
obj.sayHi()
obj.sayHi("James")
APELUL UNEI CLASE CA SI OBIECT SE NUMESTE INSTANTA
class Car:

# Class variables
vehicle_type = "suv"

205
model = "S90"

# Constructor method with instance variables brand and cost


def __init__(self, brand, cost):
self.brand = brand
self.cost = cost

# Method with instance variable followers


def fan_follow(self, follow):
print("This user has " + str(follow) + " follow")

def main():
# First object, set up instance variables of constructor method
car = Car("Volvo", 7)

# Print out instance variable brand


print(car.brand)

# Print out class variable cost


print(car.cost)

# Second object
suv = Car("Audi", 15)

# Print out instance variable brand


print(suv.brand)
print(suv.cost)

# Use set_followers method and pass followers instance variable


suv.fan_follow(77)

# Print out class variable vehicle_type


print(suv.vehicle_type)

if __name__ == "__main__":
main()

206
Car1_price = 5000
print (Car1_price)

Car2_price = Car1_price
if (id(Car1_price) == id(Car2_price)):
print("Car1 and Car2 have same object value & Memory ID = ", hex(id(Car1_price)))

Car1_price = Car1_price + 10
if (id(Car1_price) != id(Car2_price)):
print("Car1 and Car2 have different object value & Memory ID = ",
hex(id(Car1_price)),"&", hex(id(Car2_price)))

Car3_price = 5000
if (id(Car2_price)==id(Car3_price)):
print("Car2 and Car3 have same memory value & Memory ID = ", hex(id(Car3_price)))

207
else:
print("Car2 and Car3 have different object value & Memory ID = ", hex(id(Car3_price)))

Car1_price = None
print("Value is None")
print("Garbage Collector emptied the memory")

208
class Car:
def start(self):
print("Car started")

def reverse(self):
print("Car taking reverse")

def speed(self):
print("top speed = 200")

def main():
volvo=Car()
volvo.start()
volvo.reverse()
volvo.speed()

209
if __name__ == "__main__":
main()

x=10
print(type(x))

y=x
if (id(x)==id(y)):
print(" x and y are using same refernce object")

x=x+1
if (id(x)!=id(y)):
print(" x and y are using different refernce object")

z=10

210
if (id(x)!=id(y)):
print(" y and z are using same refernce object")
else:
print(" y and z are using diffenent refernce object")
NOTIUNEA DE CONSTRUCTOR AL UNEI CLASE

class Car:
#construct - paramterized constuctor
def __init__(self,name):
print("This is parameterized constructor")
self.name=name

def model(self):
print("my first car",self.name)

volvo=Car("Volvo S90")

211
volvo.model()
class Car:
def __init__(self):
self.color = None
self.type = None

def fill(self, fuel):


self.type = fuel

def empty(self):
self.type = None

redCar = Car()
redCar.color = "red"
redCar.type = "gas"
redCar.empty()
redCar.fill("petrol")
STERGEREA DIN MEMORIE A UNUI CONSTRUCTOR SE NUMESTE DESTRUCTOR
class Car:
def __init__(self):
print("Car created")

def __del__(self):
print("Destructor is called, Car is deleted")

volvo=Car()
del volvo

212
213
class Parents:
def gen(self):
x=1
print(x)

class Father(Parents):
pass

class Mother(Parents):
pass

class Child(Father,Mother):
pass

childobj=Child()

214
childobj.gen()

class Triangle():
def __init__(self,base,height):
self.base = base
self.height = height

def getArea(self):
print(self.base*self.height/2,"is area of triangle")

class Square(Triangle):
def __init__(self,side):
self.side = side
Triangle.__init__(self,side,side)

def getArea(self):

215
print(self.side*self.side,"is area of square")

t = Triangle(2,6)
s = Square(4)
t.getArea()
s.getArea()

import sys

anyList = ['X', 0, 10]

for entry in anyList:


try:
print("Entry is ",entry)
R = 1/int(entry)

216
break

except:
print("OOPs!", sys.exc_info()[0], "Occured.")
print("Next Entry.")
print()

print("Reciprocal of", entry, "is", R)

try:
n1, n2 = eval(input("Input 2 Numbers, Separated by comma: "))
ans = n1/n2
print("Answer :", ans)

except ZeroDivisionError:
print("Division by Zero is Error!")

217
except SyntaxError:
print("Comma is missing. Enter Numbers separated by comma. Eg: 5,6 ")

except:
print("Wrong Input")

else:
print("No Exception")

finally:
print("This will execute no matter what")

class Error(Exception):
"""Base Class of other exceptions"""
pass

218
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

#out main program


#user guesses a number until he/she is right

#you need to guess this number


number = 10

while True:
try:
i_num = int(input("Enter a number :"))

if i_num < number:


raise ValueTooSmallError

elif i_num > number:


raise ValueTooLargeError

break

except ValueTooSmallError:
print("This value is too small, try again!!")
print()

except ValueTooLargeError:
print("This value is too large, try again!!")
print()

print("Congratulation! You guessed it correctly.")

219
import math

class Circle:

def __init__(self, radius):


self.__radius = radius

def setRadius(self, radius):


self.__radius = radius

def getRadius(self):
return self.__radius

def area(self):
return math.pi * self.__radius ** 2

220
def __add__(self, another_circle):
return Circle(self.__radius + another_circle.__radius)

def __sub__(self, another_circle):


return Circle(self.__radius - another_circle.__radius)

c1 = Circle(8)
print(c1.getRadius())

c2 = Circle(10)
print(c2.getRadius())

c3 = c1 + c2
print(c3.getRadius())

c3 = c2 - c1
print(c3.getRadius())

221
class car:

__topspeed = 0
__name=""

def __init__(self):
self.__topspeed=250
self.name="SAM"

def drive(self):
print("Drive Top Speed=" +str(self.__topspeed))

def setTopSpeed(self,speed):
self.__topspeed=speed

222
volvo=car()
volvo.drive()
volvo.setTopSpeed(380)
volvo.drive()

def fact(x):

if x==1:
return 1
else:
return (x * fact (x-1))

numb= 5

print("factorial of", numb, "is", fact(numb))


APLICATII ELEMENTARE GIMNAZIU

223
length = 5
breadth = 2
area = length * breadth
print ('Area is', area)
print ('Perimeter is', 2 * (length + breadth))
import math
a = 4.0
x = 3.0
y = (x + a/x) / 2
print (y)
import math
a = 4.0
x = 3.0
y = (x + a/x) / 2
print (y)

224
X=5
eval('math.sqrt(3)')
Recursivitate

Neverificate
1)
def countdown(n):
if n <= 0:
print 'Blastoff!'
else:
print n
countdown(n-1)
countdown(3)
2)
def print_n(s, n):
if n <= 0:
return
print s
print_n(s, n-1)
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
radius = distance(xc, yc, xp, yp)
result = area(radius)
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))

def is_divisible(x, y):


if x % y == 0:
return True
else:
return False
is_divisible(6, 4)
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
def factorial (n):
if not isinstance(n, int):
print 'Factorial is only defined for integers.'
return None
elif n < 0:
print 'Factorial is only defined for positive integers.'
return None
elif n == 0:

225
return 1
else:
return n * factorial(n-1)

factorial(15)

def fibonacci (n):


if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

def b(z):
prod = a(z, z)
print z, prod
return prod
def a(x, y):
x=x+1
return x * y
def c(x, y, z):
sum = x + y + z
pow = b(sum)**2
return pow
x=1
y=x+1
print c(x, y+3, x+y)
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]

226

You might also like