Python core Programming chapter sixth practice answers after class

Source: Internet
Author: User
2. String designator, modify 6-1 idcheck.py script, so that it can detect the length of the identifier, and can identify the Python keyword, the latter requirement, you can use the keyword module (especially keyword.kwlist) to assist

Source:

' This is a module of the Idcheck for keyword '


Import keyword
Import string


KW = Keyword.kwlist
num = string.digits
Letters = String.letters
Alpha = letters + ' _ '
alphalist = alpha + num


Myinput = raw_input (' Please enter an identifier: ')


If Len (myinput) = = 1: #首先判断输入是否是长度为1的字符串
if (myinput[0] not in Alpha):
print ' Invalid:first char must is letter or _ '
Else
print ' This is a ID len 1 '


If Len (myinput) > 1: #当输入字符串长度大于1时
If myinput[0] not in alpha: #判断首字母是否是满足要求
print ' Invalid:first char must is letter or _ '

Else

If myinput in kw: #判断是否是关键字
print ' invalid:this is keyword '
else: #判断之后的字符是否满足要求
For Otherchar in myinput[1:]:
If Otherchar not in Alphalist:
print ' invalid:input must be in Alphalist '
Break
else: #else一定要是和for循环处于同一级别, to determine whether it is a legal character after the end of the loop
print ' ID is identifier '


3. Sorting

(a) Enter a string of numbers and arrange them from large to small.

(b) Same as a, but in dictionary order from large to small

Source:

' This is a module for Paixu '


String = raw_input ("Input num (end With '! ')"). The split () #加入split () function is to remove spaces




#以自然数的形式从大到小输出


List = []
For each in string:
List.append (int (each))
Test = sorted (List) [:: -1] #从小到大输出
Print test


#以字典的形式 (by the first letter of each element in the dictionary) from large to small output


Dict = []
For each in string:
Dict.append (each)


Test2 = sorted (Dict) [:: -1] #从小到大输出
Print Test2


5. String

(a) Update your program in exercise 2-7 so that it can display a character of a string each time forward and backwards.

(b) Scan to determine if two strings match (cannot use the comparison operator CMP () built-in functions). Additional questions: Add case distinction in your scenario.

(c) To determine whether a string is reproduced (followed by the previous one), additional questions: In addition to dealing with a strict palindrome, add support for such as control symbols and spaces.

(d) accept a character followed by a reverse copy, constituting a palindrome string.

Source:

(b):

#coding: Utf-8
STR1 = Raw_input ("Enter a string1-->")
STR2 = Raw_input ("Enter a string2-->")


If Len (str1)!= len (str2):
print ' str1 not match str2 '
Else
for char in range (0,len (str1)):
If Str1[char]!= Str2[char]:
print ' str1 not match str2 '
Break
Else
print ' str1 match str2 '


6. String, create a string.strip () substitution function: Accept a string, remove the space before and after it (if you use the String.*strip () function, the practice is meaningless)

Source:

#coding =utf-8


' This function can be used to replace the String.strip () function '




string = Raw_input (' Enter the string: ')


A, last = 0, 0


If string[0] = = ' and String[len (String)-1] = = ': #前后都有空格
print ' All owm spaces '
For char in string: #判断第一个字符是否是空格以及空格的个数
if char = = ':
A + 1
Else
#print String[first:]
Break
For Char in string[::-1]: #判断最后一个字符是否是空格以及空格的个数
if char = = ':
Last + + 1
Else
Print String[first:len (String)-last]
Print Last
Break

Elif string[0] = = ': #前面有空格后面没空格
print ' least one space '
For char in string:
if char = = ':
A + 1
Else
Print String[first:]
Break

Elif String[len (String)-1] = = ': #后面有空格前面没空格
print ' least last one space '
For Char in string[::-1]:
if char = = ':
Last + + 1
Else
Print String[:len (string)-last]
Print Last
Break
else: #前后都没有空格
print ' No space '
Print string

8. List, give an integer value, return the English that represents the value, such as input 89 return "Eight-nine". Attachment question: Can return conforms to the English grammar rule the form, like enters "89" to return "Eighty-nine". The values in this exercise are limited to 0~1000.

Source:

#coding =utf-8
units = [
' Zero ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine ', ' Ten ',
' Eleven ', ' twelve ', ' thirteen ', ' Forteen ', ' Fifteen ', ' sixteen ', ' Seventeen ',
' Eighteen ', ' nineteen '
]
TENS = [' Twenty ', ' Thirty ', ' Forty ', ' Fifty ', ' Sixty ', ' Seventy ', ' Eighty ', ' ninety ']
hundreds = [' hundreds ']




While True:
Myinput = Raw_input ("Enter" num--> (input ' quit ' to quit): ") #字符串输入
if myinput = = ' Quit ':
Break
myinput_num = Int (myinput) #将字符串输入转整型
Input_num = [] #列表



For i in Myinput: #将输入的字符串转化为列表
Input_num.append (int (i))


If Myinput_num <: #20以下的英文输出
Print Units[myinput_num]




Elif Myinput_num <: #100以下的输出
If input_num[1] = = 0:
Print Tens[input_num[0]-2]
Else
Print (Tens[input_num[0]-2] + '-' + units[input_num[1]]



Elif Myinput_num < 1000:
if (input_num[2] = = 0 and input_num[1] = = 0): #第二, three bits equals 0 (note: This statement needs to be placed at the top, if the latter two sentences are first executed, this will be the case, the last one will output zero)
Print Units[input_num[0]] + ' + ' hundreds '
Elif input_num[1] = = 0: #第二位等于0
Print Units[input_num[0]] + ' + ' hundreds ' + ' + ' + ' + ' + units[input_num[2]]
Elif input_num[2] = = 0: #第三位等于0
Print Units[input_num[0]] + ' + ' hundreds ' + ' + ' + ' + ' + tens[input_num[1]-2]
else: #每一位都不等于0
Print Units[input_num[0]] + ' + ' hundreds ' + ' + ' + ' + ' + tens[input_num[1]-2] + '-' + units[input_num[2]


9. Convert, write a sister function for exercise 5-13, accept minutes, return hours and minutes. The total time is unchanged and the number of hours required is as large as possible.

Source:

#coding =utf-8
' This is a module-translate minute to hour and minute '


While True:
temp = raw_input ("Enter" Minute (input ' quit ' to quit): ")


if temp = = ' quit ':
Break

time = Int (temp)
hour = time//60
minute = time% 60
If minute = 0:
print ' After trans:%d Hour '% hour
Else
print ' After trans:%d hour%d minute '% (hour, minute)


10. String, write a function, return a string similar to the input string, requiring a string inversion of the case. For example, if you enter "Mr.ed", you should return "Mr.ed" as output.

Source:

#coding =utf-8


"This was a module of change ' A ' to ' a ' or ' a '" a ' "


string = raw_input (' Input the string you want to change: ')
Print string.swapcase () #大小写转化函数

11. Conversion.

(a) Create a translator from an IP address to the following format: WWW.XXX.YYY.ZZZ

(b) Update your program so that it can be reversed.

Source:

#coding =utf-8


"" "" is a module of the tranfer ' int ' to IP address ""


Def int_transfer (): #将ip地址转化为整型
"""
The Raw_input return type is str, and the split () function can pass the string
Specifies the delimiter and number of times to divide an object into a list of functions, so the return type is a list


"""
Int_num = raw_input ("Input nums with space split:"). Split ()



"""
The join () function is a string, tuple, element in a list that can be generated with a specified delimiter connection
A new string, the return type is a string
"""
IP_Address = '. '. Join (Int_num)
Print IP_Address


Def ip_transfer (): #将整型数据转化为ip地址


IP_Address = raw_input ("Input IP Address:"). Split ('. ')


Int_num = '. Join (IP_Address)


Print Int_num


if __name__ = = ' __main__ ':
Int_transfer ()
Ip_transfer ()


12. String.

(a) Create a function named FINDCHR (), which declares the following function.

def FINDCHR (String,char)

FINDCHR () to find char char in string strings, find the index that returns the value, or return-1. Cannot use String.*find () or String.*index functions and methods

(b) Create another function called RFINDCHR () to find the last occurrence of the character Char. It's similar to FINDCHR (), but it's looking forward from the end of the string.

(c) Create a third function, named SUBCHR (), as stated below.

def SUBCHR (String,origchar,newchar)

SUBCHR () is similar to FINDCHR (), but if a matching character is found, the original character is replaced with the new character. Returns the modified string. Source:

#coding =utf-8
"This is a Module of the replace find ()"


Def findchar (String, char): #顺序查找字符串
#设置循环从0到两组字符串长度之差
For I in range (0, Len (string)-Len (char) + 1)):
#判断切片后的string内容是否与char相同, the same return index value
If String[i: (i + len (char))] = = Char:
return I
#for循环结束之后, all characters are traversed after the return-1 is not found
Else
Return-1

Def rfindchar (String, char): #逆序查找字符串


The #当findchar () function is not equal to-1 when the result is returned, and the length of the char is added to the position of the last occurrence
If Findchar (string, char)!=-1:
Return Findchar (String, char) + len (char)-1
The #当findchar () function equals-1 when no result is returned, the output-1
Else
Return-1


Def subchar (String, char, Newchar): #替换查找的字符串
If Findchar (string, char)!=-1:
return String.Replace (Char,newchar)






if __name__ = = ' __main__ ': #主函数
string = raw_input (' Input the string: ')
char = raw_input (' Input the char ' want find: ')
The result of the print ' Order lookup is: '
Print Findchar (string, char)

The result of print ' reverse lookup is: '
Print Rfindchar (string, char)


Newchar = raw_input (' Input the new char: ')
Print Subchar (string, char, Newchar)

14. Random number. Design a "stone, scissors, cloth" game. In the computer, the user enters the option, the computer produces a random option, and then uses the program to determine the final result, as little as possible with the IF statement

Source:

#coding =utf-8


Import Random
"This is a finger-guessing game"


Guess = ' A:stone '
B:scissor
C:paper
'''
result = [[' A ', ' B '],[' B ', ' C '],[' C ', ' a ']]


While True:
Print Guess,
Your_choice = Raw_input (' Enter your Choice (input "quit" to quit): \ n ')
print ' Your choice is:%s '% Your_choice
if Your_choice = = ' Quit ':
Break
If Your_choice!= ' a ' and Your_choice!= ' B ' and Your_choice!= ' C ':
print ' only can choose a or B or C! (only select a, B, c) '
Print
Continue
temp = [' A ', ' B ', ' C ']
Computer_choice = Random.choice (temp)
print ' Computer choice is:%s '% Computer_choice
if Computer_choice = = Your_choice:
print ' Draw '
elif [Computer_choice,your_choice] in result:
print ' Computer wins! '
Print
Else
print ' You wins! '
Print


15. Give two recognizable dates, such as MM/DD/YY or DD/MM/YY format, to calculate the number of days between two dates

Source:

#coding =utf-8


' This is a module of ' using function to count time '


Import datetime
Import Math


def string_transfer_time (string): #将字符串转化为指定的时间格式


The #strptime (string, ' specify format ') function converts a string to a specified time format.
#但是需要在datetime. DateTime type, the Datetime.datetime type is returned at the same time
#实际输出看到的效果与字符串相同


Date_time = Datetime.datetime.strptime (String, '%y-%m-%d '). Date ()


#datetime. Datetime.strptime () returns the format of time plus date, so you need to add the following
#日常函数的限制, in addition, the middle must be datetime, otherwise there is no strptime in other types
#这个类型
Return date_time


def count_days (date_time1,date_time2): #计算两个日期之间的天数
Delta = ABS (date_time1-date_time2) #利用abs计算绝对值
Return delta.days #delta. Days can be used to calculate the difference between two dates


if __name__ = = ' __main__ ':
date_time1 = raw_input (' Please enter a date formatted as YY-MM-DD: ')
date_time2 = raw_input (' Please enter a date formatted as YY-MM-DD: ')
Temp1 = String_transfer_time (date_time1)
Temp2 = String_transfer_time (date_time2)
result = Count_days (TEMP1,TEMP2)
Print result






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.