Scientific Programming with Python

Scientific Programming with Python

Learn from this GitHub

Create your first package

1. Create the following files and directories

1
2
3
4
5
6
micro/
├── micro/
│ ├── __init__.py
├── README.md
├── LICENSE.md
├── setup.py

2. Add the following to setup.py

1
2
3
4
5
6
7
8
9
10
11
from setuptools import setup
setup(name='example',
version='0.1',
description='The ultimate example',
url='http://github.com/author/example',
author='Author Name',
author_email='author@example.com',
license='MIT',
packages=['example'],
zip_safe=False)

3. Now, from the top level micro directory, install the package using pip:

$pip install -e .

4. Try to import the micro package from Python:

In [1]: import micro

5. You should always also have a README.md and LICENSE.md:

6. Finally, upload to GitHub


  • init a git for micro in your own computer.
  • create a new repository in your GitHub and upload the whole micro into it.
  • running the following code to install micro package from the GitHub:
    • pip install git+https://github.com/username/micro

Python-testing

Function description

so we could see the description when type help(strflip)

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
def strflip(s):
"""
strflip: Flip a string
Parameters
----------
s : str
String to reverse
Returns
flipped : str
Copy of `s` with characters in reverse order
"""
flipped = ''
# Starting from the last character in `s`,
# add the character to `flipped`,
# and proceed to the previous character in `s`.
# Stop whenever we reach the first character.
i = len(s)
while True:
i = i-1
char = s[i]
flipped = flipped + char
# stop if we have reached the first character:
if char == s[0]:
break
return flipped
```
also, we need to know about ``assert``:

assert(strflip(‘ab’) == ‘ba’)
assert(strflip(‘mario’) == ‘oiram’)

1
2
3
4
5
6
### pytest
create a new .py file with ``test`` prefix.
code as(only show the first error if there exists many) :

from strflip import strflip

assert(strflip(‘’) == ‘’)

1
2
or

def test_empty_string():
assert(strflip(‘’) == ‘’)
```

if we want to see the output from these test functions, we could:

pytest -s

Performance

using %timeit or %prun in IPYTHON to see the performance of a function.