Python note

[Check object attributes]


For example, if forget what attributes I can use for "random". use command dir()

dir(random)

>>> dir(random)
[..., 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle',...]
>>>

[Random]

random.randint(a, b)

Return a random integer N such that a <= N <= b.

e.g. random.randint(0,3)

return 0 or 1 or 2 or 3


random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

e.g. random.randrange(0,3)

return 0 or 1 or 2 

[Copy] 


There are essentially three kinds of 'function calls':
  • Pass by value
  • Pass by reference
  • Pass by object reference
Python is a PASS-BY-OBJECT-REFERENCE programming language.

shallow copy vs deep copy
  • default copy is "shallow copy"
  • b = a[:] means "shallow copy"
  • b = a[::] means "deep copy"
e.g.

>>> a = [1, 2]
>>> b = a
>>> b.append(3)
>>> a
[1, 2, 3]
>>> b = a[::]
>>> b.append(4)
>>> a
[1, 2, 3]
>>>

 [Bit operators]

~ Binary Ones Complement. This is the same as -x - 1.

e.g.

>>> a = (3)
>>> bin(a)
'0b11'
>>> ~a
-4
>>> bin(~a)
'-0b100'
>>>


check LSB(least significant bit) is 1 or 0

e.g.

>>> a & 1
1
>>>


count how many 1 in the number n in binary order.  n & (n - 1) will erase it's lowest set bit.

e.g.

4 (100)

4 & (4 - 1)  = > 100 & 011 => 0

so one operation change 4 to 0 means the number 4 only have one 1 in binary order.


Reverse Bits

e.g.

    def reverseBits(self, n):
        n_in_list = [0] * 32
        count = 0
        result = 0
        exp = 0

        while n:
            n_in_list[count] = n & 1
            n >>= 1
            count += 1

        n_in_list = n_in_list[::-1]
        for i in n_in_list:
            result += i * (2 ** exp)
            exp += 1

        return result



 [Array]

 yield

https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa


To understand what yield does, you must understand what generators are. And before generators come iterables.

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:

yield is a keyword that is used like return, except the function will return a generator. 

it can use to provide better performance for the program since we don't run the iterator all-in-one time.

 

留言