3 Python
3 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
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
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'
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
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
34
>>> if x == 24:
... # un comentariu
... print "Salutari de pe www.invata-programare.ro."
...
Stergem ecranul
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
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
print("Python Calculator:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
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
38
Adaugare si stergere dintr-o lista
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"]
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))
# min and max will return minimum and maximum values in a sequence
print("min: ", min(list1))
print("max: ", max(list1))
if __name__ == "__main__":
main()
REZULTA
True
False
min: 0
max: 6
sum: 17
n1 = 0
n2 = 1
count = 0
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
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
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')
46
def say_hi(first, last):
print('Hi {} {}!'.format(first, last))
say_hi('Jane', 'Doe')
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)
display_facts(facts)
def demo_print_greeting():
print("TIK SI ADY!!")
def demo_local_variable():
a_variable = 7
a_variable ="TYK 007"
print(a_variable)
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
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
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_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()
55
'phone': '555-0987',
'email': '[email protected]'
}
}
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]))
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'
}
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)
60
contacts = {'Jason': '555-0123', 'Carl': '555-0987'}
contacts['Jason'] = '555-0000'
jasons_phone = contacts['Jason']
print('Dial {} to call Jason.'.format(jasons_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.')
63
if 37 < 40:
print('Thirty-seven is less than forty.')
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
class Employee():
def __init__(self, fname, lname, level, yrsService):
self.fname = fname
self.lname = lname
self.level = level
self.seniority = yrsService
67
return self.seniority >= other.seniority
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))
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
70
def main():
# create an instance of myColor
cls1 = myColor()
# print the value of a computed attribute
print(cls1.rgbcolor)
print(cls1.hexcolor)
if __name__ == "__main__":
main()
REZULTATUL
71
# define enumerations using the Enum base class
@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))
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)
def main():
# Declare some points
p1 = Point(10, 20)
p2 = Point(30, 30)
print(p1, p2)
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)
76
# TODO: implement subtraction
def __sub__(self, other):
pass
def main():
# Declare some points
p1 = Point(10, 20)
p2 = Point(30, 30)
print(p1, p2)
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
77
return bytes(val.encode('utf-8'))
def main():
# create a new Person object
cls1 = Person()
if __name__ == "__main__":
main()
REZULTATUL ESTE
def main():
# define a list of items that we want to count
fruits = ['apple', 'pear', 'orange', 'banana',
'apple', 'grape', 'banana', 'banana']
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)
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]
80
print(list(map(CelsisusToFahrenheit, 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!")
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])
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!")
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])
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="")
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))
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!")
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])
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="")
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))
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!")
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])
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="")
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))
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'}
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])
def demoForLoops():
#Print from 0 to 4
print("\n*Print from 0 to 4")
for i in range(0,5):
print(i, ' ', end="")
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'}
def main():
#demoIf()
#demoLists()
#demoForLoops()
#demoWhileLoops()
demoDictionary()
if __name__== "__main__":
main()
94
APLICATII DIVERSE
MULTIMI
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
96
Created on Mar 31, 2018
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)
98
Created on Mar 31, 2018
99
print(number_tuple)
print(letter_tuple)
print(mixed_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
100
101
102
APAS ATCH
103
104
SE POATE SI DIRECT
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 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")
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
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
@employee_name.setter
def employee_name(self, value):
116
self.__name = value + " (Name changed. Someone quit!)"
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
# Constructor
def __init__(self, name):
self.__name = name #When values are passed in, define them.
119
self.__name = name
def get_name(self):
return self.__name.upper()
def main():
#Create employee object
anEmployee = Employee('james')
# Execute code
print(anEmployee.getIntro())
if __name__== "__main__":
main()
120
121
122
ESTE ECHIVALENTUL Python
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)
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)
# 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
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
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))
128
programare vizuala cu obiecte
129
import tkinter
tkinter.Tk().mainloop()
tk.Entry(gui).\
grid(row=0, column=2) # using grid layout manager
130
Created on May 7, 2018
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.mainloop()
o ferestra cu titlu
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
131
gui.title("Our GUI Title")
gui.mainloop()
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
132
tk.Entry(frame, textvariable=tk.StringVar(value=" <default entry>")).\
grid(row=0, column=2)
gui.mainloop()
eticheta active
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
def button_callback():
entry.config(textvariable=tk.StringVar(value=' Button was clicked!'))
133
child.grid_configure(padx=10, pady=10)
gui.mainloop()
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
entry_list = []
def button_callback(idx):
entry_list[idx].config(textvariable=tk.StringVar(value=' Button {} was clicked!'.\
format(idx)))
134
entry_list.append(entry_var)
gui.mainloop()
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
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')
135
ttk.Button(frame, text="Click Me " + str(idx), command= lambda cur_idx=idx:
button_callback(cur_idx)).\
grid(row=idx, column=1)
gui.mainloop()
136
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
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')
gui.mainloop()
137
Created on May 8, 2018
import tkinter as tk
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
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']
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()
import tkinter as tk
140
from tkinter import ttk
gui = tk.Tk()
gui.title("Our GUI Title")
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']
141
frame_2 = ttk.LabelFrame(gui, text="Another frame")
frame_2.pack(padx=10, pady=5)
gui.update()
gui_width = gui.winfo_width()
progress_bar = ttk.Progressbar(gui, length=gui_width, mode='determinate')
progress_bar.pack()
gui.mainloop()
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')
note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)
142
note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)
gui.mainloop()
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 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')
note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)
note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)
144
gui.mainloop()
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
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')
note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)
note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)
gui.mainloop()
146
Created on May 8, 2018
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
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 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')
note1 = ttk.Notebook(tabs_frame)
note1.grid(row=0, column=0)
note2 = ttk.Notebook(tabs_frame)
note2.grid(row=1, column=0)
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)
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")
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')
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')
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))
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))
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 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)
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
159
def sum(n):
result = 0
i=1
while i <= n:
result += i
i += 1
return result
def factorial(n):
if n == 0:
return 1
else:
160
return n * factorial(n - 1)
def gamma():
result = 0.
i = 1
while i <= 500000:
result += 1.0/i - math.log((i + 1.0)/i)
i += 1
return result
161
return x * power(x * x, n / 2)
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 __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):
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 __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 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):
class TwoWayMergeSorter(Sorter):
def _sort(self):
self._tempArray = Array(self._n)
self.mergesort(0, self._n - 1)
self._tempArray = None
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__()
176
weight = property(
fget = lambda self: self.getWeight())
def __init__(self):
super(Edge, self).__init__()
177
#
class Graph(Container):
class Vertex(Vertex):
class Edge(Edge):
class Graph(Container):
178
def getIsCyclic(self): pass
getIsCyclic = abstractmethod(getIsCyclic)
isCyclic = property(
fget = lambda self: self.getIsCyclic())
class Graph(Container):
def __len__(self):
return self.numberOfVertices
179
class Digraph(Graph):
class GraphAsLists(Graph):
class Graph(Container):
180
class Graph(Container):
class Digraph(Graph):
class Graph(Container):
class CountingVisitor(Visitor):
def __init__(self):
super(Graph.CountingVisitor, self).__init__()
self._count = 0
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):
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):
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 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
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 displayCount(self):
print ("Total Car %d" % Car.carCount)
200
def displayCar(self):
print ("Name : ", self.name, ", Year: ", self.year)
class MyClass(object):
def __init__(self, number):
self.number = number
201
my_objects = []
for i in range(100):
my_objects.append(MyClass(i))
# later
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"
def main():
# First object, set up instance variables of constructor method
car = Car("Volvo", 7)
# Second object
suv = Car("Audi", 15)
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 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
216
break
except:
print("OOPs!", sys.exc_info()[0], "Occured.")
print("Next Entry.")
print()
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
while True:
try:
i_num = int(input("Enter a number :"))
break
except ValueTooSmallError:
print("This value is too small, try again!!")
print()
except ValueTooLargeError:
print("This value is too large, try again!!")
print()
219
import math
class Circle:
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)
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
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))
225
return 1
else:
return n * factorial(n-1)
factorial(15)
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