Lecture3_2 Python

download Lecture3_2 Python

of 9

Transcript of Lecture3_2 Python

  • 7/30/2019 Lecture3_2 Python

    1/9

    Classesofalgorithms

    Itera0vealgorithmsallowustodomorecomplexthingsthansimplearithme0c

    Wecanrepeatasequenceofstepsmul0ple0mesbasedonsomedecision;leadstonewclassesofalgorithms

    Oneusefulexampleareguessandcheckmethods

  • 7/30/2019 Lecture3_2 Python

    2/9

    Guessandcheck

    Rememberourdeclara0vedefini0onofsquarerootofx!

    Ifwecouldguesspossiblevaluesforsquareroot(callitg),thencanusedefini0ontocheckifg*g = x!

    Wejustneedagoodwaytogenerateguesses

  • 7/30/2019 Lecture3_2 Python

    3/9

    Findingacuberootofaninteger

    Onewaytousethisideaofgenera0ngguessesinordertofindacuberootofx isto

    firsttry0**3,then1**3,then2**3,andsoon

    Canstopwhenreachk suchthatk**3 > x! Onlyafinitenumberofcasestotry

  • 7/30/2019 Lecture3_2 Python

    4/9

    Somecode

    x = int(raw_input('Enter an integer: '))!ans = 0!

    while ans**3 < x:!ans = ans + 1!

    if ans**3 != x:! print(str(x) + ' is not a perfect cube')!else:! print('Cube root of ' + str(x) + ' is '+ str(ans))!

  • 7/30/2019 Lecture3_2 Python

    5/9

    Extendingscope

    Onlyworksforposi0veintegers Easytofixbykeepingtrackofsign,lookingfor

    solu0ontoposi0vecase

  • 7/30/2019 Lecture3_2 Python

    6/9

    Somecode

    x = int(raw_input('Enter an integer: '))!ans = 0!

    while ans**3 < abs(x):!ans = ans + 1!if ans**3 != abs(x):!

    print(str(x) + ' is not a perfect cube')!else:!

    if x < 0:!ans = - ans!

    print('Cube root of ' + str(x) + ' is '+ str(ans))!

  • 7/30/2019 Lecture3_2 Python

    7/9

    Loopcharacteris0cs

    Needaloopvariable Ini0alizedoutsideloopChangeswithinloopTestfortermina0ondependsonvariable

    Usefultothinkaboutadecremen'ngfunc'onMapssetofprogramvariablesintoanintegerWhenloopisentered,valueisnon-nega0veWhenvalueis

  • 7/30/2019 Lecture3_2 Python

    8/9

    Whathappensifwemissacondi0on?

    Supposewedontini0alizethevariable? Supposewedontchangethevariableinside

    theloop?

  • 7/30/2019 Lecture3_2 Python

    9/9

    Exhaus0veenumera0on

    Guessandcheckmethodscanworkonproblemswithafinitenumberofpossibili0es

    Exhaus0veenumera0onisagoodwaytogenerateguessesinanorganizedmanner