Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Примеры работы циклов for и while для выполнения
- # одной и той же задачи. Время выполнение циклов
- a1 = 3 # Первый член арифметической прогрессии
- d = 4 # Разница между соседними членами арифметической прогрессии
- N = 6 # Количество членов арифметической прогрессии
- # Поиск суммы через цикл
- S_circle = 0 # Сумма подсчитанная перебором через цикл
- for k in range(1, N + 1):
- ak = a1 + ( k - 1 )*d
- S_circle = S_circle + ak
- print('Сумма арифметической прогрессии через цикл: ', S_circle)
- # Поиск суммы через теоретическую формулу
- S_general = 0.5*(2*a1 + (N-1)*d)*N # Сумма подсчитанная перебором через цикл
- print('Сумма арифметической прогрессии через формулу: ', S_general)
- for k in range(0, 10):
- print('for: Итерация №',k)
- k = 0
- while(k < 10):
- print('while: Итерация №',k)
- k += 1
- # Попытка профилирования кода
- import timeit
- code_for = '''
- numberOfElements = 4
- amount = 0
- for currentElement in range(1, numberOfElements + 1):
- amount = amount + 1 / currentElement
- '''
- code_while = '''
- currentElement = 1
- numberOfElements = 4
- amount = 0
- while(currentElement <= numberOfElements):
- amount = amount + 1 / currentElement
- currentElement = currentElement + 1
- '''
- execution_time_for = timeit.timeit(code_for, number = 1000000)
- execution_time_while = timeit.timeit(code_while, number = 1000000)
- print('Время выполнения цикла FOR: ', execution_time_for)
- print('Время выполнения цикла WHILE: ', execution_time_while)
- # Примеры работы
- currentElement = 1
- numberOfElements = 4
- amount = 0
- while(currentElement <= numberOfElements):
- amount = amount + 1 / currentElement
- currentElement = currentElement + 1
- numberOfElements = 4
- amount = 0
- for currentElement in range(1, numberOfElements + 1):
- amount = amount + 1 / currentElement
- print('while: Сумма первых {} \
- членов ряда равна: {}'.format(numberOfElements, amount))
- print('for: Сумма первых {} \
- членов ряда равна: {}'.format(numberOfElements, amount))
- print('Дисассемблирование:')
- import dis
- def test_for():
- numberOfElements = 4
- amount = 0
- for currentElement in range(1, numberOfElements + 1):
- amount = amount + 1 / currentElement
- def test_while():
- currentElement = 1
- numberOfElements = 4
- amount = 0
- while(currentElement <= numberOfElements):
- amount = amount + 1 / currentElement
- currentElement = currentElement + 1
- print('Asm FOR:')
- print(dis.dis(test_for))
- print('Asm WHILE:')
- print(dis.dis(test_while))
Add Comment
Please, Sign In to add comment