练习一:自己定义一个reverse(s)函数,功能返回字符串s的倒序字符串。


In [1]:
def reverse(s):
    rev_s = [0]*len(s)
    for i in range(len(s)):
        rev_s[len(s)-i-1] = s[i]
    s = rev_s
    print (s)

s = [1,2,3,4,5,6,7,8]
reverse(s)


[8, 7, 6, 5, 4, 3, 2, 1]

练习二:写函数,根据给定符号和行数,打印相应直角三角形,等腰三角形及其他形式的三角形。


In [3]:
def play_triangel(symbol,line_num):
    print ('直角三角形:')   #加上列号似乎有多种,其余同理
    for i in range(line_num):
        print (' '*(line_num-i-1)+symbol*(i+1))
    print ('等腰三角形:')  
    for i in range(line_num):
        print (' '*(line_num-i-1)+symbol*(i)+'*'+symbol*(i)+' '*(line_num-i-1))
    print ('其他三角形:')  #不是很懂,其余?    
    for i in range(line_num):
        if i < line_num//2:
            print (' '*(line_num-i-1)+symbol*(i+1))
        else:
            if line_num%2 == 0:
                j = line_num-i-2
            else:
                j = line_num-i-1
            print (' '*(line_num-j-1)+symbol*(j+1))
               
symbol = '*' 
line_num = int(input("请输入行号,回车结束:"))
play_triangel(symbol,line_num)


请输入行号,回车结束:7
直角三角形:
      *
     **
    ***
   ****
  *****
 ******
*******
等腰三角形:
      *      
     ***     
    *****    
   *******   
  *********  
 *********** 
*************
其他三角形:
      *
     **
    ***
   ****
    ***
     **
      *

练习三:将任务4中的英语名词单数变复数的函数,尽可能的考虑多种情况,重新进行实现。


In [4]:
#写成英语名词了,就不写动词了

def sin_to_plu(Eng_word):
    if Eng_word.endswith('s') or Eng_word.endswith('x') or Eng_word.endswith('sh') or Eng_word.endswith('ch'):
        print (Eng_word+'es')
    elif Eng_word.endswith('y'):
        print (Eng_word[0:len(Eng_word)-1]+'ies')
    elif Eng_word.endswith('f') or Eng_word.endswith('fe'):
        if Eng_word == 'safe' or Eng_word == 'roof': #这特殊情况能列举不完
            print (Eng_word+'s')
        elif(Eng_word.endswith('f')):
            print (Eng_word[0:len(Eng_word)-1]+'ves')
        else :
            print (Eng_word[0:len(Eng_word)-2]+'ves')
    elif Eng_word.endswith('o'):
        if Eng_word == 'tomato' or Eng_word == 'tomato' or Eng_word == 'hero' or Eng_word == 'negro':  #这特殊情况能列举不完
            print (Eng_word+'es')
        else :
            print (Eng_word+'s')
    #elif #不规则的单词 就不写了
    else :
        print (Eng_word+'s')
        
while True :
    Eng_word = input('请输入一个要转换的英语单词,回车结束,输入‘q’结束  ')
    if Eng_word == 'q':
        break
    sin_to_plu(Eng_word)


请输入一个要转换的英语单词,回车结束,输入‘q’结束  tomato
tomatoes
请输入一个要转换的英语单词,回车结束,输入‘q’结束  safe
safes
请输入一个要转换的英语单词,回车结束,输入‘q’结束  life
lives
请输入一个要转换的英语单词,回车结束,输入‘q’结束  bus
buses
请输入一个要转换的英语单词,回车结束,输入‘q’结束  q

练习四:写函数,根据给定符号,上底、下底、高,打印各种梯形。


In [5]:
def play_trapezium(symbol,upper_line,lower_line,height):
    print ('trapezium:')   
    for i in range(height):
        print (' '*(lower_line-upper_line-i)+symbol*(i+upper_line))
        
symbol = '*' 
upper_line = int(input("请输入梯形上底,回车结束:"))
lower_line = int(input("请输入梯形下底,回车结束:"))
height = int(input("请输入梯形的高,回车结束:"))
play_trapezium(symbol,upper_line,lower_line,height)


请输入梯形上底,回车结束:6
请输入梯形下底,回车结束:12
请输入梯形的高,回车结束:6
trapezium:
      ******
     *******
    ********
   *********
  **********
 ***********

练习五:写函数,根据给定符号,打印各种菱形。


In [7]:
def play_rhombus(symbol,line_num):
    print ('rhombus:')  
    for i in range(line_num):
        if i < line_num//2:
            print (' '*(line_num-i-1)+symbol*(i)+'*'+symbol*(i)+' '*(line_num-i-1))
        else:
            if line_num%2 == 0:
                j = line_num-i-2
                if (i != line_num-1):
                    print (' '*(i+1)+symbol*(j)+'*'+symbol*(j)+' '*(i))
            else:
                j = line_num-i-1
                print (' '*(i)+symbol*(j)+'*'+symbol*(j)+' '*(i))
symbol = '*' 
line_num = int(input("请输入行数,回车结束:"))  
play_rhombus(symbol,line_num)


请输入行数,回车结束:7
rhombus:
      *      
     ***     
    *****    
   *******   
    *****    
     ***     
      *      

练习六:加密解密文件


In [1]:
import random

def compute_rand_key():
    rand_num = [0]*9
    for i in range(9):
        rand_num[i] = random.randint(0,9)
    return rand_num

def compute_rand_letter():
    rand_letter = random.randint(65,122)
    while rand_letter >= 91 and rand_letter <= 96:
        rand_letter = random.randint(65,122)
    return rand_letter

def encode(rand_key,word_len):
    file_in = open('F:\\python\\419test.txt','r')
    file_out = open('F:\\python\\419test_new_out.txt','w')
    for line in file_in:
        symbol = '.,?'
        for s in symbol: 
            line = line.replace(s,' ')
        line = line.split()
        for word in line:
            word_len.append(len(word))
            key = rand_key.copy()
            key.append(len(word))
            word_new = []
            for i in range(len(word)):
                ascii_i = ord(word[i])
                #ascii_i >> int(key[i])
                ascii_i += int(key[i])
                ascii_i = chr(ascii_i)
                word_new.append(ascii_i)
            for j in range(len(word),10):   # len(word)要如何保存下来
                rand_le = compute_rand_letter()
                word_new.append(chr(rand_le))
            word_new = "".join(word_new)
            #print (word_new)
            file_out.write(word_new+' ')
    file_in.close()
    file_out.close()

def decode(rand_key,word_len):
    file_in = open('F:\\python\\419test_new_out.txt','r')
    file_out = open('F:\\python\\419test_old_out.txt','w')
    for line in file_in:
        print (line+'\n解密后的文件:')
        line = line.split()
        j = 0
        for word_new in line:
            rand_key.append(len(word_new))   ###如何得到原来的len(word)即字符的长度
            key = rand_key.copy()
            word_old = []
            for i in range(int(word_len[j])):
                ascii_i = ord(word_new[i])
                #ascii_i << int(key[i])
                ascii_i -= int(key[i])
                ascii_i = chr(ascii_i)
                word_old.append(ascii_i)

            word_old = "".join(word_old)
            j += 1
            print (word_old)
            file_out.write(word_old+' ')
    file_in.close()
    file_out.close()

def main():
    file_in = open('F:\\python\\419test.txt','r')
    print ('加密前的文件:')
    for line in file_in:
        print (line)
    word_len = []
    rand_key = compute_rand_key()
    encode(rand_key,word_len)
    print ('加密后的文件:')
    decode(rand_key,word_len)
        
    print ('''    -----------------分割线-----------------
    
    问题:
         1.原来单词的长度再现困难,是否是我题意理解错了
         2.移位问题
    
    -----------------分割线-----------------''')
    

if __name__ == '__main__':
    main()


加密前的文件:
South African Duo Amis to be First to Row Across Southern Atlantic.
加密后的文件:
UqxtjbslFJ ChuieasLPD FwrcNTivvk ColskFLnbf vqyKPuYdrh dgKXYFNRyA HkusvmITat vqgUXpUcaZ TqzQguyMTO CeuousQbDZ Uqxtjewouq CvoaptndBK 
解密后的文件:
South
African
Duo
Amis
to
be
First
to
Row
Across
Southern
Atlantic
    -----------------分割线-----------------
    
    问题:
         1.原来单词的长度再现困难,是否是我题意理解错了
         2.移位问题
    
    -----------------分割线-----------------

练习七:与本小节任务基本相同,但要求打印回文字符倒三角形。


In [2]:
def plalindrome(line):
    for i in range(len(line)*2,0,-1):
        if i == 1:
            print( line[0] + ' '*(len(line)*2-1))
        elif i%2 == 1:
            print(line[:i//2] + line[i//2] + line[i//2-1::-1] +'  '*(len(line)*2-i) )
        else:
            print(line[:i//2] + line[i//2-1::-1] + ' '*(len(line)*2-i) )

def main():
    text = '赏花归去马如飞'
    plalindrome(text)
    

if __name__ == '__main__':
    main()


赏花归去马如飞飞如马去归花赏
赏花归去马如飞如马去归花赏  
赏花归去马如如马去归花赏  
赏花归去马如马去归花赏      
赏花归去马马去归花赏    
赏花归去马去归花赏          
赏花归去去归花赏      
赏花归去归花赏              
赏花归归花赏        
赏花归花赏                  
赏花花赏          
赏花赏                      
赏赏            
赏