day5-20180410笔记

笔记:Python的练习题讲解

一、Python的练习题讲解

1、判断一个字符串数字、字母、空格、其他字符有多少个。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 13:33
# @Author : yangyuanqiang
# @File : 统计字符总数.py

'''
判断一个字符串数字有多少个
字母有多少个
空格有多少个
其他字符

'''



while 1:
    strings = input("Please inpur a string(quit will be exit):")
    alpha, dig, space, other = 0, 0, 0, 0
    if strings.strip() == "quit":
        exit(1)
    for i in strings:
        if i.isdigit():
            dig += 1
        elif i.isspace():
            space += 1
        elif i.isalpha():
            alpha += 1
        else:
            other += 1
    print("alpha = {0}".format(alpha))
    print("dig = {0}".format(dig))
    print("space = {0}".format(space))
    print("other = {0}".format(other))
    print("字符串数字有{0}个,字母有{1}个,空格有{2}个,其他字符有{3}个".format(alpha, dig, space, other))

以上实例输出的结果

Please inpur a string(quit will be exit):abc 123 ^&*% 你好
alpha = 5
dig = 3
space = 3
other = 4
字符串数字有5个,字母有3个,空格有3个,其他字符有4个
Please inpur a string(quit will be exit):quit

解析:

1、使用while循环,通过if判断,输入字符为quit退出,使用strip过滤前和尾的空格。

2、使用for对strings进行循环,通过if判断输入的字符是字符串数字、字母、空格还是其他字符,每循环一次都加1。

3、print打印输出结果。

2、ABCD乘9=DCBA,A=? B=? C=? D=? 答案:a=1,b=0,c=8,d=9 1089*9=9801

方法一:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 13:41
# @Author : yangyuanqiang
# @File : 9801.py


'''

ABCD乘9=DCBA,A=? B=? C=? D=? 答案:a=1,b=0,c=8,d=9      1089*9=9801

'''
import datetime
import time

t1 = time.time()   # 当前时间转换为时间戳
print("版本一启动时间:{0}".format(t1))

# for A in [1]:
for A in range(1,10):
    for B in range(0, 10):
        for C in range(0, 10):
            # for D in [9]:
            for D in range(1,10):
                if ((1000* A + 100*B + 10*C + D)*9 == 1000*D + 100*C + 10*B + A ):
                    print("A = {0}".format(A))
                    print("B = {0}".format(B))
                    print("C = {0}".format(C))
                    print("D = {0}".format(D))
                    print("{0}{1}{2}{3}x9={3}{2}{1}{0}".format(A, B, C, D))
t2 = time.time()   # 当前时间转换为时间戳
print("版本一结束时间:{0}".format(t2))
print("版本一运行效率:{0}".format(t2 - t1))

以上实例输出的结果

版本一启动时间:1523435422.9405403
A = 1
B = 0
C = 8
D = 9
1089x9=9801
版本一结束时间:1523435422.9455407
版本一运行效率:0.00500035285949707

2、ABCD乘9=DCBA,A=? B=? C=? D=? 答案:a=1,b=0,c=8,d=9 1089*9=9801

方法二:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 13:41
# @Author : yangyuanqiang
# @File : 9801.py


'''

ABCD乘9=DCBA,A=? B=? C=? D=? 答案:a=1,b=0,c=8,d=9      1089*9=9801

'''
import datetime
import time

t1 = time.time()   # 当前时间转换为时间戳
print("版本二启动时间:{0}".format(t1))

for A in [1]:
# for A in range(1,10):
    for B in range(0, 10):
        for C in range(0, 10):
            for D in [9]:
            # for D in range(1,10):
                if ((1000* A + 100*B + 10*C + D)*9 == 1000*D + 100*C + 10*B + A ):
                    print("A = {0}".format(A))
                    print("B = {0}".format(B))
                    print("C = {0}".format(C))
                    print("D = {0}".format(D))
                    print("{0}{1}{2}{3}x9={3}{2}{1}{0}".format(A, B, C, D))
t2 = time.time()   # 当前时间转换为时间戳
print("版本二结束时间:{0}".format(t2))
print("版本二运行效率:{0}".format(t2 - t1))

以上实例输出的结果

版本二启动时间:1523435511.9296303
A = 1
B = 0
C = 8
D = 9
1089x9=9801
版本二结束时间:1523435511.9296303
版本二运行效率:0.0

总结:加上时间参数后,进行对比,使用四个for循环比两个for循环运行的效率有相差,肉眼是看不出效果的。

3、九宫格

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 16:38
# @Author : yangyuanqiang
# @File : 九宫格.py


'''

九宫格
1-9
                -------------
                | A | B | C |
                | D | E | F |
                | G | H | I |
                -------------
所有的横竖斜线加起来都等于15
A  1-9
B  1-9 除A
C  1-9 除A,B

'''

number = list()
for i in range(1, 10):
    number.append(i)
print(number)


count = 1
for A in number:
    a = number.copy()
    a.remove(A)
    for B in a:
        b = a.copy()
        b.remove(B)
        for C in b:
            c = b.copy()
            c.remove(C)
            for D in c:
                d = c.copy()
                d.remove(D)
                for E in d:
                    e = d.copy()
                    e.remove(E)
                    for F in e:
                        f = e.copy()
                        f.remove(F)
                        for G in f:
                            g = f.copy()
                            g.remove(G)
                            for H in g:
                                h = g.copy()
                                h.remove(H)
                                for I in h:
                                    if (A+B+C == D+E+F == G+H+I == A+D+G == B+E+H == C+F+I == A+E+I == G+E+C == 15):
                                        print('''
                                        第{9}种例子
                                        -------------
                                        | {0} | {1} | {2} |
                                        | {3} | {4} | {5} |
                                        | {6} | {7} | {8} |
                                        -------------'''.format(A,B,C,D,E,F,G,H,I,count))
                                        count += 1

以上实例输出的结果

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

                                        第1种例子
                                        -------------
                                        | 2 | 7 | 6 |
                                        | 9 | 5 | 1 |
                                        | 4 | 3 | 8 |
                                        -------------

                                        第2种例子
                                        -------------
                                        | 2 | 9 | 4 |
                                        | 7 | 5 | 3 |
                                        | 6 | 1 | 8 |
                                        -------------

                                        第3种例子
                                        -------------
                                        | 4 | 3 | 8 |
                                        | 9 | 5 | 1 |
                                        | 2 | 7 | 6 |
                                        -------------

                                        第4种例子
                                        -------------
                                        | 4 | 9 | 2 |
                                        | 3 | 5 | 7 |
                                        | 8 | 1 | 6 |
                                        -------------

                                        第5种例子
                                        -------------
                                        | 6 | 1 | 8 |
                                        | 7 | 5 | 3 |
                                        | 2 | 9 | 4 |
                                        -------------

                                        第6种例子
                                        -------------
                                        | 6 | 7 | 2 |
                                        | 1 | 5 | 9 |
                                        | 8 | 3 | 4 |
                                        -------------

                                        第7种例子
                                        -------------
                                        | 8 | 1 | 6 |
                                        | 3 | 5 | 7 |
                                        | 4 | 9 | 2 |
                                        -------------

                                        第8种例子
                                        -------------
                                        | 8 | 3 | 4 |
                                        | 1 | 5 | 9 |
                                        | 6 | 7 | 2 |
                                        -------------

4、阶乘

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 17:00
# @Author : yangyuanqiang
# @File : 阶乘.py


'''
0! +1! +2! + 3! +4! + 5! + n!
1 + 1 + 2 + 6 + …… + n*(n-1)*(n-2)……*1

'''

def jc(n):
    result = 1
    if n == 0:
        return result
    else:
        for i in range(1, n+1):
            result *= i
        return result


n = input("Plese inpurt number n:")
count = 0
for i in range(0, int(n)+1):
    count += jc(i)

print("count = {0}".format(count))

以上实例输出的结果

Plese inpurt number n:2
count = 4

5、对100以内的两位数,请使用一个两重循环打印出所有十位数数字比个位数数字小的数,例如,23(2 < 3)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 17:34
# @Author : yangyuanqiang
# @File : test.py

'''

对100以内的两位数,请使用一个两重循环打印出所有十位数数字比个位数数字小的数,例如,23(2 < 3)。

'''

count = 0
for x in [1,2,3,4,5,6,7,8,9]:
    for y in [0,1,2,3,4,5,6,7,8,9]:
        if x < y :
            count += 1
            print("第{0}个数:{1}".format(count, x * 10 + y))
print("十位数数字比个位数数字小的数总数有:{0} 个".format(count))

以上实例输出的结果

第1个数:12
第2个数:13
第3个数:14
第4个数:15
第5个数:16
第6个数:17
第7个数:18
第8个数:19
第9个数:23
第10个数:24
第11个数:25
第12个数:26
第13个数:27
第14个数:28
第15个数:29
第16个数:34
第17个数:35
第18个数:36
第19个数:37
第20个数:38
第21个数:39
第22个数:45
第23个数:46
第24个数:47
第25个数:48
第26个数:49
第27个数:56
第28个数:57
第29个数:58
第30个数:59
第31个数:67
第32个数:68
第33个数:69
第34个数:78
第35个数:79
第36个数:89
十位数数字比个位数数字小的数总数有:36 个

6、利用while True无限循环配合 break 语句,计算 1 + 2 + 4 + 8 + 16 + .....的前20个数的和

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/11 17:15
# @Author : yangyuanqiang
# @File : 前20个数的和.py

'''

利用while True无限循环配合 break 语句,计算 1 + 2 + 4 + 8 + 16 + .....的前20个数的和

'''
# 方法一:
sum = 0
x = 1
n = 1
while 1:
    if x<=20:
        # print(x)
        x += 1
        sum = sum + n
        n *= 2
    else:
        break
print("方法一:{0}".format(sum))

#方法二:
sum1 = 0
a = 1
b = 1
while 1:
    if a>20:
        break
    a += 1
    # print(a)
    sum1 = sum1 + b
    b *= 2
print("方法二:{0}".format(sum1))

以上实例输出的结果

方法一:1048575
方法二:1048575

解析:

1、使用while 1循环,通过if判断a是否小于等于20,如果是执行break终止循环

2、规律每求出一个数都要乘以2

计算从1到1000以内所有能被3或者17整除的数的和并输出

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/13 13:55
# @Author : yangyuanqiang
# @File : test2.py

# 计算从1到1000以内所有能被3或者17整除的数的和并输出

sum = 0
for i in range(1,1001):
    if i%3==0 or i%17==0:
        # print("{0} + {1} = {2}".format(i, sum, sum+i ))
        sum = sum + i
        # print("1到1000以内能被3或者17整除的数:{0}".format(i))
print(sum)

以上实例输出的结果

1到1000以内能被3或者17整除的数总和:186230

7、python的编码

支持中文的编码:utf-8、gbk、gb2312

decode  解码

encode  编码

不写python2代码排头,就会报错,而python3默认就以utf-8编码,所以不存在编码的问题。

s = "哈哈哈"
print s

以上实例输出的结果

File "/root/PycharmProjects/python_atuo/test/code.py", line 3
SyntaxError: Non-ASCII character 'xe7' in file /root/PycharmProjects/python_atuo/test/code.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

这个代码文件被执行时就会出错,就是编码出了问题。python默认将代码文件内容当作ASCII,但是ASCII编码中不存在中文,因此抛出异常。

解决问题之道就是要让python知道文件中使用的是什么编码形式,对于中文,可以用的常见编码有utf-8、gbk和gb2312等。只需要在代码文件的最前端添加如下内容:

# -*- coding: utf-8 -*-

控制台乱码

#!/usr/bin/env python
#_*_coding:utf-8_*_
s = "哈哈"
print s

Pycharm运行程序正常,在控制台运行程序乱码

解决办法:

1、更改头文件的编码格式

#_*_coding:gbk_*_

可以在windows控制台打印出来正常的字体了。

2、#_*_coding:utf-8_*_

s = u"哈哈"

print(s)

print(type(s))  #unicode

m = "哈哈"

print(m)

print(type(m))  #str

说明:文件申明时utf-8的编码,识别"哈哈"以后,以unicode对象的形式存在。如果我们用type查看,存储形式是unicode,python在向控制台输出unicode对象的时候会自动根据输出环境的编码进行转换。如果输出的不是unicode对象而是str类型。则会按昭字符串的编码输出字符串。从而出现utf-8没法在gbk编码的控制台展现

s = "哈哈"

m = s.decode("utf-8")

print(type(m))

print(m)

7、Python编码转换报错

编码

#_*_coding:utf-8

s = "中文"

s.encode("gbk")

报错了,为什么呢?

python转码的过程:

源有编码 -----> unicode编码 -----> 目的编码

python会自动先将s解码为unicode,然后再编码为gbk,因为解码是python自动进行的,我们没有指明解码的方式,python就会使用sys.defaultencoding指明的方式来解码

方法一:

s.decode("utf-8").encode("gbk")

方法二:

import sys

reload(sys)

print(sys.getdefaultencoding())

sys.setdefaultencoding("utf-8")

print(sys.getdefaultencoding())

原文地址:https://www.cnblogs.com/ivan-yang/p/8783346.html