Last active
December 9, 2017 17:28
-
-
Save coto/466c3ae0e7420687f1ac89c42f1ca776 to your computer and use it in GitHub Desktop.
Python... List, tuples, classes, properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
__author__ = '@coto' | |
# Detect numbers even if they are complex | |
def is_number(s): | |
try: | |
float(s) # for int, long and float | |
except ValueError: | |
try: | |
complex(s) # for complex | |
except ValueError: | |
return False | |
return True | |
def suma(a=0.0, b=0.0): | |
"""Sum. | |
Keyword arguments: | |
a -- number (default 0.0) | |
b -- number (default 0.0) | |
""" | |
return a + b | |
def sumatoria(l): | |
"""Sum. | |
Keyword arguments: | |
l -- range | |
""" | |
return sum(l) | |
def factorial(n): | |
"""Sum. | |
Keyword arguments: | |
n -- number | |
""" | |
if n == 0: | |
return 1 | |
return reduce(int.__mul__, range(1, n + 1)) | |
def merssene(n): | |
""" In mathematics, a Mersenne prime is a prime number of the form M_n=2^n-1 | |
Keyword arguments: | |
n -- number | |
""" | |
return ((2 ** n) - 1) | |
def merssene_closure(y, x): | |
return lambda n: y ** n - x | |
def prime_list(n): | |
return map(merssene, range(1, n + 1)) | |
def prime_list_ho(n): | |
return map(lambda x: merssene(x), range(1, n + 1)) | |
def prime_list_closure(n): | |
return map(merssene_closure(2, 1), range(1, n + 1)) | |
def prime_list_closure_arg(n, f): | |
return map(f, range(1, n + 1)) | |
print(" ---8<--- Python ---8<---") | |
print("suma (1+3)................: %d" % (suma(1, 3))) | |
print("sumatoria (0->6)...........: %d" % (sumatoria(range(0, 6)))) | |
print("factorial (2)...........: %d" % (factorial(2))) | |
print("factorial (6)...........: %d" % (factorial(6))) | |
print("merssene (2)............: %d" % (merssene(2))) | |
print("merssene (3)............: %d" % (merssene(3))) | |
print("> map merssene range") | |
print("prime_list (10): %s" % (repr(prime_list(10)))) | |
print("> map lambda merssene range") | |
print("prime_list_ho (10): %s" % (repr(prime_list_ho(10)))) | |
print("> map merssene_closure range") | |
print("prime_list_clo (10): %s" % (repr(prime_list_closure(10)))) | |
print("> repr map merssene_closure range") | |
print("prime_list_clo_arg (10): %s" % (repr(prime_list_closure_arg(10, merssene_closure(2, 1))))) | |
# Create a list of range between -6 to +6 by 2 | |
list(range(-6, 7, 2)) | |
# reverse by words | |
s = "hi, how are you?" | |
l1 = s.split() | |
l1.reverse() | |
' '.join(l1) | |
# > 'you? are how hi,' | |
# reverse by characters | |
l2 = list(s) | |
l2.reverse() | |
''.join(l2) # ?uoy era woh ,ih | |
# Sum group of lists | |
N = [[2, 3, 100], [4, 5], [1, 1]] | |
G = (sum(row) for row in N) | |
next(G) # 105 | |
next(G) # 9 | |
next(G) # 2 | |
# List of lists -> Lists of Tuples | |
my_list = zip(['name', 'last_name'], ['rodrigo', 'augosto']) # [('name', 'rodrigo'), ('last_name', 'augosto')] | |
# Lists of tuples -> Dictionary | |
coto = dict(my_list) # {'last_name': 'augosto', 'name': 'rodrigo'} | |
# Tuples to Dictionary | |
sequence = [(1, 2), (3, 4), (5, 6)] | |
d = {key: value for (key, value) in sequence} | |
# d = {1: 2, 3: 4, 5: 6} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# -*- coding: utf8 -*- | |
__author__ = '@coto' | |
class Rectangle(object): | |
""" Rectangle Object """ | |
def __call__(self, param): | |
# Implements function call operator. | |
print("hello {}".format(param)) | |
def __init__(self): | |
# the self variable represents the instance of the object itself. | |
# Constructor for instances, it will overwrite Class attributes | |
# when it is called | |
self._name = 'Public Name' | |
self._height = 220 | |
_name = 'Private Class Atribute' | |
_another_private = 'Another Private Class Atribute' | |
@property | |
def height(self): | |
return self._height | |
@height.setter | |
def height(self, value): | |
self._height = value/2 | |
@height.deleter | |
def height(self): | |
del self._height | |
@staticmethod | |
def my_static_method(param1, param2): | |
# Only Params | |
return "Hello %s and %s" % (param1, param2) | |
@classmethod | |
def my_class_method(cls, param1): | |
# First Param is this Class Object | |
return "Hello %s and %s" % (cls._name, param1) | |
print "p = Rectangle()" | |
def print_values(param): | |
print(">>> {}:\t {}".format(param, eval(param))) | |
p = Rectangle() | |
print("\n-------- __dict__ ----------") | |
print_values("Rectangle.__dict__") # a lot of information | |
print_values("p.__dict__") # {'_private': 'inside', '_height': 220} | |
print "\n-------- __doc__ ----------" | |
print_values("Rectangle.__doc__") # Describe the electricity | |
print_values("p.__doc__") # Describe the electricity | |
print "\n-------- _private ----------" | |
print_values("Rectangle._name") # outside | |
print_values("p._name") # inside | |
print "\n-------- _another_private ----------" | |
print_values("Rectangle._another_private") # inside class 2 | |
print_values("p._another_private") # inside class 2 | |
print "\n--------- _height property ---------" | |
try: | |
print_values("Rectangle._height") # Exception: 'Rectangle' has no attribute '_height' | |
except Exception, e: | |
print "Exception: %s " % e | |
print_values("p._height") | |
print "\n--------- Object p: Hualtata as a new value for _private ---------" | |
p._name = "Hualtata" | |
print_values("Rectangle._name") # it will keep 'outside' | |
print_values("p._name") # it will be 'new private' | |
print "\n-------- height (setter and getter) ----------" | |
print_values("p.height") | |
p.height = 120 | |
print_values("p.height") | |
print "\n-------- @staticmethod ----------" | |
print p.my_static_method("pedro", "juan") | |
print "\n-------- @classmethod ----------" | |
print p.my_class_method("pedro") | |
print "\n-------- Class Person ----------" | |
class Person(object): | |
""" | |
Another way to create Properties | |
""" | |
def __init__(self): | |
self.first_name = None | |
self.last_name = None | |
def get_full_name(self): | |
return "%s %s" % (self.first_name, self.last_name) | |
def set_full_name(self, full_name): | |
self.first_name, self.last_name = full_name.split() | |
def del_full_name(self): | |
del self.__x | |
x = property(get_full_name, set_full_name, del_full_name, "I'm the 'x' property.") | |
boo = Person() | |
print "boo.__dict__ : \n\t %s \n" % boo.__dict__ | |
boo.x = "Rodrigo Augosto" | |
print boo.x |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Measuring performance internally | |
import timeit | |
s = """\ | |
try: | |
str.__nonzero__ | |
except AttributeError: | |
pass | |
""" | |
t = timeit.Timer(stmt=s) | |
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) | |
# Measuring performance externally | |
$ python - mtimeit - s"x = 123" "x**.5" [16:10:39] | |
10000000 loops, best of 3: 0.171 usec per loop | |
$ python - mtimeit - s"from math import sqrt; x = 123" "sqrt(x)" [16:13:00] | |
10000000 loops, best of 3: 0.12 usec per loop | |
$ python - mtimeit - s"import math; x = 123" "math.sqrt(x)" [16:13:14] | |
10000000 loops, best of 3: 0.166 usec per loop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment