Classes: Dealing with Complex Numbers
Create Date: March 31, 2019 at 10:04 PM         | Tag: PYTHON         | Author Name: Sun, Charles |
For this challenge, you are given two complex numbers, and you have to print the result of their addition, subtraction, multiplication, division and modulus operations.
The real and imaginary precision part should be correct up to two decimal places.
Input Format
One line of input: The real and imaginary part of a number separated by a space.
Output Format
For two complex numbers and , the output should be in the following sequence on separate lines:
For complex numbers with non-zero real and complex part, the output should be in the following format:
Replace the plus symbol with a minus symbol when .
For complex numbers with a zero complex part i.e. real numbers, the output should be:
For complex numbers where the real part is zero and the complex part is non-zero, the output should be:
Sample Input
2 1
5 6
Sample Output
7.00+7.00i
-3.00-5.00i
4.00+17.00i
0.26-0.11i
2.24+0.00i
7.81+0.00i
Concept
Python is a fully object-oriented language like C++, Java, etc. For reading about classes, refer here.
Methods with a double underscore before and after their name are considered as built-in methods. They are used by interpreters and are generally used in the implementation of overloaded operators or other built-in functionality.
__add__-> Can be overloaded for + operation
__sub__ -> Can be overloaded for - operation
__mul__ -> Can be overloaded for * operation
For more information on operator overloading in Python, refer here.
import math
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, no):
realSum = self.real + no.real
imaginarySum = self.imaginary + no.imaginary
return Complex(realSum, imaginarySum)
def __sub__(self, no):
realDiff = self.real - no.real
imaginaryDiff = self.imaginary - no.imaginary
return Complex(realDiff, imaginaryDiff)
def __mul__(self, no):
realProd = self.real * no.real + self.imaginary * no.imaginary * -1
imaginaryProd = self.real * no.imaginary + self.imaginary * no.real
return Complex(realProd, imaginaryProd)
def __truediv__(self, no):
conj = Complex(no.real, no.imaginary * -1)
num = self * conj
denom = no * conj
realQuo = num.real / denom.real
imaginaryQuo = num.imaginary / denom.real
return Complex(realQuo, imaginaryQuo)
def mod(self):
m = math.pow(math.pow(self.real, 2) + math.pow(self.imaginary, 2), 0.5)
return Complex(m, 0)
def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
elif self.real == 0:
if self.imaginary >= 0:
result = "0.00+%.2fi" % (self.imaginary)
else:
result = "0.00-%.2fi" % (abs(self.imaginary))
elif self.imaginary > 0:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
else:
result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))
return result
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
y = Complex(*d)
print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')
New Comment
Reduce Function
Create Date: March 31, 2019 at 09:36 PM         | Tag: PYTHON         | Author Name: Sun, Charles |
Given a list of rational numbers,find their product.
Concept
The reduce()
function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3]
and you have to find its sum.
>>> reduce(lambda x, y : x + y,[1,2,3])
6
You can also define an initial value. If it is specified, the function will assume initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list. For example:
>>> reduce(lambda x, y : x + y, [1,2,3], -3)
3
>>> from fractions import gcd
>>> reduce(gcd, [2,4,8], 3)
1
Input Format
First line contains , the number of rational numbers.
The of next lines contain two integers each, the numerator( ) and denominator( ) of the rational number in the list.
Constraints
Output Format
Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than .
Sample Input 0
3
1 2
3 4
10 6
Sample Output 0
5 8
Explanation 0
Required product is 1/2 * 3/4 * 10 / 6 = 5/8
from fractions import Fraction
from functools import reduce
def product(fracs):
t = reduce(lambda x, y : x * y, fracs) # complete this line with a reduce statement
return t.numerator, t.denominator
if __name__ == '__main__':
fracs = []
for _ in range(int(input())):
fracs.append(Fraction(*map(int, input().split())))
result = product(fracs)
print(*result)
Validating Email Addresses With a Filter
Create Date: March 31, 2019 at 06:27 PM         | Tag: PYTHON         | Author Name: Sun, Charles |
You are given an integer followed by email addresses. Your task is to print a list containing only valid email addresses in lexicographical order.
Valid email addresses must follow these rules:
- It must have the username@websitename.extension format type.
- The username can only contain letters, digits, dashes and underscores.
- The website name can only have letters and digits.
- The maximum length of the extension is .
Concept
A filter takes a function returning True or False and applies it to a sequence, returning a list of only those members of the sequence where the function returned True. A Lambda function can be used with filters.
Let's say you have to make a list of the squares of integers from to (both included).
>> l = list(range(10))
>> l = list(map(lambda x:x*x, l))
Now, you only require those elements that are greater than but less than .
>> l = list(filter(lambda x: x > 10 and x < 80, l))
Easy, isn't it?
Input Format
The first line of input is the integer , the number of email addresses.
lines follow, each containing a string.
Constraints
Each line is a non-empty string.
Output Format
Output a list containing the valid email addresses in lexicographical order. If the list is empty, just output an empty list, [].
Sample Input
3
lara@hackerrank.com
brian-23@hackerrank.com
britts_54@hackerrank.com
Sample Output
['brian-23@hackerrank.com', 'britts_54@hackerrank.com', 'lara@hackerrank.com']
method 1:
import re
def fun(s):
# return True if s is a valid email, else return False
pattern = re.compile("^[a-zA-Z][\w-]*@[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$")
return re.match(pattern, s)
def filter_mail(emails):
return list(filter(fun, emails))
if __name__ == '__main__':
n = int(input())
emails = []
for _ in range(n):
emails.append(input())
filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)
mehtod 2:
def fun(s):
# return True if s is a valid email, else return False
try:
username, url = s.split("@")
website, extension = url.split(".")
except ValueError:
return False
if not username.replace("-", "").replace("_", "").isalnum():
return False
if not website.isalnum():
return False
if len(extension) > 3:
return False
return True
def filter_mail(emails):
return list(filter(fun, emails))
if __name__ == '__main__':
n = int(input())
emails = []
for _ in range(n):
emails.append(input())
filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)
method 3:
def fun(s):
# return True if s is a valid email, else return False
try:
username, url = s.split("@")
website, extension = url.split(".")
except ValueError:
return False
if username.replace("-", "").replace("_", "").isalnum() is False:
return False
elif website.isalnum() is False:
return False
elif len(extension) > 3:
return False
else:
return True
def filter_mail(emails):
return list(filter(fun, emails))
if __name__ == '__main__':
n = int(input())
emails = []
for _ in range(n):
emails.append(input())
filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)
New Comment