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

#一阶段一:21-40
#----------------------------------------#
Question 21
Level 3

Question
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:
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:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

import math
pos = [0,0]
while True:
    s = input("执行动作")
    # s = raw_input()
    if not s:
        break
    movement = s.split(" ")
    direction = movement[0]
    steps = int(movement[1])
    if direction=="UP":
    # if direction=="UP" or direction=="up":
        pos[0]+=steps
    elif direction=="DOWN":
        pos[0]-=steps
    elif direction=="LEFT":
        pos[1]-=steps
    elif direction=="RIGHT":
        pos[1]+=steps
    else:
        pass
#print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
print (int(round(math.sqrt(pos[1]**2+pos[0]**2))))

#----------------------------------------#
Question 21;数学函数
#----------------------------------------#
Question 22:
Level 3

Question:
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:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1

Hints
In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

freq = {}   # frequency of words in text
line = input("input words :")
# line = raw_input()
for word in line.split():
    freq[word] = freq.get(word,0)+1

words = freq.keys()
# 将words对象转换为列表
words = list(words)
words.sort()

for w in words:
    print ("%s:%d" % (w,freq[w]))

#----------------------------------------#
Question 22 :python2 与 python3 freq.keys()de 区别
#----------------------------------------#
Question 23:
level 1

Question:
Write a method which can calculate square value of number

Hints:
Using the ** operator

Solution:

def square(num):
    return num ** 2

# print (square(2))
print square(3)

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

#----------------------------------------#
Question 24:
Level 1

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

Hints:
The built-in document method is doc

Solution:

print abs.__doc__
print int.__doc__
print raw_input.__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 24 函数文档式设置
#----------------------------------------#
Question 25:
Level 1

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

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

Solution:

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 ("%s name is %s" % (Person.name, jeffrey.name))

nico = Person()
nico.name = "Nico"
print ("%s name is %s" % (Person.name, nico.name))

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

#----------------------------------------#
Question 26:
Define a function which can compute the sum of two numbers.

Hints:
Define a function with two numbers as arguments. You can compute the sum in the function and return the value.

Solution

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.

Hints:

Use str() to convert a number to string.

Solution

def printValue(n):
	print str(n)

printValue(3)

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

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

Hints:

Use int() to convert a string to integer.

Solution

def printValue(s1,s2):
	print (int(s1)+int(s2))

printValue("3","4") #7

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

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

Hints:

Use + to concatenate the strings

Solution

def printValue(s1,s2):
	print s1+s2

printValue("3","4") #34

#----------------------------------------#
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 al l strings line by line.

Hints:

Use len() function to get the length of a string

Solution

def printValue(s1,s2):
	len1 = len(s1)
	len2 = len(s2)
	if len1>len2:
		print s1
	elif len2>len1:
		print s2
	else:
		print s1
		print s2
		

printValue("one","three")

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

Question 31:
Define a function that can accept an integer number as input and print the “It is an even number” if the number is even, otherwise print “It is an odd number”.

Hints:

Use % operator to check if a number is even or odd.

Solution

def checkValue(n):
	if n%2 == 0:
		print "It is an even number"
	else:
		print "It is an odd number"
		
num = int(input("Enter an integer: "))

checkValue(num)

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

Question 32:
Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys.

Hints:

Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.

Solution

# 1-1
def printDict():
	d=dict()
	d[1]=1
	d[2]=2**2
	d[3]=3**2
	print d
		
printDict()

# 1-2
def print_square_dict():
    square_dict = {}
    for i in range(1, 4):
        square_dict[i] = i ** 2
    print(square_dict)

# 测试函数
print_square_dict()

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

Question 33:
Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.

Hints:

Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.

Solution

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

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

Question 34:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only.

Hints:

Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.

Solution

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

printDict()

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

Question 35:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.

Hints:

Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.

Solution

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

printDict()

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

Question 36:
Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).

Hints:

Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.

Solution

def printList():
	li=list()
	for i in range(1,21):
		li.append(i**2)
	print (li)
		

printList()

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

Question 37:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.

Hints:

Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list

Solution

def printList():
	li=list()
	for i in range(1,21):
		li.append(i**2)
	print (li[:5])
		

printList()

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

Question 38:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.

Hints:

Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list

Solution

def printList():
	li=list()
	for i in range(1,21):
		li.append(i**2)
	print (li[-5:])
		

printList()

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

Question 39:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.

Hints:

Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list

Solution

def printList():
	li=list()
	for i in range(1,21):
		li.append(i**2)
	print (li[5:])
		

printList()

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

Question 40:
Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).

Hints:

Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use tuple() to get a tuple from a list.

Solution

def printTuple():
	li=list()
	for i in range(1,21):
		li.append(i**2)
	print (tuple(li))
		
printTuple()

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值