This is a learning note related to the Python learning and exercise, including but not limited to numpy, pytorch. Continuously updating…

  1. The outputs of a same function name are different since importing a library.

    print(sum(range(5),-1))
    ## output: 9
    from numpy import *
    print(sum(range(5),-1))
    ## output: 10
    
    • built-in function sum(iterable, start): iterable is a iterable (list, tuple, dict, etc). Start is a value that will be added to the sum of items of the iterable. The default value of start is 0 (if omitted).

    • numpy.sum(array, axis): array are the elements to sum. axis is an integer indicating which axis or axes along to sum. If axis is negative it counts from the last to the first axis.

  2. bitwise shift operator << and >>

    • <<: x << y returns x with the bits shifted to the left by y places. Same as multiplying x by 2**y.

    • >>: x >> y returns x with the bits shifted to the right by y places. Same as dividing x by 2**y.

  3. generator function

    A generator function doesn’t return a single value but returns an iterator object with a sequence of values. It use yield rather return. The difference between yield and return is that yield returns a value and pauses the execution while maintaining the internal states, whereas the return statement returns a value and terminates the execution of the function.

    def generate():
      for x in range(10):
        yield x
       
    a = np.fromiter(generate(), dtype = int)
    print(a)
    
  4. broadcasting semantics Two tensors are “broadcastable” if the following rules hold:

    • Each tensor has at least one dimension.

    • When iterating over the dimension sizes, starting at the trailing dimension, the dimension sizes must either be equal, one of them is 1, or one of them does not exist.

numpy exercise

pytorch exercise