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

相关推荐
Salt_07282 小时前
DAY 19 数组的常见操作和形状
人工智能·python·机器学习
无心水2 小时前
【Python实战进阶】2、Jupyter Notebook终极指南:为什么说不会Jupyter就等于不会Python?
python·jupyter·信息可视化·binder·google colab·python实战进阶·python工程化实战进阶
上班日常摸鱼3 小时前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
无心水3 小时前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶
2301_807583234 小时前
了解python,并编写第一个程序,常见的bug
linux·python
小白学大数据4 小时前
构建混合爬虫:何时使用Requests,何时切换至Selenium处理请求头?
爬虫·python·selenium·测试工具
2401_827560204 小时前
【Python脚本系列】PyAudio+librosa+dtw库录制、识别音频并实现点击(四)
python·语音识别
BBB努力学习程序设计4 小时前
Python自动化脚本:告别重复劳动
python·pycharm
BBB努力学习程序设计4 小时前
Python函数式编程:优雅的代码艺术
python·pycharm
2501_940943914 小时前
体系课\ Python Web全栈工程师
开发语言·前端·python