Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CS 112, Lab 8 – Exercise – Functions Due: Monday, March 27 th , 11:59pm Files: Y

ID: 3834171 • Letter: C

Question

CS    112,        Lab 8      –      Exercise –      Functions

             

Due:    Monday,          March 27th,     11:59pm        

                             

              

Files:      

              

You       should download       tester8L.py    from     Piazza for         testing.

Grading            is           based on         the        fraction            of           passing tests.   You       can        run        it            like       this:      python3 tester8L.py gmason76_230_L8.py              

If            you       only      want    to           test       some   functions,         you       can run        it            like       this:      (only    testing extract_negatives) python3 tester8L.py gmason76_230_L8.py      extract_negatives

              

As          this       is           an          Exercise,          you       can        read     any       and       all               materials,         ask        us          questions,        talk       with     other   students,               and       learn    however           you       best      learn    in           order   to           solve               the        task.     Just       create your     own      solution            from     those               experiences,   and       turn      in           your     work.  

              

              

We        can        define functions          to           name   a             block   of           code,    and               then     feed      it            inputs and       get        an          output.               Functions               also      allow   us          to           give      default values for         parameters,               which is           useful but        needs special attention.         We        will       write               functions          that      are        more    than     just       side-effect-free               input-output factories.         

              

              

Notes     

You       cannot import any       modules.          

Don't    call        input()            or          print()            anywhere.       

We        need     you       to           figure out        the        "signature"      (top      line) of           some   functions,         so          we         don't    explicitly          show   you the        parameters     lists      for         those   functions.         Part      of           the goal      is           learning            how      to           choose when   to           use default parameters,    and       what    default values to           use.      

You're also      learning            when   to           modify               the        original or          not;       test       cases   should target this       fact.     

              

              

Turning It     In   

              

Add      a             comment          at           the        top        of           the        file        that               indicates          your     name, userID,               G#,        lab         section,             a               description     of           your     collaboration partners,           as          well      as               any       other   details you       feel       like       sharing.             Please also               mention            what    was      most    helpful for         you.      Once    you       are               done,   run        the        testing script   once     more    to           make   sure      you               didn't break   things while   adding these   comments.      If            all          is               well,     go          ahead and       turn      in           just       your    one       .py        file               you've been     working            on,         named with     our        usual    convention               (see      above),              over     on          BlackBoard     to           the        correct               lab         assignment.    Please don't    turn      in           the        tester file        or               any       other   extra    files,     as          it            will       just       slow     us               down.

              

              

Grading    Rubric      

Pass                                        shared    test                                             cases                                                                                                                       4x25 (zero                                            points    for                                         hard-coding)      

-----------------------------------     TOTAL:                                                                                                             100                    

        

Tasks     

Implement      each     of           the        following          functions.                       

              

              

def   simple_pig_latin(input, sep=" ",    end="."):   Accept a string input, which might include              multiple            words separated by          a             separator         sep        and       perform            the        following steps:

Find     the        list        of           “words”            (Note: “words”            are               just       “zero    or          more    characters       separated         by               a             symbol”.           So,         depending       on          the               separator         '     '             or          'a..b'               could   be               a             “word”.).          

Inspect              every   “word”               and       apply   the        following               conversions:  

if            the        word    starts   with     a             non-letter        or          contains            no          characters,      do          nothing        to           it                          

if            the        word    starts   with     a             vowel, add        'way'   to           the        end      

if            the        word    starts   with     a             consonant,        place    the        first      letter   at           the        end       and       add        'ay'     o Reassemble the        words back     into      one        string and       return it,           making              sure      a        single sep        is           padded              between           any       two        neighboring    words and       the        final      string ends     with        end.                     

Assume:            the        input    does     not        have     any       capital               letters o Go     ahead and       use        string methods           like               .join(),            .split()          Examples:       

simple_pig_latin("i     like this")                        'iway ikelay      histay.'   

#     default      sep(space)   and    end(dot)    

simple_pig_latin("i     like this",      sep='.')               'i    like thisway.'  

#      separator    is     dot,   so     whole thing is     a       single “word”

simple_pig_latin("i-like-this","-")            'iway-ikelay-histay.'  

#     sep    is     '-'    and    default      end(dot)    

simple_pig_latin("i.like.this",sep='.',end='!')       'iway.ikelay.histay!'  

#     sep    is     '.'    and    end    is     '!'        


simple_pig_latin(".")                                '..'     

#      only   word   is     '.',   so     do     nothing      to     it     and       add    a      '.'    to     the    end   

     

     

def   replace(xs,old,new,limit=None): Given a list xs, replace occurrences of old value with new value. An optional fourth argument limit is an integer states the maximum number of replacements allowed. You should only      replace              up          to           the        first      limit occurrences    of           old        and       leave    the        rest       unchanged. When   limit==None, there's truly     no          limit     (and     we         replace all          occurrences    of           old).    

Negative           or          zero      limit: no          replacement.

Assume: xs is a list; xs could be empty.

Return              None,    because             the        replacement   happened               in-place.

Examples:       

>>>   xs    =     [1,2,1,3,1,4,1,5,1]    

                                                    >>>    replace(xs,1,-1)                #returns                       None           

>>>   xs   

                                                                 [-1,                      2,      -1,   3,                           -1,                       4,      -1,   5,                           -1]                    #replace   all   

      o >>>      xs   = [1,2,1,3,1,4,1,5,1]  

>>>   replace(xs,1,-1,2)     

>>>   xs   

                                                              [-1,                                   2, -1,                          3,                                    1, 4,                          1,                                    5, 1]                                                             #replace                            only                                       the                           first                                        2                        occurrences                                     

      o >>>      xs   = [1,2,1,3,1,4,1,5,1]  

>>>   replace(xs,1,-1,-100)  

>>>   xs   

                                                            [1,              2,          1,     3,    1,                         4,              1,          5,     1]                          #replace            none         

     

extract_negatives:    The       first      argument,        xs,         contains integers.           We        will       be          removing         any       negative integers            we         find       in           xs,         and       appending       them    to the        second               argument,        new_home.         A            reference          to the        list        that      received            negatives         must    be          returned. When   no          second               argument         is           given, a             list        of all          the        extracted          negatives         should be          created              and returned.                        

              

Figuring            out        the        signature          of           this       function               is           part      of           the        task.                    Careful:              What               default value    do          you       want    to           use        for               new_home?        What    happens            when   we         call        the               function            multiple            times   in           the        same               coding session?            (try       it            out)     

Go         ahead and       use        methods           like       .insert(),      .pop(),      .append()      

You       might need     to           iterate and       update the        list        at               the        same    time.                   Hint:    if            you       need     to               traverse            a             list        from     front    to           back,    but               you       don't    always want    to           go          to           the        next               index   location,            while   loops   can        be          very               useful –             we         get        to           control               when               (which iteration)         to           step      forward.           

              

Examples:

>>>   xs    =     [1,-22,3,-44,-5,6,7]   

>>>   extract_negatives(xs)  

[-22, -44, -5]               #return a      list   of     negatives    >>>   xs

                                         [1,          3,    6,                7]                           #remove     negatives from                xs     

      o >>>      xs   =     [1,-22,3,-44,-5,6,7]  

>>>   negatives   =     [-3, -1]  

>>>   extract_negatives(xs,   negatives)

                                                  [-3,          -1, -22,-44,-5]                

>>>   negatives  

                                                  [-3,          -1,                -22,-44,-5]                                #new                  negatives              appended   to     the    list

>>>   xs   

                                         [1,          3,    6,    7]                                        

Explanation / Answer

Hi there I have written a few tests at the end. You can observe the behaviour and write down what's happening. Something real interesting is happening at extract negatives when we pass reference instead of value. Have a look at that and search the internet a bit. Well most of code is pretty obvious, but still may not be too obvious for beginners, If you have an understanding issue please comment I'd love to reply. Have a great day.

Cheers,

Rj

import re

def simple_pig_latin(inpt, sep=" ", end="."):
   words = inpt.split(sep)
   out = ""
   for word in words:

       # First word 'Alpha'
       alpha_0 = re.compile(r"^[a-zA-z].*")
       # First   word 'Vowel'
       vowel_0 = re.compile(r"^[aeiouAEIOU].*")
       # First   word 'Consonant'
       vowel_0 = re.compile(r"^[aeiouAEIOU].*")

       if (re.match(alpha_0, word[0]) == None):
           pass
       elif (re.match(vowel_0, word[0]) != None):
           word += "way"
       elif (re.match(vowel_0, word[0]) == None):
           word = word[1:] + word[0] + "ay"

       out += word + sep
   out = out[:-1] + end
   return out


def replace(xs, old, new, limit=None):
   if (len(xs) == 0):      
       return None;      
   elif (limit == None):
       for i in range(len(xs)):
           if (xs[i] == old):
               xs[i] = new  
       return xs
   elif (limit < 1):      
       return xs
   elif (limit >= 1):
       for i in range(limit):
           if (xs[i] == old):
               xs[i] == new      
       return xs
   else:
       return xs


def extract_negatives(xs, new_home = []):
   i = 0
   while (i < len(xs)):
       if (xs[i] < 0):
           new_home.append(xs.pop(i))
       else:
           i += 1
   return new_home[:]


# TESTS
# ====

print(simple_pig_latin("i like this"))
print(simple_pig_latin("."))
print(simple_pig_latin("i.like.this",sep='.',end='!'))
print(simple_pig_latin("i-like-this","-"))

print(replace(['anim@l', 'Animal', 'ANIMAL', 'aNIMAL'], 'Animal', '@nimal'))

print(extract_negatives([1,-22,3,-44,-5,6,7]))
print(extract_negatives([1,-22,3,-44,-5,6,7]))