Introduction to computer science and Programming

Source: Internet
Author: User

Introduction to computer science and Programming

Skills:
* Computational thinking
* Understand code
* Understand abilities & limits
* Map problems into computation

Turing compatibility:
What can be done in one language can also be done in another language.

The type of the variable changes according to the type of the value currently bound to it,Do not change the type of a variable in any way.

Y = 3*5 # y points to 15y = x # y points to the value of x (15) instead of xif x = y # compares the value of x with the value of y, instead of x and y

Linear Complexity:
The number of execution cycles is directly related to the size of input parameters.

Defensive Programming:
Cover all possible paths in the Code. Make sure that all possible inputs correspond to a path in the code to avoid errors and infinite loops.

A string is an ordered string of characters.

Create a function:
Decomposition (Code structuring) and abstraction (avoiding details)

Function purpose:
Finding a common Computing Model

Chicken and rabbit cage problems:

def solve(numHeads,numLegs):    for numRabbits in range(0,numHeads+1):        numChicks = numHeads - numRabbits        totLegs = 2 * numChicks + 4 * numRabbits        if totLegs == numLegs:            return(numRabbits,numChicks)    return(None,None)def farm():    heads = int(raw_input('enter number of heads:'))    legs = int(raw_input('enter number of legs:'))    Rabbits,Chicks = solve(heads,legs)    if Rabbits == None:        print 'there is no solution.'    else:        print 'number of Rabbits is',Rabbits        print 'number of Chicks is',Chicks

 

Recursion (recursion ):
Break down a problem into a simple similar problem or a series of basic steps that can be solved.

Two examples of recursive thinking:
1. determine whether an English string is a text return (that is, whether it is exactly the same from left to right and from right to left ):

def isPalindrome(s):    """Return True if s is a palindrome and False otherwise"""    if len(s) <=1: return True    else: return s[0] == s[-1] and isPalindrome(s[1:-1])

 

2,Fibonacci Series(From the third item, each item is the sum of the first two items. ...) :

def fib(x):    """Return Fibonacci of x, where x is a non-negative int"""    if x == 0 or x == 1: return 1    else: return fib(x-1) + fib(x-2)

 64-bit storage:

1-bit storage symbol (positive or negative)
11-bit storage Index
52-bit storage tail
(Floating point) value = ending number x base number ^ index (plus and minus signs) can represent the 10 Progress precision of 17 count Length

Pay attention to the comparison of Floating Point Numbers
The test results should not be equal or not equal, but should be close enough to the test results.
Abs (a-B) <epsilon (abs: absolute value function epsilon: Minimum value greater than zero)

Brute-force algorithm brute force
Successive approximation Method
Bisection method dichotomy
Newton's method

Once the computing in python reaches the order of L (2 billion), it will stay at L. For example:

>>> a = 2**1000>>> a10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376L>>> b = 2**999>>> b5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688L>>> a/b2L

Returns the square root of the binary method:

Def squarerootraumatic brain (x, epsilon): "" Return y s. t. y * y is within epsilon of x "assert epsilon> 0, 'epsilon must be postive, not '+ str (epsilon) low = 0 high = max (x, 1) # when x is greater than 1, the square of x is greater than x, so the value is in (0, x. When x is less than 1, the square of x is less than x, and the value must be in (0, 1. Guess = (low + high)/2.0 ctr = 1 while abs (guess ** 2-x)> epsilon and ctr <= 100: # print 'low: ', low, 'High: ', high, 'Guess:', guess if guess ** 2 <x: low = guess else: high = guess = (low + high) /2.0 ctr + = 1 assert ctr <= 100, 'iteration count exceeded 'print 'Bi method. num. iterations: ', ctr, 'estimate:', guess return guess

Calculate the square root using Newton's method

def squareRootNR(x, epsilon): """Return y s.t. y*y is within epsilon of x""" assert epsilon > 0, 'epsilon must be postive, not' + str(epsilon) x = float(x) guess = x/2.0  diff = guess**2 - x ctr = 1 while abs(diff) > epsilon and ctr <= 100: #print 'Error:', diff, 'guess:', guess guess = guess - diff/(2.0*guess) diff = guess**2 - x ctr += 1 assert ctr <= 100, 'Iteration count exceeded' print 'NR method.  Num. iterations:', ctr, 'Estimate:', guess return guess 

Assert)
It is used to detect a condition. If the condition is true, nothing is done. Otherwise, an AssertionError with an optional error message is triggered and the program stops running.

What is the difference between L1 + L2 and L1.append (L2 )?
L1 + L2 adds all elements in L2 to L1, while L1.append (L2) adds L2 to L1 as a whole.

What is the difference between list binding and value binding?

>>> L1 = [, 3] >>> L2 = L1 >>> L1 [0] = 4 >>> L1, 3] >>> L2 [, 3] >>> a = 1 >>> B = a # After binding B and 1, the binding between a and 1 is interrupted >>> a = 2 >>> b1

Differences between input and raw_input
Input receives numeric values (return numeric values), expressions (return calculated numeric values), and strings (return strings ). Raw_input receives arbitrary user input and returns it as a string.

Separating implementation from use

Big O notation):
Mathematical symbols used to describe the progressive behavior of a function. Generally, a more simple function is used to describe the progressive upper bound of a function of an order of magnitude.
For example, f (x) ε O (n ^ 2), where x is the input of a specific problem, and n is an estimation of the size of x.

Common algorithm complexity:
O (n) constant level
O (logn) logarithm level
O (Len (s) linear level
O (n ^ 2) Square level
O (2 ^ n) exponential

Two storage methods of Arrays:
1. linked list: the value of a point in memory pointing to the next element
2. Sequential List: a point in memory points to the starting point of the array.

Selection Sort)AndBubble Sort)

You can query whether an element is in an array in the following two ways:
1. Directly search for O (n)
2. sort and search for O (n * logn + logn)

When only one query is performed, direct search is faster. To perform multiple searches, the time required for direct search is k * n, and the time required for sorting is n * logn + k * logn. After sorting, the search speed is faster.

Divide and conquer algorithm)
1. Split the problem into several sub-problems of the same type.
2. solve independently.
3. combine solutions.

It is applicable to the following problems solved by the divide and conquer algorithm:It is best to simply break down the problem, and the merge process is not very complicated (smaller than the linear solution ).

An Application of the grouping algorithm:
Merge sort)(Invented by von noriman in 1945)
1. divide list in half.
2. continue until we have singleton lists.
3. merge of the sub-lists.

def merge(left,right):    """Assumes left and right are sorted lists,return a new sorted list containing the same elementsas (left + right) would contain."""    result = []    i,j = 0,0    while i < len(left) and j < len(right):        if left[i] <= right[j]:            result.append(left[i])            i = i + 1        else:            result.append(right[j])            j = j + 1    while (i < len(left)):        result.append(left[i])        i = i + 1    while (j < len(right)):        result.append(right[j])        j = j + 1    return resultdef mergesort(L):    """Return a new sort list containing the same elements as L"""    print L    if len(L) < 2:        return L[:]    else:        middle = len(L)/2        left = mergesort(L[:middle])        right = mergesort(L[middle:])        together = merge(left,right)        print 'merged', together        return together

 

Hash Algorithm
1. Map the input to a group of numbers.
2. Change the time with space.
3. the hash algorithm is used in Python to implement dictionary technology.
4. It is difficult to create good hash functions.

Two examples of exception handling:
1. Get a specific type of input

def readVal(valType, requestMsg, errorMsg):    while True:        val = raw_input(requestMsg)        try:            val = valType(val)            return val        except:            print(errorMsg)print readVal(int, 'Enter int: ', 'Not an int.')

 

2. Open a file and calculate the median

def getGrades(fname):    try:        gradesFile = open(fname, 'r')    except IOError:        print 'Could not open', fnmae        raise 'GetGradesError'    grades = []    for line in gradesFile: grades.append(float(line))    return gradestry:    grades = getGrades('q1grades.txt')    grades.sort()    median = grades[len(grades)/2]    print 'Median grade is', medianexcept 'GetGradesError':    print 'Whoops'

 

Difference between assertion and exception
1. assertions are some test conditions. If the input meets these conditions, the remaining code will run. If not, an error is thrown and the operation is stopped immediately.
2. Exception and exception handling are some of our expected exceptions, and I can try to handle them. When an exception occurs, the code runs normally and you will be notified when an error occurs in the program.

Test and debug test: Compare the input and output with the program specification.
  • Testing and Reasoning (speculative)
  • Validation is a process
  • Designed to uncover problems and increase confidence that our program does what we think it's intent to do.
  • Unit testing & Integration testing)
  • Test suite (Test Set): small enough & big enough to give us some confidence
Debugging: find out why the program is not running or does not run as expected
  • Function debugging and Performance debugging)
  • The purpose of debugging is not to eliminate a bug, but to get a program without a bug.
  • Two of the best debugging tools
    • Print statement
    • Reading
  • Perform systematic debugging
    • Reduce search space
    • Localize the source of the problem
    • Study the text (how cocould it have produced this result & is it part of a family & how to fix it)
  • The experiment must have the possibility to refute our assumptions.
  • How to design an experiment
    • Find simplest input that will the bug
    • Find the part of the program that is most likely at fault (Binary search)
  • Possible Errors
    • Reversed order of arguments
    • Spelling
    • Initialization
    • Object vs Value equality
    • Aliasing (duplicate name)
    • Side-function
  • Some Suggestions
    • Keep record of what you tried
    • Reconsidering assumptions
    • Debug the code, not the comment
    • Get help-Explain
    • Walk away
    • Code shoshould not always grow
    • Make sure that you can revert: save old version
Optimization problems (Optimal Selection Problem)
  • Features
    • A function to maximize/minimize
    • A set of comstraints (constraints)
  • Application:
    • Shortest path
    • Traveling sales person (TSP)
    • Bin packing
    • Sequence alignment (adjusted)
    • Knapsack (Backpack)
  • Problem ction
    When you have a problem that you have never encountered before, the first thing you need to do is to ask yourself if this problem has been solved by someone else.
  • 0/1 backpack Problems
    • Greedy algorithm: each step maximizes your value and makes no plans for the future.
    • Local optimal decisions: Local optimization policies do not guarantee global optimization.
  • Dynamic programing (Dynamic Programming)
    • Overlapping sub-problems (Overlapping sub-problems)
    • Optimal sub-structure: Global optimal solution can be constructed from optimal solutions to sub-problem.
  • Memoization)
    We record a value the first time it's computerd, then look it up the subsequent times we need it.
  • Demo-tree (Decision tree)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.