cs107-lecture-examples

Example codes used during Harvard CS107 lectures
git clone https://git.0xfab.ch/cs107-lecture-examples.git
Log | Files | Refs | README | LICENSE

04.py (610B)


      1 #!/usr/bin/env python3
      2 def Complex(r, i):
      3     """
      4     Construct a complex number
      5     Arguments:
      6         r: real part
      7         i: imaginary part
      8     """
      9     def implementation(method, z=None):
     10         nonlocal r, i
     11         if method.lower() == 'set_z':
     12             assert z is not None
     13             r, i = z
     14         elif method.lower() == 'real':
     15             return r
     16         elif method.lower() == 'imag':
     17             return i
     18         elif method.lower() == 'string':
     19             return f"{r:e} + i{i:e}"
     20 
     21     return implementation
     22 
     23 
     24 z = Complex(1, 2)
     25 z('set_z', (3, 4))
     26 print(z('real'), z('imag'), z('string'))