100+ Python challenging programming exercises 6

Question 51
Define a class named American and its subclass NewYorker.
Hints: Use class Subclass(ParentClass) to define a subclass.
Solution:
class American:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
    def introduce(self):  
        return f"Hello, my name is {self.name} and I am {self.age} years old."  
  
class NewYorker(American):  
    def introduce(self):  
        return f"Yo, my name is {self.name} and I am from New York. I'm {self.age} years old."
anAmerican = American('Tom',8)
aNewYorker = NewYorker('Jerry',5)
print(anAmerican.introduce())
print(aNewYorker.introduce()) 
Out:
Hello, my name is Tom and I am 8 years old.
 Yo, my name is Jerry and I am from New York. I'm 5 years old.
Question 52
Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
Hints: Use def methodName(self) to define a method.
Solution:
class Circle(object):
    def __init__(self, r):
        self.radius = r
    def area(self):
        return self.radius**2*3.14
aCircle = Circle(10)
print(aCircle.area()) 
Out:
314.0
Question 53
Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.
Hints: Use def methodName(self) to define a method.
Solution:
class Rectangle(object):
    def __init__(self, l, w):
        self.length = l
        self.width = w
    def area(self):
        return self.length*self.width
aRectangle = Rectangle(3,5)
print(aRectangle.area()) 
Out:
15
Question 54
Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
Hints: To override a method in super class, we can define a method with the same name in the super class.
Solution:
class Shape(object):
     def __init__(self):
          pass
     def area(self):
          return 0
class Square(Shape):
     def __init__(self, l):
          Shape.__init__(self)
          self.length = l
     def area(self):
          return self.length*self.length
aSquare = Square(3)
print(aSquare.area()) 
Out:
9
Question 55
Please raise a RuntimeError exception.
Hints: Use raise() to raise an exception.
Solution:
raise RuntimeError('something wrong') 
Question 56
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints: Use try/except to catch exceptions.
Solution:
def throws():
     return 5/0
try:
     throws()
except ZeroDivisionError:
     print("division by zero!")
except Exception(err):
     print('Caught an exception')
finally:
     print('In finally block for cleanup')
 
Out:
division by zero!
 In finally block for cleanup
Question 57
Define a custom exception class which takes a string message as attribute.
Hints: To define a custom exception, we need to define a class inherited from Exception.
Solution:
class CustomException(Exception):  
    def __init__(self, message):  
        self.message = message
try:  
    raise CustomException("This is a custom exception")  
except CustomException as e:  
    print(e.message)  
Out:
"This is a custom exception"
Question 58
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
Example: If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
john
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints: Use \w to match letters.
Solution:
import re
emailAddress = input()
pat2 = "(\w+)@"
r2 = re.match(pat2,emailAddress)
print(r2.group(1)) 
In:
 john@google.com
Out:
 John
Question 59
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.
Example: If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints: Use \w to match letters.
Solution:
import re
emailAddress = input()
pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print(r2.group(2)) 
In:
 john@google.com
Out:
 google
Question 60
Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
Example: If the following words is given as input to the program:
2 cats and 3 dogs.
Then, the output of the program should be:
['2', '3']
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints: Use re.findall() to find all substring using regex.
Solution:
import re
s = input()
print(re.findall("\d+",s))
 
In:
 2 cats and 3 dogs
Out:
 ['2', '3']
相关阅读
挑战Python100题(1)-CSDN博客
挑战Python100题(2)-CSDN博客
挑战Python100题(3)-CSDN博客
挑战Python100题(4)-CSDN博客
挑战Python100题(5)-CSDN博客










