挑战Python100题(6)

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:

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.

假设我们在"username@companyname.com"格式,请编写程序打印给定电子邮件地址的用户名。用户名和公司名称都只能由字母组成。

Solution:

python 复制代码
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:

google

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:

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.

编写一个程序,接受由空格分隔的单词序列作为输入,只打印由数字组成的单词。

示例:如果将以下单词作为程序的输入:

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


相关阅读

挑战Python100题(1)-CSDN博客

挑战Python100题(2)-CSDN博客

挑战Python100题(3)-CSDN博客

挑战Python100题(4)-CSDN博客

挑战Python100题(5)-CSDN博客

相关推荐
ROBOT玲玉39 分钟前
Milvus 中,FieldSchema 的 dim 参数和索引参数中的 “nlist“ 的区别
python·机器学习·numpy
Kai HVZ2 小时前
python爬虫----爬取视频实战
爬虫·python·音视频
古希腊掌管学习的神2 小时前
[LeetCode-Python版]相向双指针——611. 有效三角形的个数
开发语言·python·leetcode
m0_748244832 小时前
StarRocks 排查单副本表
大数据·数据库·python
B站计算机毕业设计超人2 小时前
计算机毕业设计PySpark+Hadoop中国城市交通分析与预测 Python交通预测 Python交通可视化 客流量预测 交通大数据 机器学习 深度学习
大数据·人工智能·爬虫·python·机器学习·课程设计·数据可视化
路人甲ing..2 小时前
jupyter切换内核方法配置问题总结
chrome·python·jupyter
游客5202 小时前
opencv中的常用的100个API
图像处理·人工智能·python·opencv·计算机视觉
每天都要学信号2 小时前
Python(第一天)
开发语言·python
凡人的AI工具箱2 小时前
每天40分玩转Django:Django国际化
数据库·人工智能·后端·python·django·sqlite
咸鱼桨3 小时前
《庐山派从入门到...》PWM板载蜂鸣器
人工智能·windows·python·k230·庐山派