挑战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博客

相关推荐
nuclear201137 分钟前
使用Python 在Excel中创建和取消数据分组 - 详解
python·excel数据分组·创建excel分组·excel分类汇总·excel嵌套分组·excel大纲级别·取消excel分组
Lucky小小吴1 小时前
有关django、python版本、sqlite3版本冲突问题
python·django·sqlite
GIS 数据栈1 小时前
每日一书 《基于ArcGIS的Python编程秘笈》
开发语言·python·arcgis
爱分享的码瑞哥1 小时前
Python爬虫中的IP封禁问题及其解决方案
爬虫·python·tcp/ip
傻啦嘿哟2 小时前
如何使用 Python 开发一个简单的文本数据转换为 Excel 工具
开发语言·python·excel
B站计算机毕业设计超人3 小时前
计算机毕业设计SparkStreaming+Kafka旅游推荐系统 旅游景点客流量预测 旅游可视化 旅游大数据 Hive数据仓库 机器学习 深度学习
大数据·数据仓库·hadoop·python·kafka·课程设计·数据可视化
IT古董3 小时前
【人工智能】Python在机器学习与人工智能中的应用
开发语言·人工智能·python·机器学习
湫ccc3 小时前
《Python基础》之pip换国内镜像源
开发语言·python·pip
hakesashou3 小时前
Python中常用的函数介绍
java·网络·python
菜鸟的人工智能之路4 小时前
极坐标气泡图:医学数据分析的可视化新视角
python·数据分析·健康医疗