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.
定义一个名为American的类及其子类NewYorker。
提示:使用class Subclass(ParentClass)来定义子类。
Solution:
python
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.
定义一个名为"圆"的类,该类可以由半径构造。Circle类有一个可以计算圆面积的方法。
提示:使用def methodName(self)定义方法。
Solution:
python
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.
定义一个名为Rectangle的类,该类可以由长度和宽度构造。Rectangle类有一个可以计算面积的方法。
提示:使用def methodName(self)定义方法。
Solution:
python
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.
定义一个名为Shape的类及其子类Square。Square类有一个init函数,它以一个长度作为参数。这两个类都有一个面积函数,该函数可以打印形状的面积,其中shape的面积默认为0。
提示:要覆盖SuperClass中的方法,可以在SuperClass中定义一个同名的方法。
Solution:
python
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.
请引发RuntimeError异常。
提示:使用raise()引发异常。
Solution:
python
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.
编写一个函数来计算5/0,并使用try/except来捕获异常。
提示:使用try/except捕获异常。
Solution:
python
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.
定义一个以字符串消息为属性的自定义异常类。
提示:要定义自定义异常,我们需要定义从exception继承的类。
Solution:
python
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:
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.
假设我们在"username@companyname.com"格式,请编写程序打印给定电子邮件地址的用户名。用户名和公司名称都只能由字母组成。
Solution:
python
import re
emailAddress = input()
pat2 = "(\w+)@"
r2 = re.match(pat2,emailAddress)
print(r2.group(1))
In:
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:
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.
假设我们在"username@companyname.com"格式,请编写程序打印给定电子邮件地址的公司名称。用户名和公司名称都只能由字母组成。
Solution:
python
import re
emailAddress = input()
pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print(r2.group(2))
In:
Out:
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.
编写一个程序,接受由空格分隔的单词序列作为输入,只打印由数字组成的单词。
示例:如果将以下单词作为程序的输入:
2只猫和3只狗。
然后,程序的输出应该是:
['2','3']
在向问题提供输入数据的情况下,应假设它是控制台输入。
提示:使用re.findall()使用正则表达式查找所有子字符串。
Solution:
python
import re
s = input()
print(re.findall("\d+",s))
In:
2 cats and 3 dogs
Out:
['2', '3']
来源:GitHub - 965714601/Python-programming-exercises: 100+ Python challenging programming exercises