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
# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')

# Our new "Car" class works as expected:
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4

# We get a nice string repr for free:
>>> my_car
Car(color='red' , mileage=3812.4)

# Like tuples, namedtuples are immutable:
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"
>>import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than the nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!



For more information check this link: https://stackoverflow.com/questions/5855758/what-is-the-source-code-of-the-this-module-doing?__s=jiqhbmujrpzk42psnkek
# The standard string repr for dicts is hard to read:
>>> my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
>>> my_mapping
{'b': 42, 'c': 12648430. 'a': 23} #


# The "json" module can do a much better job:
>>> import json
>>> print(json.dumps(my_mapping, indent=4, sort_keys=True))
{
"a": 23,
"b": 42,
"c": 12648430
}


# Note this only works with dicts containing
# primitive types (check out the "pprint" module):
>>> json.dumps({all: 'yup'})
TypeError: keys must be a string
# Why Python Is Great:
# Function argument unpacking

def myfunc(x, y, z):
print(x, y, z)

tuple_vec = (1, 0, 1)
dict_vec = {'x': 1, 'y': 0, 'z': 1}

>>> myfunc(*tuple_vec)
1, 0, 1

>>> myfunc(**dict_vec)
1, 0, 1
# To measure the execution time of your code
# The "timeit" module lets you measure the execution
# time of small bits of Python code

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)


0.3412662749997253

>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)

0.2996307989997149

>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)

0.24581470699922647
Execution time will differ from machine to machine depends on your computing architecture.
timeit runs your snippet of code millions of time (default value is 1000000) so that you get the statistically most relevant measurement of code execution time!
The module function timeit.timeit(stmt, setup, timer, number) accepts four arguments:
• stmt which is the statement you want to measure; it defaults to ‘pass’.
• setup which is the code that you run before running the stmt; it defaults to ‘pass’. We generally use this to import the required modules for our code.
• timer which is a timeit.Timer object; it usually has a sensible default value so you don’t have to worry about it.
• number which is the number of executions you’d like to run the stmt.
Python '!=' Is Not 'is not': Comparing Objects in Python

In this tutorial, you’ll learn:
• What the difference is between object equality and identity
• When to use equality and identity operators to compare objects
• What these Python operators do under the hood
• Why using is and is not to compare values leads to unexpected behavior
• How to write a custom __eq__() class method to define equality operator behavior

https://realpython.com/python-is-identity-vs-equality/
This media is not supported in your browser
VIEW IN TELEGRAM
None is evaluated as False so you can write

>>> results = None
>>> print(results or "No results")
============24th April 2020=======
# "is" vs "=="

>>> a = [1, 2, 3]
>>> b = a

>>> a is b

True
>>> a == b
True

>>> c = list(a)

>>> a == c

True
>>> a is c
False

# • "is" expressions evaluate to True if two
# variables point to the same object

# • "==" evaluates to True if the objects
# referred to by the variables are equal
———First class Functions—————
# Functions are first-class citizens in Python:

# They can be passed as arguments to other functions,
# returned as values from other functions, and
# assigned to variables and stored in data structures.

>>> def myfunc(a, b):
... return a + b
...
>>> funcs = [myfunc]
>>> funcs[0]

<function myfunc at 0x107012230>

>>> funcs[0](2, 3)
5
No switch case in Python. However, we can emulate it with the help of first class function feature of Python.
# Because Python has first-class functions they can
# be used to emulate switch/case statements

def dispatch_if(operator, x, y):
if operator == 'add':
return x + y
elif operator == 'sub':
return x - y
elif operator == 'mul':
return x * y
elif operator == 'div':
return x / y
else:
return None


def dispatch_dict(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()


>>> dispatch_if('mul', 2, 8)

16

>>> dispatch_dict('mul', 2, 8)
16

>>> dispatch_if('unknown', 2, 8)
None

>>> dispatch_dict('unknown', 2, 8)
None