Bring Your Logic using Python
341 subscribers
109 photos
1 video
4 files
544 links
Logic building using Python : Materials, links, e-books and Code snippets
Download Telegram
# itertools.permutations() generates
# permutations for an iterable.
# Time to brute-force those passwords

>>> import itertools
>>> for p in itertools.permutations('ABCD'):
... print(p)


('A', 'B', 'C', 'D')
('A', 'B', 'D', 'C')
('A', 'C', 'B', 'D')
('A', 'C', 'D', 'B')
('A', 'D', 'B', 'C')
('A', 'D', 'C', 'B')
('B', 'A', 'C', 'D')
('B', 'A', 'D', 'C')
('B', 'C', 'A', 'D')
('B', 'C', 'D', 'A')
('B', 'D', 'A', 'C')
('B', 'D', 'C', 'A')
('C', 'A', 'B', 'D')
('C', 'A', 'D', 'B')
('C', 'B', 'A', 'D')
('C', 'B', 'D', 'A')
('C', 'D', 'A', 'B')
('C', 'D', 'B', 'A')
('D', 'A', 'B', 'C')
('D', 'A', 'C', 'B')
('D', 'B', 'A', 'C')
('D', 'B', 'C', 'A')
('D', 'C', 'A', 'B')
('D', 'C', 'B', 'A')
# When To Use repr vs str?
# Emulate what the std lib does:
>>> import datetime
>>> today = datetime.date.today()

# Result of str should be readable:
>>> str(today)
'2020-04-27’


# Result of repr should be unambiguous:
>>> repr(today)
'datetime.date(2020,4,27)’


# Python interpreter sessions use
# repr to inspect objects:
>>> today
datetime.date(2020,4,27)
# You can use Python's built-in "dis"
# module to disassemble functions and
# inspect their CPython VM bytecode:

>>> def greet(name):
... return 'Hello, ' + name + '!'

>>> greet('Dan')
'Hello, Dan!'

>>> import dis
>>> dis.dis(greet)
2 0 LOAD_CONST 1 ('Hello, ')
2 LOAD_FAST 0 (name)
4 BINARY_ADD
6 LOAD_CONST 2 ('!')
8 BINARY_ADD
10 RETURN_VALUE
Beware of nan!  
😱#python

>>> sorted([5.0, math.nan, 10.0, 0.0])
[5.0, nan, 0.0, 10.0]

>>> sorted([math.nan, 1.0])
[nan, 1.0]
>>> sorted([1.0, math.nan])
[1.0, nan]

>>> min(3, math.nan, 1)
1
>>> min(math.nan, 3, 1)
nan


#pythontip
In the python document it says that math.nan is the same as float("nan")
Do you want to avoid problems with math.nan? Then use #numpy!

> np.sort([5., math.nan, 10., 0.])
array([ 0., 5., 10., nan])

> np.sort([math.nan, 1.])
array([ 1., nan])
> sorted([1., math.nan])
array([ 1., nan])

> np.max([3., math.nan, 1.])
nan
> np.nanmax([3., math.nan, 1.])
3.0
# The lambda keyword in Python provides a
# shortcut for declaring small and
# anonymous functions:

>>> add = lambda x, y: x + y
>>> add(5, 3)

8

# You could declare the same add()
# function with the def keyword:

>>> def add(x, y):
... return x + y
>>> add(5, 3)

8

# So what's the big fuss about?
# Lambdas are *function expressions*:
>>> (lambda x, y: x + y)(5, 3)
8

# β€’ Lambda functions are single-expression
# functions that are not necessarily bound
# to a name (they can be anonymous).

# β€’ Lambda functions can't use regular
# Python statements and always include an
# implicit return statement.
# @classmethod vs @staticmethod vs "plain" methods
# What's the difference?

class MyClass:
def method(self):

"""

Instance methods need a class instance and can access the instance through self.
"""
return 'instance method called', self

@classmethod
def classmethod(cls):

"""

Class methods don't need a class instance. They can't access the instance (self) but they have access to the class itself via cls.
"""

return 'class method called', cls

@staticmethod
def staticmethod():

"""

Static methods don't have access to cls or self. They work like regular functions but belong to the class's namespace.
"""
return 'static method called'

# All methods types can be
# called on a class instance:

>>> obj = MyClass()
>>> obj.method()

('instance method called', <MyClass instance at 0x1019381b8>)

>>> obj.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)

>>> obj.staticmethod()
'static method called'

# Calling instance methods fails
# if we only have the class object:

>>> MyClass.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)

>>> MyClass.staticmethod()
'static method called'

>>> MyClass.method()
TypeError:
"unbound method method() must be called with MyClass "
"instance as first argument (got nothing instead)"
If the local date format us DD/MM/YYYY, you can use the dayfirst=True argument in dateutil.parser.parse:

>>> from dateutil.parser import parse
>>> s = '6.5.2020'
>>> parse(s)
datetime.datetime(2020, 6, 5, 0, 0)
>>> parse(s, dayfirst=True)
datetime.datetime(2020, 5, 6, 0, 0)
Do you need something like range() but with float numbers? Try numpy.arange()

>>> range(0, 5, 0.5) #Error!

>>> np.arange(0, 5, 0.5)
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])


If you need exactly X steps, but one step is not a short decimal number, you can use:

>>> np.linspace(0, 1, 4)
array([0., 0.3333333, 0.6666667, 1.])
# In Python 3.4+ you can use
# contextlib.suppress() to selectively
# ignore specific exceptions:

import contextlib

with contextlib.suppress(FileNotFoundError):
os.remove('somefile.tmp')

# This is equivalent to:

try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass

# contextlib.suppress docstring:
#
# "Return a context manager that suppresses any
# of the specified exceptions if they occur in the body
# of a with statement and then resumes execution with
# the first statement following the end of
# the with statement."
What is the difference between __str__ and __repr__ in #Python?

In short, the goal of __repr__ is to be unambiguous and __str__ is to be readable.

==> "__repr__ is for developers, __str__ is for customers."
πŸπŸ“° Introduction to Git and GitHub for Python Developers

What is Git, what is GitHub, and what's the difference? Learn the basics of Git and GitHub from the perspective of a Pythonista in this tutorial
#python

https://realpython.com/python-git-github-intro/
πŸπŸ“Ί Reading and Writing CSV Files [Video]

This short course covers how to read and write data to CSV files using Python's built in "csv" module and the "pandas" library
#python