Home Backend Development Python Tutorial Some small exercises in Python

Some small exercises in Python

Jun 21, 2017 pm 03:22 PM
python Operation practise

# 作 1 :

## Use to use the*dictionary*output directory, you can select the directory to enter , you can go back and exit!

##
<span style="color: #808080; font-style: italic">#conding:utf8<span style="color: #000080; font-weight: bold"><br><br><br>menu = {<span style="color: #008080; font-weight: bold">'北京':{<span style="color: #008080; font-weight: bold">'昌平':{<span style="color: #008080; font-weight: bold">'沙河':{<span style="color: #008080; font-weight: bold">'昌平妇幼',}},<span style="color: #008080; font-weight: bold">'海淀':{<span style="color: #008080; font-weight: bold">'海淀一区':{<span style="color: #008080; font-weight: bold">'海淀二区'},}},}  <span style="color: #808080; font-style: italic">#字典嵌套<br><span style="color: #808080; font-style: italic"><br>current_layer = menu                              <span style="color: #808080; font-style: italic">#利用此变量来记录当前的层的位置<br>pre_menu = []                                     <span style="color: #808080; font-style: italic">#用【】来记录每一层<br><span style="color: #808080; font-style: italic"><br><span style="color: #000080; font-weight: bold">while True:<br><span style="color: #000080; font-weight: bold">for k <span style="color: #000080; font-weight: bold">in current_layer:<br><span style="color: #000080">print (k)<br>    choice = <span style="color: #000080">input(<span style="color: #008080; font-weight: bold">'>>>>>>>:').strip()            <span style="color: #808080; font-style: italic">#去除输入选项连边的空格<br><span style="color: #808080; font-style: italic">    <span style="color: #000080; font-weight: bold">if <span style="color: #000080">len(choice) == <span style="color: #0000ff">0:                          <span style="color: #808080; font-style: italic">#通过len的长度来判断用户是否输入了<br><span style="color: #808080; font-style: italic">        <span style="color: #000080; font-weight: bold">continue<br><span style="color: #000080; font-weight: bold"><br><span style="color: #000080; font-weight: bold">    if choice <span style="color: #000080; font-weight: bold">in current_layer:<br>        pre_menu.append(current_layer)<br>        current_layer = current_layer[choice]<br><span style="color: #000080; font-weight: bold">elif choice == <span style="color: #008080; font-weight: bold">'b':<br><span style="color: #000080; font-weight: bold">if <span style="color: #000080">len(pre_menu) > <span style="color: #0000ff">0:                    <span style="color: #808080; font-style: italic">#通过大于0 来判断,还有目录可退<br><span style="color: #808080; font-style: italic">            current_layer = pre_menu.pop()       <span style="color: #808080; font-style: italic">#利用pop来弹出上面的一层。<br><span style="color: #808080; font-style: italic">    <span style="color: #000080; font-weight: bold">elif choice == <span style="color: #008080; font-weight: bold">'q':<br><span style="color: #000080">exit()</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>
Copy after login
#Assignment 2                                                                                                                     
# A small exercise for list: Implementing the shopping cart function

product_list = [[
Copy after login

Assignment 3                                                      
Small practice with bubble algorithm

a_list = [
Copy after login
Copy after login

Assignment 4                                          ​ Insertion algorithm is small Exercise

Implementation method one:

##

a_list = [
Copy after login
Copy after login

Implementation method two

:##
arr1 = [
Copy after login

做业五                                                                                                          

打印99乘法表

#! /usr/bin/python
# Filename : table_9x9.py
 
print '\n9x9 Table\n'
 
for i in range(1, 10) :
    for j in range(1, i+1) :
        print j, 'x', i, '=', j*i, '\t',
        # print '%d x %d = %d\t' %(j, i, j*i),
    print '\n'
print '\nDone!'
 
 
关于该程序的说明:
1. 第一行是特殊注释行,称为组织行,用来告诉GNU/Linux系统应该使用哪个解释器来执行该程序。
2. 第二行至第四行都是一般的注释行,用来说明一些信息的(如文件名,作者,时间等)。
3. 第六行打印一个字符串。
4. 第八行i取值范围为1, 2, 3, 4, 5, 6, 7, 8, 9
5. 第九行j取值范围为1, 2, ..., i
6. 第十行和第十一行效果一样,最后的逗号都是用来取消自动换行的。
7. 第十二行作用是在每个内层for循环结束后换行,即在输出完九九乘法表一行后换行。
8. 第十四行打印一个字符串。
 
 
小结:通过这个程序熟悉print的用法,for循环的用法,以及range函数的特点。

课堂中提到的方法:

for i in range(1,10):<br>    output = ''<br>    for j in range(1,i+1):<br>        output+= "%s*%s=%2s "%(i,j,i*j)<br>    print output

 

---------------------------------------------------

作业六:                                                                                                       

取一个列表中前两位大的数字

<br>
Copy after login
#!/usr/bin/python<br><br>NumList = [1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,4222,46,33,45,65555]<br><br>max_num = 0<br>sec_num = 0<br><br>for n in NumList:<br>if max_num < n:
sec_num=max_num
#获取最大数之前的比较的哪个数肯定是在这之前第二大的
max_num = n
#但是后面如果再出现比最大的大,比之前比较出料的第二大
#小的数时需要再比较下。
if n < max_num and n > sec_num:<br>            sec_num = n<br><br><br>print ('The bigest NUM is : %s' %(max_num))<br>print ('The second one is : %s' %(sec_num))
Copy after login
 <br>
Copy after login

利用单循环来同事去除两个两个数。

作业七                                                                                                      

二分查找法(利用递归函数)

num_list = [
Copy after login

作业八                                                                                                                

利用函数完成用户的注册登录功能

 

#!/usr/bin/python<br>#encoding: utf-8

import getpass

user_list = {}

def new_user():<br>    username = raw_input('please input your new name:')<br>    if username in user_list:<br>        print '%s is already exits!!' %username<br>    else:<br>        passwd = getpass.getpass()               #已密码不显示的方式输入。<br>        user_list[username] = passwd

def old_user():<br>    username = raw_input('please input your name:')<br>    passwd = raw_input('please input your passwd:')<br>    if username in user_list:<br>        if user_list[username] == passwd:<br>            print 'login successfull!!'<br>        else:<br>            print 'login fail!!'<br>    else:<br>        print 'login fail!!!'

CMD = {'n' : new_user , 'o' : old_user}

def main_menu():<br>    ppp = '''<br>        新用户注册:n<br>        老用户登录:o<br>        推出:q

'''<br>    while True:<br>        try:<br>            choice = raw_input(ppp)<br>        except (KeyboardInterrupt, EOFError):       #捕捉ctrl+ D 的错误输出。<br>            choice = 'q'

if choice not in 'noq':<br>            print 'please input again'<br>            continue<br>        if choice == 'q':<br>            break<br>        CMD[choice]()          #通过取字典的key,选择来执行函数

 

if __name__ == '__main__':<br>    main_menu()

作业九

log日志前十排序,其中包括重复的。利用函数简单的html输出

#!/usr/bin/python
#coding:utf8

def openFile(log):
    with open(log) as f:
        content = f.readlines()
    return content

def countLine(fn):
    content = fn
    count_dict = {}
    for line in content:
        line = line.split(' ')  # string 通过split 转换为list
        local_ip,uri,code = line[0],line[6],line[8]
Copy after login
        #利用元组来作为key,然后统计数量
Copy after login
        count_dict[(local_ip,uri,code)] = count_dict.get((local_ip,uri,code),0) + 1
Copy after login
    #这个排序的功能网上copy的,不了解原理
Copy after login
    count_dict = sorted(count_dict.items() ,key=lambda item:item[1],reverse=True)        
    return count_dict

def detailLine(fn):
    count_dict = fn
    #下面进行重复行计数为一行。
    n = 1                              #取行计数
    num = 0                            #用于判断'统计数量'是否出现一样的
    # print ('-----IP------------------URI----------CODE---count---')
    # for i in count_dict:
    #     if n <= 10:  # 取前十
    #         if i[1] != num:
    #             print(&#39;%-10s%20s%5s%10s   ---->no%s' % (i[0][0], i[0][1], i[0][2], i[1], n))
    #             num = i[1]
    #             n += 1
    #         elif i[1] == num:
    #             print('%-10s%20s%5s%10s' % (i[0][0], i[0][1], i[0][2], i[1]))

    with open('count.html','w') as f:
        res = "<table border=&#39;1&#39;>"
        res += '<tr><td>IP</td><td>URI</td><td>CODE</td><td>COUNT</td></tr>'
        for i in count_dict:
            if n <= 10:
                if i[1] != num:
                    res += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>'% (i[0][0],
                     i[0][1], i[0][2], i[1])
                    num = i[1]
                    n += 1
                elif i[1] == num:
                    res += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (i[0][0], 
                    i[0][1], i[0][2], i[1])
        res +='</table>'
        f.write(res)
def main():
    first = openFile('access.log')
    second = countLine(first)
    detailLine(second)

if __name__ == '__main__':
    main()
Copy after login
作业十,

 生成随机验证码:

方法一:
import string,random

source = string.digits + string.ascio_lowercase
print ("".join(random.sample(source,6)))

方法二:
checkcode = ''
for i in range(6):
    current = random.randrange(0,6)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0-9)
    checkcode += str(temp)
print(checkcode)
Copy after login

 

 
 

 

The above is the detailed content of Some small exercises in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

MiniOpen Centos compatibility MiniOpen Centos compatibility Apr 14, 2025 pm 05:45 PM

MinIO Object Storage: High-performance deployment under CentOS system MinIO is a high-performance, distributed object storage system developed based on the Go language, compatible with AmazonS3. It supports a variety of client languages, including Java, Python, JavaScript, and Go. This article will briefly introduce the installation and compatibility of MinIO on CentOS systems. CentOS version compatibility MinIO has been verified on multiple CentOS versions, including but not limited to: CentOS7.9: Provides a complete installation guide covering cluster configuration, environment preparation, configuration file settings, disk partitioning, and MinI

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to choose the PyTorch version on CentOS How to choose the PyTorch version on CentOS Apr 14, 2025 pm 06:51 PM

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

How to update PyTorch to the latest version on CentOS How to update PyTorch to the latest version on CentOS Apr 14, 2025 pm 06:15 PM

Updating PyTorch to the latest version on CentOS can follow the following steps: Method 1: Updating pip with pip: First make sure your pip is the latest version, because older versions of pip may not be able to properly install the latest version of PyTorch. pipinstall--upgradepip uninstalls old version of PyTorch (if installed): pipuninstalltorchtorchvisiontorchaudio installation latest

See all articles