关于Python基础阶段练习阶段(3)

#一阶段一:41-60

#----------------------------------------#
Question 41:
With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.

Hints:

Use [n1:n2] notation to get a slice from a tuple.

Solution

# 1-1

tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
print tp1
print tp2

# 1-2
def print_half_tuple(tup):
    half_length = len(tup) // 2
    first_half = tup[:half_length]
    second_half = tup[half_length:]

    print("First half:", first_half)
    print("Second half:", second_half)

# 测试函数
my_tuple = (1, 2, 3, 4, 5, 6)
print_half_tuple(my_tuple)

#----------------------------------------#
Question 42:
Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).

Hints:

Use “for” to iterate the tuple
Use tuple() to generate a tuple from a list.

Solution

tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in tp:
	if tp[i]%2==0:
		li.append(tp[i])

tp2=tuple(li)
print tp2

#----------------------------------------#
Question 43:
Write a program which accepts a string as input to print “Yes” if the string is “yes” or “YES” or “Yes”, otherwise print “No”.

Hints:

Use if statement to judge condition.

Solution

s= raw_input()
if s=="yes" or s=="YES" or s=="Yes":
    print "Yes"
else:
    print "No"

#----------------------------------------#
Question 44:
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].

Hints:

Use filter() to filter some elements in a list.
Use lambda to define anonymous functions.

Solution

li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = list(filter(lambda x: x%2==0, li))
print (evenNumbers)

#----------------------------------------#
Question 45:
Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.

Solution

li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = list(map(lambda x: x**2, li))
print (squaredNumbers)

#----------------------------------------#
Question 46:
Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.

Solution

li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = list(map(lambda x: x**2, filter(lambda x: x%2==0, li)))
print evenNumbers

#----------------------------------------#
Question 47:
Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).

Hints:

Use filter() to filter elements of a list.
Use lambda to define anonymous functions.

Solution

evenNumbers = list(filter(lambda x: x%2==0, range(1,21)))
print (evenNumbers)

#----------------------------------------#
Question 48:
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).

Hints:

Use map() to generate a list.
Use lambda to define anonymous functions.

Solution

squaredNumbers = list(map(lambda x: x**2, range(1,21)))
print (squaredNumbers)

#----------------------------------------#

Question 49:
Define a class named American which has a static method called printNationality.
Hints:
Use @staticmethod decorator to define class static method.
Solution

class American(object):
    @staticmethod
    def printNationality():
        print ("America")

anAmerican = American()
anAmerican.printNationality()
# 1-2
American.printNationality()

#----------------------------------------#

Question 50:
Define a class named American and its subclass NewYorker.
Hints:
Use class Subclass(ParentClass) to define a subclass.
Solution:

class American(object):
    pass

class NewYorker(American):
    pass

anAmerican = American()
aNewYorker = NewYorker()
print (anAmerican)
print (aNewYorker)

#----------------------------------------#
Question 51:
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(2)
print (aCircle.area())

#----------------------------------------#
Question 51:

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(2,10)
print aRectangle.area()

#----------------------------------------#
Question 52:

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():
    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())

#----------------------------------------#

Question 53:
Please raise a RuntimeError exception.
Hints:
Use raise() to raise an exception.
Solution:

raise RuntimeError('something wrong')

#----------------------------------------#
Question 54:
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 as err:
    print ('Caught an exception')
finally:
    print ('In finally block for cleanup')

#----------------------------------------#
Question 55:

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:

# 1-1

class MyError(Exception):
    """My own exception class

    Attributes:
        msg  -- explanation of the error
    """

    def __init__(self, msg):
        self.msg = msg

error = MyError("something wrong")
# 测试自定义异常类
try:
    raise error
except MyError as e:
    print("Caught custom exception:", e.msg)
# 1-2
class CustomException(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.message = message

# 测试自定义异常类
try:
    raise CustomException("This is a custom exception")
except CustomException as e:
    print("Caught custom exception:", e.message)

#----------------------------------------#
Question 56:

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 = raw_input()
pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAddress)
print r2.group(1)

#----------------------------------------#
Question 57:
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:

goegle
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 = raw_input()
pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print r2.group(2)

#----------------------------------------#
Question 58:
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))

# 1-2
def main():
    # 获取用户输入的由空格分隔的单词序列
    input_str = input("请输入由空格分隔的单词序列:")

    # 使用空格分隔输入字符串,得到单词列表
    words = input_str.split()

    # 遍历单词列表,检查每个单词是否仅由数字组成
    for word in words:
        if word.isdigit():
            print(word)

if __name__ == "__main__":
    main()

#----------------------------------------#
Question 59:

Print a unicode string “hello world”.
Hints:
Use u’strings’ format to define unicode string.

Solution:

# p2
unicodeString = u"hello world!"
print unicodeString

# p3
unicode_string = "hello world!"
print(unicode_string)

#----------------------------------------#
Question 60:

Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
Hints:
Use unicode() function to convert.

Solution:

# p2
s = raw_input()
u = unicode( s ,"utf-8")
print u

# p3
s = input()
print(s)

#----------------------------------------#

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值