Showing posts with label Python Programming Tips and Tricks. Show all posts
Showing posts with label Python Programming Tips and Tricks. Show all posts

Friday, June 18, 2021

A Cheatsheet for Python Built-in Functions (Part 2: C-D)

 A Cheatsheet for Python Built-in Functions (Part 2: C-D)


# *** callable() ***
def func0():
    pass
print(callable(func0))  # Output: True
# *** chr() ***
print(chr(65))  # Output: A
# *** classmethod() ***
# Note: The new @classmethod decorator should be used instead of 
# the built-in function classmethod().
class MyClass1:
    myProperty = 1234
    def myFunc(self):
        print(self.myProperty)
obj0 = MyClass1()
obj0.myFunc()
MyClass1.myFunc = classmethod(MyClass1.myFunc)
MyClass1.myFunc() # myFunc is used as a class method (vs. instance method)
# *** compile() ***
myCode = '_a = 10 \n_b = 20 \nmySum = _a + _b \nprint("mySum =", mySum)'
myCodeObject = compile(myCode'myCodeString''exec')
exec(myCodeObject#  Output: 30
# *** complex() ***
print(complex(12))  # Output: (1+2j)
# *** delattr() ***
class MyClass2:
    myProperty1 = 1234
    myProperty2 = 'ABC'
myObj2 = MyClass2()
print(myObj2.myProperty2)
delattr(MyClass2'myProperty2')
#print(myObj2.myProperty2)  # Error: AttributeError: 'MyClass2' object has no attribute 'myProperty2' 
# *** dict() ***
myDic1 = dict(key1 = "val1"key2 = "val2"key3 = "val3")
print(myDic1)  # Output: {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
# *** dir() ***
class MyClass3:
    myProperty1 = 1234
    def myMethod1():
        pass
print(dir(MyClass3))  # Output:
"""
'__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', 
'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'myMethod1', 'myProperty1']
"""
# *** divmod() ***
print(divmod(73))  # Output: (2, 1)
# Note: The output is a tuple:
# divmod(dividend, divisor) => (quotient, reminder)


Wednesday, June 16, 2021

A Cheatsheet for Python Built-in Functions (Part 1: A-B)

A Cheatsheet for Python Built-in Functions (Part 1: A-B)

x1 = -1.5
x2 = 1.5
x3 = 255
b1 = x1 == x2
b2 = x1 == -x2
# *** abs() ***
print(abs(x1))  # Output: 1.5
# *** all() ***
print(all([not b1, b2]))  # Output: True
# *** any() ***
print(any([b1, b2]))  # Output: True
# *** ascii() ***
print(ascii("This is R in Farsi: ر"))  # Output: 'This is R in Farsi: \u0631'
print(ascii(set([b1, b2])))  # Output: {False, True}
# *** bin() ***
print(bin(x3))  # Output: 0b11111111
# *** bool() ***
print(bool(x3), bool(x2), bool(x1))  # Output: True True True
print(bool(0), bool(None), bool([]), bool(()), bool({})) # Output: False False False False False
# *** bytearray() ***
ba1 = bytearray([b1, b2])
print(ba1) # Output: bytearray(b'\x00\x01')
ba2 = bytearray("TEST"encoding='utf8')
print(ba2) # Output: bytearray(b'TEST')
ba3 = bytearray(8)
print(ba3) # Output: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
# *** bytes() ***
ba1 = bytes([b1, b2])
print(ba1) # Output: b'\x00\x01'
ba2 = bytes("TEST"encoding='utf8')
print(ba2) # Output: b'TEST'
ba3 = bytes(8)
print(ba3) # Output: '\x00\x00\x00\x00\x00\x00\x00\x00'




Declare Arrays in Python

Declare Arrays in Python

A Python List can be considered as a Dynamic Array. The following examples present how to declare an Array in Python.


arr1 = [0] * 8
print(arr1)
# Output: [0, 0, 0, 0, 0, 0, 0, 0]

arr2 = [""] * 8
print(arr2)
# Output: ['', '', '', '', '', '', '', '']

arr3 = [None] * 8
print(arr3)
# Output: [None, None, None, None, None, None, None, None]

arr4 = [None for i in range(08)]
print(arr4)
# Output: [None, None, None, None, None, None, None, None]



A Cheatsheet for Python Lists

A Cheatsheet for Python Lists 


# *** Creating a list ***
list1 = []
list2 = [1"item1"2.2]
list3 = [list1, list2, "a text"1234]
print(list3[1][1])
# Output:  item1
print(list3[-1]) # negative index are counted from the end.
# Output:  1234
# *** Length of a list ***
len3 = len(list3)
print(len3)
# Output:  4
# *** Appending new list items ***
for i in range(1014):
    list3.append(i)
list3.append([t for t in range(0103)])
print(list3)
# Output:  [[], [1, 'item1', 2.2], 'a text', 1234, 10, 11, 12, 13, [0, 3, 6, 9]]
print(list3[-1]) # negative index are counted from the end.
# Output:  [0, 3, 6, 9]
#
# Inserting new items into a list.
print(list2)
# Output:  [1, 'item1', 2.2]
list2.insert(2222)
print(list2)
# Output:  [1, 'item1', 222, 2.2]
#
# Extending a list.
list2.extend([t for t in range(0103)])
print(list2)
# Output:  [1, 'item1', 222, 2.2, 0, 3, 6, 9]
#
# Removing an items from a list.
list2.remove("item1")
print(list2)
# Output:  [1, 222, 2.2, 0, 3, 6, 9]
#
# Using pop method to get and remove an item.
val1 = list2.pop()
print(val1)
# Output:  9
val2 = list2.pop(2# index.
print(val2)
# Output:  2.2
#
# Slicing a list.
list4 = ["A""B""C""D""E""F""G"]
print(list4[:2])
# Output:  ['A', 'B']
print(list4[:-2])
# Output:  ['A', 'B', 'C', 'D', 'E']
print(list4[2:])
# Output:  ['C', 'D', 'E', 'F', 'G']
print(list4[2:4])
# Output:  ['C', 'D']
print(list4[::-1])
# Output:  [['G', 'F', 'E', 'D', 'C', 'B', 'A']

Sunday, March 19, 2017

A Fast Approach to List Prime Numbers in Python

A Fast Approach to List Prime Numbers in Python

In this post, an efficient function is developed to generate all the prime numbers that are smaller than an arbitrary number x.


def GeneratePrimes(x):
    nums = set(range(x, 1, -1)) # set of all numbers to be checked.
    p = [] # list of prime numbers to be returned.
    while nums:
        n = nums.pop()
        p.append(n)
        nums.difference_update(set(range(n*2, x+1, n)))
    return p


print(GeneratePrimes(2000))

Result:

   [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999]



Copyright ©2017, Software Developer, All rights reserved.
See Contents

Function "join()" in Python

Function join() in Python 

In this post, with a simple example, the power of the "join" function is presented.

l = ['This', 'is', 'a', 'sentence']
str = ' '.join(l)
print(str + '.')

Result:
   This is a sentence.

In the above  example, the "join" function is used to join a list of words by space.

Note: Actually, "join" is a method of the String class that returns a string in which the string elements of sequence are joined by the instance as separator. In the above example, the String instance is a space character: '  '. So the above example, could be written as:


l = ['This', 'is', 'a', 'sentence']
space = ' '
str = space.join(l)
print(str + '.')



Copyright ©2017, Software Developer, All rights reserved.
See Contents

A Quick Sort Code in Python

A Quick Sort Code in Python

In this post an efficient and short Quick Sort function is presented.

def QuickSort(arr):
    if len(arr) <= 1:
        return arr
    else:
        return QuickSort([x for x in arr[1:] if x < arr[0]]) + [arr[0]] + \
            QuickSort([x for x in arr[1:] if x >= arr[0]])


example = [15,4,2,6,17,4,11,19]

print(QuickSort(example))


Copyright ©2017, Software Developer, All rights reserved.
See Contents

Removing Consecutive Duplicates in Lists

Removing Consecutive Duplicates in Lists

In the following a simple and short function is presented that removes any consecutive duplicates in an arbitrary list.


def RemoveConsecutiveDuplicates(theList):
   return [item for index, item in enumerate(theList) \
      if index==0 or  item != theList[index-1]]


example = ['1','1','2','3','3','a','a','b','b','c','c','c','c','d']

print(RemoveConsecutiveDuplicates(example))

Result:

['1', '2', '3', 'a', 'b', 'c', 'd']

Copyright ©2017, Software Developer, All rights reserved.
See Contents

Generic Decorator to Convert Empty Arguments to None

Generic Decorator to Convert Empty Arguments to None

In the following, a generic decorator is developed to convert all the empty arguments of any arbitrary function to None.

def EmptyToNone(func):
    def innerFunc(*args, **kwargs):
        args = (None if item == "" else item for item in args)
        kwargs = {k:(None if v == "" else v) for k, v in kwargs.items()}
        return func(*args, **kwargs)
    return innerFunc

@EmptyToNone
def testingFunc(a, b, c, *d, **e):
    print(a, b, c, d, e)

testingFunc("", 1, "", 2, "", k="aaa")

Result: 

None 1 None (2, None) {'k': 'aaa'}

 


Copyright ©2017, Software Developer, All rights reserved.
See Contents

Friday, March 17, 2017

Autovivification in Python ∞

Autovivification in Python

In the Perl programming language, autovivification is the automatic creation of new arrays and hashes as required every time an undefined value is dereferenced. Perl autovivification allows a programmer to refer to a structured variable, and arbitrary sub-elements of that structured variable, without expressly declaring the existence of the variable and its complete structure beforehand (for more info click here). 

In this post, we implement Autovivification in Python as in the following.


import collections

class PythonAV(dict):
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value


example = PythonAV()
example[1][2][3] = 8
example[1][3][3] = 9
example[1][2]['string_val'] = 10

print(example)





Copyright ©2017, GRREF, All rights reserved.
See Contents

Thursday, March 9, 2017

Generic Cartesian Product Function

Generic Cartesian Product Function

In the following you can find a Generic Cartesian Product Function in Python.

Rem: The Cartesian product of two sets A and B (also called the product set, set direct product, or cross product) is defined to be the set of all points (a,b) where a in A and b in B. It is denoted A×B, and is called the Cartesian product since it originated in Descartes' formulation of analytic geometry. In the Cartesian view, points in the plane are specified by their vertical and horizontal coordinates, with points on a line being specified by just one coordinate. The main examples of direct products are Euclidean three-space (R×R×R, where R are the real numbers), and the plane (R×R). The graph product is sometimes called the Cartesian product (Vizing 1963, Clark and Suen 2000) [Ref: http://mathworld.wolfram.com/CartesianProduct.html].

def genericCartesianProduct(s, t):
    if t == 0:
        return set()
    result = [(e,) for e in s]
    for i in range(t - 1):
        result = [e + (f,) for e in result for f in s]
    return set(result)


example = {1, 2, 3, 4}
for i in range(4):
    print(genericCartesianProduct(example, i))


Result:
{(2,), (3,), (1,), (4,)}
{(1, 2), (3, 2), (1, 3), (4, 1), (3, 3), (3, 1), (4, 4), (2, 1), (1, 4), (2, 4), (2, 3), (4, 3), (2, 2), (4, 2), (3, 4), (1, 1)}
{(4, 3, 4), (4, 2, 2), (4, 4, 1), (1, 3, 2), (1, 4, 4), (2, 2, 4), (1, 3, 1), (4, 3, 2), (3, 3, 1), (3, 4, 1), (1, 4, 2), (4, 3, 3), (2, 4, 1), (3, 4, 2), (1, 4, 3), (2, 3, 1), (3, 3, 3), (3, 4, 3), (2, 3, 2), (4, 3, 1), (3, 3, 2), (2, 4, 3), (1, 4, 1), (2, 3, 3), (2, 4, 2), (3, 1, 4), (3, 2, 2), (4, 1, 4), (3, 3, 4), (3, 1, 3), (3, 2, 3), (2, 4, 4), (3, 1, 2), (1, 2, 1), (4, 4, 2), (3, 1, 1), (3, 2, 1), (2, 1, 4), (1, 2, 2), (1, 2, 3), (4, 1, 1), (1, 2, 4), (2, 1, 2), (4, 2, 4), (1, 1, 1), (2, 2, 3), (3, 2, 4), (2, 1, 3), (4, 1, 2), (2, 2, 2), (4, 1, 3), (1, 1, 3), (2, 2, 1), (2, 1, 1), (4, 2, 1), (1, 1, 2), (4, 4, 4), (3, 4, 4), (4, 4, 3), (1, 3, 4), (2, 3, 4), (4, 2, 3), (1, 1, 4), (1, 3, 3)}

Copyright ©2017, Software Developer, All rights reserved.
See Contents