Informatics2-2018/Lab06

A MathWikiből
A lap korábbi változatát látod, amilyen Gaebor (vitalap | szerkesztései) 2018. március 21., 11:09-kor történt szerkesztése után volt.
(eltér) ←Régebbi változat | Aktuális változat (eltér) | Újabb változat→ (eltér)

previous up next

Tartalomjegyzék

Lecture

See the OOP I. lecture

Exercises

Complex

You have to add methods to the Complex class from the lecture:

class Complex(object):
    def __init__(self, real, imaginary):
        self.re = real
        self.im = imaginary
 
    def __add__(self, z2):
        new_re = z1.re + z2.re
        new_im = z1.im + z2.im
        return Complex(new_re, new_im)
 
    # used by print
    def __repr__(self):
        return str(self.re) + " + " + str(self.im) + "i"
 
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = z1 + z2
 
print z3
  • Implement the subtraction, multiplication and division methods (__sub__, __mul__, __div__).
  • Also implement the norm method which returns the length of the complex number.
  • Improve the __repr__ method to handle numbers like this for example:
2 - 4i
5i
2

For testing use this (or you can use other tests):

k1 = Complex(4, 3)
k2 = Complex(-2, 1)
k3 = Complex(4, 1)
 
print k1 + k2
print k1 - k3
print k2 * k1
print k3 / k1
print k1.norm()

In Cloudcoder

  1. reservation_1
  2. reservation_2
  3. reservation_3
  4. reservation_4
  5. reservation_5
  6. whowins

previous up next

Személyes eszközök