Фишки Python
29 subscribers
2 photos
3 files
29 links
Всё что ты хотел узнать, но ленился спросить.

Декораторы, итераторы и контракты.
Download Telegram
cp ${f}.txt $bar : Variable expansion in magics and system commands
files = !ls /usr : Capture system command output
%writefile [-a] filename : Write the contents of the cell to a file.
Esc will take you into command mode where you can navigate around your notebook with arrow keys.

While in command mode:
A to insert a new cell above the current cell, B to insert a new cell below.
M to change the current cell to Markdown, Y to change it back to code
D + D (press the key twice) to delete the current cell
Enter will take you from command mode back into edit mode for the given cell.
Shift + Tab will show you the Docstring (documentation) for the the object you have just typed in a code cell - you can keep pressing this short cut to cycle through a few modes of documentation.
Ctrl + Shift + - will split the current cell into two from where your cursor is.
Esc + F Find and replace on your code but not the outputs.
Esc + O Toggle cell output.
Select Multiple Cells:
Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up.
Once cells are selected, you can then delete / copy / cut / paste / run them as a batch. This is helpful when you need to move parts of a notebook.
You can also use Shift + M to merge multiple cells.
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Вычисляет и отображает результат по каждой строке, пример:

from pydataset import data
q = data('quakes')
q.head()
q.tail()

Отобразит таблицу и head и tail
%run -d mysqcript.py - Запуск под отладчиком
%debug запуск отладчика после exception
list
Отображает текущее место в файле
h(elp)
Отображает список команд или справку по конкретной команде
q(uit)
Выход из отладчика и программы
c(ontinue)
Выход из отладчика, продолжение выполнения программы
n(ext)
Переход к следующему шагу программы
<enter>
Повтор предыдущей команды
p(rint)
Вывод значений переменных
s(tep)
Вход в подпрограмму
r(eturn)
Возврат из подпрограммы
Дональд Кнут: «Лучше не держать в голове подобные “малые” вопросы производительности, скажем, 97 % времени: преждевременная оптимизация — корень всех зол»
%time — длительность выполнения отдельного оператора;
%timeit — длительность выполнения отдельного оператора при неоднократном повторе, для большей точности;
%prun — выполнение кода с использованием профилировщика;
%lprun — пошаговое выполнение кода с применением профилировщика;
%memit — оценка использования оперативной памяти для отдельного оператора;
%mprun — пошаговое выполнение кода с применением профилировщика памяти.
Необходимо установить расширения line_profiler и memory_profiler
Профилирование

def sum_of_lists(N):
total = 0
for i in range(5):
L = [j ^ (j >> i) for j in range(N)]
total += sum(L)
return total

%prun sum_of_lists(1000000)

14 function calls in 1.089 seconds

Ordered by: internal time

ncalls tottime percall cumtime percall filename:lineno(function)
5 0.817 0.163 0.817 0.163 <ipython-input-1-f105717832a2>:4(<listcomp>)
5 0.220 0.044 0.220 0.044 {built-in method builtins.sum}
1 0.040 0.040 1.077 1.077 <ipython-input-1-f105717832a2>:1(sum_of_lists)
1 0.012 0.012 1.089 1.089 <string>:1(<module>)
1 0.000 0.000 1.089 1.089 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Загрузка расширения для IPython
%load_ext line_profiler
import statsmodels
defaultdict(lambda: 1) - создает структуру словаря с значением по умолчанию
scipy.stats.bernoulli - Bernoulli discrete random variable