前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python基础练习100题 ( 21

Python基础练习100题 ( 21

作者头像
py3study
发布2020-01-06 15:38:52
4710
发布2020-01-06 15:38:52
举报
文章被收录于专栏:python3python3

刷题继续

昨天和大家分享了前10道题,今天继续来刷21~30

Question 21:

A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:

代码语言:javascript
复制
UP 5
DOWN 3
LEFT 3
RIGHT 2

The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program:

代码语言:javascript
复制
UP 5
DOWN 3
LEFT 3
RIGHT 2

Then, the output of the program should be:

代码语言:javascript
复制
2

解法一
代码语言:javascript
复制
import  math

x,y = 0,0
while True:
    s = input().split()
    if not s:
        break
    if s[0]=='UP':                  # s[0] indicates command
        x-=int(s[1])                # s[1] indicates unit of move
    if s[0]=='DOWN':
        x+=int(s[1])
    if s[0]=='LEFT':
        y-=int(s[1])
    if s[0]=='RIGHT':
        y+=int(s[1])
                                    # N**P means N^P
dist = round(math.sqrt(x**2 + y**2))  # euclidean distance = square root of (x^2+y^2) and rounding it to nearest integer
print(dist)

Question 22:

Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.Suppose the following input is supplied to the program:

代码语言:javascript
复制
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.

Then, the output should be:

代码语言:javascript
复制
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1

解法一
代码语言:javascript
复制
ss = input().split()
word = sorted(set(ss))     # split words are stored and sorted as a set

for i in word:
    print("{0}:{1}".format(i,ss.count(i)))
解法二
代码语言:javascript
复制
ss = input().split()
dict = {}
for i in ss:
    i = dict.setdefault(i,ss.count(i))   

dict = sorted(dict.items())            
                                         
for i in dict:
    print("%s:%d"%(i[0],i[1]))
解法三
代码语言:javascript
复制
from collections import Counter

ss = input().split()
ss = Counter(ss)         # returns key & frequency as a dictionary
ss = sorted(ss.items())  # returns as a tuple list

for i in ss:
    print("%s:%d"%(i[0],i[1]))

Question 23:

Write a method which can calculate square value of number

解法一
代码语言:javascript
复制
def square(num):
    return num ** 2

print(square(2))
print(square(3))
解法二
代码语言:javascript
复制
n=int(input())
print(n**2)

Question 24:

Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input() And add document for your own function

解法一
代码语言:javascript
复制
print (abs.__doc__)
print (int.__doc__)

def square(num):
    '''
 Return the square value of the input number.
 The input number must be integer.
 '''
    return num ** 2

print (square(2))
print (square.__doc__)

Question 25:

Define a class, which have a class parameter and have a same instance parameter.

解法一
代码语言:javascript
复制
class Car:
    name = "Car"

    def __init__(self,name = None):
        self.name = name

honda=Car("Honda")
print("%s name is %s"%(Car.name,honda.name))

toyota=Car()
toyota.name="Toyota"
print("%s name is %s"%(Car.name,toyota.name))
解法二
代码语言:javascript
复制
class Person:
    # Define the class parameter "name"
    name = "Person"
    
    def __init__(self, name = None):
        # self.name is the instance parameter
        self.name = name

jeffrey = Person("Jeffrey")
print ("{0} name is {1}".format(Person.name, jeffrey.name))

nico = Person()
nico.name = "Nico"
print (f"{Person.name} name is {nico.name}")

Question 26:

Define a function which can compute the sum of two numbers.

解法一
代码语言:javascript
复制
sum = lambda n1,n2 : n1 + n2      # here lambda is use to define little function as sum
print(sum(1,2))
解法二
代码语言:javascript
复制
def SumFunction(number1, number2):
    return number1 + number2

print SumFunction(1,2)

Question 27:

Define a function that can convert a integer into a string and print it in console.

解法一
代码语言:javascript
复制
def printValue(n):
    print (str(n))

printValue(3)
解法二
代码语言:javascript
复制
conv = lambda x : str(x)
n = conv(10)
print(n)
print(type(n))  

Question 28:

Define a function that can receive two integer numbers in string form and compute their sum and then print it in console.

解法一
代码语言:javascript
复制
def printValue(s1,s2):
    print int(s1) + int(s2)
printValue("3","4") #7
解法二
代码语言:javascript
复制
sum = lambda s1,s2 : int(s1) + int(s2)
print(sum("10","45"))      # 55

Question 29:

Define a function that can accept two strings as input and concatenate them and then print it in console.

解法一
代码语言:javascript
复制
def printValue(s1,s2):
    print s1 + s2

printValue("3","4") #34
解法二
代码语言:javascript
复制
sum = lambda s1,s2 : s1 + s2
print(sum("10","45"))        # 1045

Question 30:

Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print all strings line by line.

解法一
代码语言:javascript
复制
def printVal(s1,s2):
    len1 = len(s1)
    len2 = len(s2)
    if len1 > len2:
        print(s1)
    elif len1 < len2:
        print(s2)
    else:
        print(s1)
        print(s2)

s1,s2=input().split()
printVal(s1,s2)

源代码下载

这十道题的代码在我的github上,如果大家想看一下每道题的输出结果,可以点击以下链接下载:

我的运行环境Python 3.6+,如果你用的是Python 2.7版本,绝大多数不同就体现在以下3点:

  • raw_input()在Python3中是input()
  • print需要加括号
  • fstring可以换成.format(),或者%s,%d

谢谢大家,我们下期见!希望各位朋友不要吝啬,把每道题的更高效的解法写在评论里,我们一起进步!!!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 刷题继续
    • Question 21:
      • Question 22:
        • Question 23:
          • Question 24:
            • Question 25:
              • Question 26:
                • Question 27:
                  • Question 28:
                    • Question 29:
                      • Question 30:
                      • 源代码下载
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档