100+ Python挑战性编程练习(2)

熟能生巧,多撸代码多读书

https://github.com/zhiwehu/Python-programming-exercises/blob/master/100+%20Python%20challenging%20programming%20exercises.txt

21、机器人从原点(0,0)开始在平面内移动。机器人可以按照给定的步骤向上、向下、向左和向右移动。机器人运动轨迹如右所示: 上 5  下 3  左 3  右2  i;方向后面的数字是步骤。请写一个程序来计算从当前位置经过一系列的移动和原始点的距离。如果距离是一个浮点数,那么只需打印最近的整数。

   例如:输入 UP 5   DOWN 3   LEFT 3   RIGHT 2    输出为 2

 1 import math
 2 pos = [0,0]
 3 while True:
 4     s = input()
 5     if not s:
 6         break
 7     movement = s.split(" ")
 8     direction = movement[0]
 9     steps = int(movement[1])
10     if direction=="UP":
11         pos[0]+=steps
12     elif direction=="DOWN":
13         pos[0]-=steps
14     elif direction=="LEFT":
15         pos[1]-=steps
16     elif direction=="RIGHT":
17         pos[1]+=steps
18     else:
19         pass
20 
21 print(int(round(math.sqrt(pos[1]**2+pos[0]**2))))
View Code

    注意:考察点为--  int(round(math.sqrt(pos[1]**2+pos[0]**2)))

22、编写一个程序来计算输入单词的频率。输出应该在对关键字进行数字排序后输出。

假设向程序提供以下输入:

是Python新手还是在python2和python3之间选择?阅读python2或python3。

则输出为: (没看明白什么意思,后期在研究)

 1 freq = {}   # frequency of words in text  文本中单词的频率
 2 line = input()
 3 for word in line.split():
 4     freq[word] = freq.get(word,0)+1
 5 
 6 words = freq.keys()
 7 words.sort()
 8 
 9 for w in words:
10     print("%s:%d" % (w,freq[w]))
View Code

23、写一个计算数字平方值的方法 (Using the ** operator)

1 def square(num):
2     return num ** 2
3 
4 print(square(2))
5 print(square(3))
View Code

24、Python有许多内置函数,如果您不知道如何使用它,您可以在线阅读文档或查找一些书籍。但是Python对于每个内置函数都有一个内置的文档函数,请编写程序打印一些Python内置函数文档,如abs(), int(), raw_input(),并为自己的函数添加文档。

  The built-in document method is __doc__

 1 def square(num):
 2     '''Return the square value of the input number.
 3 
 4     The input number must be integer.
 5     '''
 6     return num ** 2
 7 
 8 
 9 print(square(2))
10 print(square.__doc__)
11 # print(int.__doc__)
12 # print(abs.__doc__)
View Code

 25、定义一个类,该类有一个类参数和一个相同的实例参数。

   Define a instance parameter, need add it in __init__ method You can init a object with construct parameter or set the value later.

   定义一个实例参数,需要在_init__方法中添加它,您可以使用构造参数初始化一个对象,或者稍后设置该值。

 1 class Person:
 2     # Define the class parameter "name"
 3     name = "Person"
 4 
 5     def __init__(self, name=None):
 6         # self.name is the instance parameter
 7         self.name = name
 8 
 9 
10 jeffrey = Person("Jeffrey")
11 print("%s name is %s" % (Person.name, jeffrey.name))
12 
13 nico = Person()
14 nico.name = "Nico"
15 print("%s name is %s" % (Person.name, nico.name))
16 
17 # 输出结果为:
18 # Person name is Jeffrey
19 # Person name is Nico
View Code

26、定义一个可以计算两个数字和的函数。

1 def SumFunction(number1, number2):
2     return number1+number2
3 
4 print(SumFunction(1,2))
View Code

27、定义一个可以将整数转换为字符串并在控制台中打印它的函数。   --Use str() to convert a number to string.

def printValue(n):
    print(str(n))

printValue(3.0)

28、定义一个函数,该函数可以接收两个字符串形式的整数并计算它们的和,然后在控制台中打印它们。  --Use int() to convert a string to integer.

1 def printValue(s1,s2):
2     print(int(s1)+int(s2))
3 
4 printValue("3","4") #7
View Code

29、定义一个函数,该函数可以接受两个字符串作为输入,并连接它们,然后在控制台中打印它们。

1 def printValue(s1,s2):
2     print(s1+s2)
3 
4 printValue("3","4") #34
View Code

30、定义一个函数,该函数可以接受两个字符串作为输入,并在控制台中打印最大长度的字符串。如果两个字符串的长度相同,那么该函数应该逐行打印所有l字符串。

 1 def printValue(s1, s2):
 2     len1 = len(s1)
 3     len2 = len(s2)
 4     if len1 > len2:
 5         print(s1)
 6 
 7     elif len2 > len1:
 8         print(s2)
 9     else:
10         print(s1)
11         print(s2)
12 
13 
14 printValue("fuck", "you")
View Code

31、定义一个可以接受整数作为输入的函数,如果数字是偶数,则打印“它是偶数”,否则打印“它是奇数”。

1 def checkValue(n):
2     if n % 2 == 0:
3         print("It is an even number-偶数")
4     else:
5         print("It is an odd number-奇数")
6 
7 
8 
9 checkValue(72)
View Code

32、定义一个可以打印字典的函数,其中键是1到3之间的数字(包括),值是键的平方。

 1 def printDict(n):
 2     d = dict()
 3     d[1] = 1
 4     d[2] = 2 ** 2
 5     d[3] = 3 ** 2
 6     d[n] = n ** 2
 7     print(d)
 8 
 9 
10 
11 printDict(78)
12 
13 # 输出:  {1: 1, 2: 4, 3: 9, 78: 6084}
View Code

33、定义一个可以打印字典的函数,其中键是1到20之间的数字(包括),值是键的平方。

使用dict[key]=value模式将条目放入字典。   使用**运算符得到一个数的幂。   对循环使用range()。

---->>>  由于下面几题类似,code直接显示。

def printDict():
    d = dict()
    for i in range(1, 21):
        d[i] = i ** 2
    print(d)

printDict()
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}

34、定义一个函数,它可以生成一个字典,其中键是1到20之间的数字(包括),值是键的平方。函数应该只打印值。

 1 def printDict():
 2     d = dict()
 3     for i in range(1, 21):
 4         d[i] = i ** 2
 5     for (k, v) in d.items():
 6         print(v)
 7 
 8 
 9 
10 printDict()
View Code

35、定义一个函数,它可以生成一个字典,其中键是1到20之间的数字(包括),值是键的平方。该函数应该只打印键。

1 def printDict():
2     d = dict()
3     for i in range(1, 21):
4         d[i] = i ** 2
5     for k in d.keys():
6         print(k)
7 
8 
9 printDict()
View Code

36、定义一个函数,它可以生成和打印一个列表,其中的值是1到20之间的数字的平方(都包括在内)。(什么鬼,没完没了吗o(╥﹏╥)o)

1 def printList():
2     li = list()
3     for i in range(1, 21):
4         li.append(i ** 2)
5     print(li)
6 
7 
8 printList()
9 # # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
View Code

37、定义一个函数,它可以生成一个列表,其中的值是1到20之间的数字的平方(都包括在内)。然后该函数需要打印列表中的前5个元素。

1 def printList():
2     li = list()
3     for i in range(1, 21):
4         li.append(i ** 2)
5     print(li[:5])
6 
7 printList()
8 # [1, 4, 9, 16, 25]   我怀疑这老哥是在凑题目总数
View Code

38、定义一个函数,它可以生成一个列表,其中的值是1到20之间的数字的平方(都包括在内)。然后该函数需要打印列表中的最后5个元素。

1 def printList():
2     li = list()
3     for i in range(1, 21):
4         li.append(i ** 2)
5     print(li[-5:])
6 
7 printList()
8 # [256, 289, 324, 361, 400] 
View Code

39、定义一个函数,它可以生成一个列表,其中的值是1到20之间的数字的平方(都包括在内)。然后,该函数需要打印列表中除前5个元素之外的所有值。

40、定义一个函数,它可以生成和打印一个元组,其中的值是1到20之间的数字的平方(都包括在内)。

1 def printTuple():
2     li = list()
3     for i in range(1, 21):
4         li.append(i ** 2)
5     print(tuple(li))
6 
7 
8 printTuple()
9 # (1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400)
View Code

=============================分割线================缓一缓=======================================

41、对于给定的元组(1、2、3、4、5、6、7、8、9、10),编写一个程序将前半值打印在一行中,后半值打印在一行中。

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

42、编写一个程序来生成和打印另一个元组,它的值是给定元组中的偶数(1、2、3、4、5、6、7、8、9、10)。

 1 tp=(1,2,3,4,5,6,7,8,9,10)
 2 li=list()
 3 for i in tp:
 4     # print(i)
 5     if i%2==0:
 6         li.append(i)
 7 
 8 tp2=tuple(li)
 9 print(tp2)
10 #(2, 4, 6, 8, 10)
View Code

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".

1 s= input()
2 if s=="yes" or s=="YES" or s=="Yes":
3     print("Yes")
4 else:
5     print("No")
View Code

44、编写一个程序,可以过滤列表中的偶数使用过滤功能。列表是:[1、2、3、4、5、6、7、8、9、10]。

li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print(evenNumbers)
#<filter object at 0x000001891A2162B0>
# 它生成的是一个对象, 这是想表达什么意思?求解

45、编写一个可以映射()的程序,生成一个元素是[1,2,3,4,5,6,7,8,9,10]中元素的平方的列表。

li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print(squaredNumbers)
# <map object at 0x000002CCD4976208>

46、编写一个程序,可以映射()和过滤器(),使一个列表的元素是偶数的平方在[1,2,3,4,5,6,7,8,9,10]。

li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print(evenNumbers)
# <map object at 0x000001F9391D6BA8>

47、编写一个可以filter()的程序,生成一个元素在1到20之间的偶数列表(都包含在内)。

evenNumbers = filter(lambda x: x%2==0, range(1,21))
print (evenNumbers)
# <filter object at 0x00000254AE8F6630>

48、编写一个可以映射()的程序,生成一个元素为1到20之间的数字的平方的列表(都包含在内)。

squaredNumbers = map(lambda x: x**2, range(1,21))
print(squaredNumbers)
# <map object at 0x000001F2ABA369E8>
#上面几个在研究一下

49、定义一个名为American的类,该类有一个名为printNationality的静态方法。

 1 class American(object):
 2     @staticmethod
 3     def printNationality():
 4         print("America")
 5 
 6 anAmerican = American()
 7 anAmerican.printNationality()
 8 American.printNationality()
 9 
10 # America
11 # America
View Code

50、定义一个名为American的类及其子类NewYorker。

 1 class American(object):
 2     pass
 3 
 4 class NewYorker(American):
 5     pass
 6 
 7 anAmerican = American()
 8 aNewYorker = NewYorker()
 9 print(anAmerican)
10 print(aNewYorker)
11 
12 # <__main__.American object at 0x000001A7D04B62B0>
13 # <__main__.NewYorker object at 0x000001A7D04B6A20>
View Code

51、定义一个名为Circle的类,它可以由一个半径来构造。Circle类有一个计算面积的方法。

1 class Circle(object):
2     def __init__(self, r):
3         self.radius = r
4 
5     def area(self):
6         return self.radius**2*3.14
7 
8 aCircle = Circle(521)
9 print(aCircle.area())
View Code

52、定义一个名为Rectangle的类,它可以由长度和宽度来构造。矩形类有一个可以计算面积的方法。

 1 class Rectangle(object):
 2     def __init__(self, l, w):
 3         self.length = l
 4         self.width  = w
 5 
 6     def area(self):
 7         return self.length*self.width
 8 
 9 aRectangle = Rectangle(2,10)
10 print(aRectangle.area())
View Code

53、定义一个名为Shape的类及其子类Square。Square类有一个init函数,它以长度作为参数。这两个类都有一个area函数,可以打印形状的面积,其中形状的面积默认为0。

 1 class Shape(object):
 2     def __init__(self):
 3         pass
 4 
 5     def area(self):
 6         return 0
 7 
 8 class Square(Shape):
 9     def __init__(self, l):
10         Shape.__init__(self)
11         self.length = l
12 
13     def area(self):
14         return self.length*self.length
15 
16 aSquare= Square(3)
17 print(aSquare.area())
View Code

54、请抛出一个RuntimeError异常。

raise RuntimeError('something wrong')

55、编写一个函数来计算5/0并使用try/except来捕获异常。

 1 def throws():
 2     return 5/0
 3 
 4 try:
 5     throws()
 6 except ZeroDivisionError:
 7     print("division by zero!")
 8 except Exception as err :
 9     print('Caught an exception')
10 finally:
11     print('In finally block for cleanup')
12     
13 # division by zero!
14 # In finally block for cleanup
View Code

注意:Python 语法错误 except Exception python2 和Python3 区别,github上的是2,需要改回来

希望不再熬夜,不要一个人,晚安,加油。

猜你喜欢

转载自www.cnblogs.com/pythonbetter/p/11964863.html