MIT public class: Introduction to Computer science and programming Python Note 4 function decomposition abstraction and recursion

Source: Internet
Author: User
Tags square root

Lecture4:decomposition and abstraction through functions;introduction to recursion function decomposition abstraction and recursion

Functions function

    • Block up into modules decomposition into modules
    • Suppress detail ignoring details
    • Create "New primitives" how to think about creating primitives
      W3school python functions
 #example code for finding Square roots before  x = 16  ans = 0  if  x >= 0 : while  ans* Ans < X:ans = ans + 1  print   "ans = ' , ans if  Ans*ans! = x: print  x, " is not a perfect square '  else : print  anselse :  Print  x,   
    • def keyword
    • Function_name (formal parameters) function name (formal parameter)
    • return keyword
    • None-special value
#example code for finding square roots def sqrt(x):  "" " Returns the square root of x, if X is a perfect square. Prints an error message and returns None otherwise "" "Ans =0  ifX >=0: whileAns*ans < X:ans = ans +1      ifAns*ans! = x:PrintX' is not a perfect square '          return None      Else:returnAnsElse:PrintX' is a negative number '        return None

Local binding does not affect global binding:
Local bindings (local variables) do not affect global bindings (variables):

def f(x): x=x+1return x>>>x=3>>>z = f(x) >>>print x3 >>>print z4

Farmyard Problem Farm issues:

    • Heads, legs
    • Numpig + Numchicken = 20 number of pigs + number of chickens = 20
    • 4 *numpig + 2*numchicken = 56
 def solve(Numlegs, numheads):     forNumchicksinchRange0, Numheads +1): Numpigs = numheads-numchicks Totlegs =4*numpigs +2*numchicksifTotlegs = = Numlegs:return(Numpigs, Numchicks)return(None,None) def Barnyard():Heads = Int (Raw_input (' Enter number of heads: ')) legs = Int (Raw_input (' Enter number of legs: ')) pigs, chickens = solve (legs, heads)ifPigs = =None:Print ' There is no solution '    Else:Print ' Number of pigs: ', pigsPrint ' Number of chickens: ', chickens

The farmer also kept the spider:

 def solve1(Numlegs, numheads):     forNumspidersinchRange0, Numheads +1): forNumchicksinchRange0, Numheads-numspiders +1): Numpigs = numheads-numchicks-numspiders Totlegs =4*numpigs +2*numchicks +8*numspidersifTotlegs = = Numlegs:return(Numpigs, Numchicks, Numspiders)return(None,None,None) def barnYard1():Heads = Int (Raw_input (' Enter number of heads: ')) legs = Int (Raw_input (' Enter number of legs: ')) pigs, chickens, spiders = solve1 (legs, heads)ifPigs = =None:Print ' There is no solution '    Else:Print ' Number of pigs: ', pigsPrint ' Number of chickens: ', chickensPrint ' Number of spiders: ', spiders

Improved: Output all the solutions:

 def solve2(Numlegs, numheads):Solutionfound =False     forNumspidersinchRange0, Numheads +1): forNumchicksinchRange0, Numheads-numspiders +1): Numpigs = numheads-numchicks-numspiders Totlegs =4*numpigs +2*numchicks +8*numspidersifTotlegs = = Numlegs:Print ' Number of pigs: '+ STR (numpigs) +', ',Print ' Number of chickens: '+str (numchicks) +', ',Print ' Number of spiders: ', Numspiders solutionfound =True    if  notSolutionfound:Print ' There is no solution. '

Recursion recursion

    • Base Case–break problem into simplest possible solution to break the problem down into the simplest solution
    • Inductive step, or the recursive step induction, recursive steps: Break problem to a simpler version of the same problem and some other STE Ps
# string is palindrome eg. "ABCBA"  def   Ispalindrome   (s) :   "" "Returns 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 :-< span class= "Hljs-number" >1 ])  
# 付波纳切fibonacci数列def fib(x):    """Return fibonacci of x, where x is a non-negative int"""    if0or1return1    elsereturn fib(x-1) + fib(x-2)

MIT public class: Introduction to Computer science and programming Python Note 4 function decomposition abstraction and recursion

Related Article

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.