Python期末复习
第二章 基本程序设计
eval('3')
eval('3') + eval('4')
eval('abc')
x , y = y ,x
eval('34') == eval('3' + '4')
integer = eval(input('Enter an integer:'))
q = integer // 1000
b = integer // 100 % 10
g = integer % 1000 % 100 // 10
s = integer % 1000 % 100 %10
print(s,g,b,q)
第三章 数字函数,字符串和对象
-
符串和字符 ord('a')
chr(98)
-
对象和方法 n = 3
id(n)
type(n)
s1 = 'HELLO'
s1 = s1.lower()
s1
s2 = 'hello'
s2 = s1.upper()
s2
-
strip():删除字符串两端的空格 s = '\t Welcome \n'
s1 = s.strip()
s1
s = '\t \n\t123e\t12\nsa \t\n\t'
s.strip()
'''\t,\f,\r,\n都属于空格'''
-
object.find(str(被查找字符),beg = 0(开始索引),end(结束索引)).如果找到则返回object中第一次出现str的索引值,否则返回-1 。 -
format() 函数 ‘.2f’ 四舍五入后保留小数点后2位小数 round(0.1532,2)
format(0.125,'.2f')
format(57.467657,'10.2f')
format(12345678.923,'10.2f')
format(57.4,'10.2f')
format(57,'10.2f')
format(57,'.2f')
format('hello! Amber','20s')
format('hello! Amber','<20s')
format('hello! Amber','>20s')
format('hello! Amber!hello! Amber!','>20s')
format(0.456789101112,'9.3%')
format(0.456789101112,'<9.3%')
-
object.split (str=’’,num = string.count(str)) str = 'Line1-abcdef \nLine2-abcdef \nLine3-abcdef'
str.split()
str.split(' ',1)
s = 'apple,peach,banana,pear'
s.split(',',2)
s = 'asda\t as\nsada saa\nasda'
s.split('s')
s.split('\n')
第四章 选择
-
布尔类型、值和表达式
- python用1代表True ;用0代表False
- True是python关键字;一个布尔字面量(对);等同于1(错)
- Python将任何非零和非空值视为True,如果一个对象为0或者为空,那么被视为Flase
-
生成随机数
- random.randint(a,b) 从范围[a,b]中返回一个随机整数,包括a和b
- random.random() 从范围(0,1)中返回一个随机**浮点数****
- randrange(a,b) 从范围[a,b)中返回一个随机整数,包括a但不包括b,与 random.randint(a,b - 1 )相同
- random.sample(object(eg.string,list),number) 多用于截取列表的指定长度的随机数,但不改变列表本身的顺序
random.randint(0,10)
random.random()
random.randrange(0,10)
random.sample(range(1,100),3)
random.sample(range(1,100),4)
-
if i > 0 :
x = 1
y = 1
可以使用任何宽度的空格,但一定要对齐 -
条件表达式 if x > 0:
y = 1
else:
y = -1
y = 1 if x > 0 else -1
if number % 2 == 0:
print(number,'is even.')
else:
print(number,'is odd.')
print(number,'is even.' if number % 2 == 0 else 'is odd.')
第五章 循环
0 % 2 = 0 1 % 2 = 0
-
举例
-
乘法口诀表
print(' Multiplication Table')
print(' '* 2 ,end = ' ')
for i in range(1,10):
print(format(i,'4d'),end = ' ')
print()
print('-' * 4 * 12)
for i in range(1,10):
print(i,end = '| ')
for j in range(1,10):
print(format(i * j,'4d'),end = ' ')
print()
-
嵌套循环 for i in range(1,5):
j = 0
while j < i:
print(j,end = ' ')
j += 1
i = 5
while i >= 1:
num = 1
for j in range(1,i + 1):
print(num,end = 'xxx')
num *= 2
print()
i -= 1
1xxx2xxx4xxx8xxx16xxx
1xxx2xxx4xxx8xxx
1xxx2xxx4xxx
1xxx2xxx
1xxx
for i in range(1,9):
print(' ' * 4 * (8 - i),end = ' ')
for j in range(0,i):
print(format(2 ** j ,'3d'),end = ' ')
for j in range(0,i - 1):
print(format(2 ** (i - j - 1),'3d'),end = ' ')
print()
-
找出最大公约数
n1 = eval(input('Enter first integer:'))
n2 = eval(input('Enter second integer:'))
gcd = 1
k = 2
while k < min(n1,n2):
if n1 % k == 0 and n2 % k == 0:
gck = k
k += 1
print(n1,'和',n2,'的最大公约数是',gck)
n1,n2 = eval(input('Please enter two integer:'))
for i in range(1,min(n1 + 1, n2 + 1)):
if n1 % i == 0 and n2 % i == 0:
a = i
print(n1,'和',n2,'的最大公约数是',a)
-
break 和 continue
-
break帮助退出整个循环 -
continue帮助退出或跳过当前的迭代 sum = 0
number = 0
while number < 20:
number += 1
sum += number
if sum >= 100:
break
print('The number is ',number,'\nThe sum is ',sum)
sum = 0
number = 0
while number < 20:
number += 1
if number == 10 or number == 11:
continue
sum += number
print('The sum is ',sum)
b = 1000
while 1:
if b < 9:
break
b = b - 9
print('b is ',b)
b = 1000
while 1:
if b < 9:
continue
b = b - 9
print('b is ',b)
for i in range(1,4):
for j in range(1,4):
if i * j > 2:
break
print( i * j)
print(i)
1
2
1
2
2
3
for i in range(1,4):
for j in range(1,4):
if i * j > 2:
continue
print( i * j)
print(i)
1
2
1
2
2
3
print('The first 50 prime numbers are')
print()
count = 0
n = 2
while count < 50:
for i in range(2,(n // 2 + 1)):
if n % i == 0:
break
else:
count += 1
print(format(n,'>5d'),end = ' ')
if count % 10 == 0:
print()
n += 1
第六章 对象和类
-
一切事物都是对象,如类,函数等,因此对象并不只是一个类的实例 -
init(self,…) self初始化:创建数据域 -
self可以用其他变量代替,只是习惯上self -
不可变对象和可变对象 -
举例
-
class Count:
def __init__(self,count = 0):
self.count = count
def main():
c = Count()
times = 0
for i in range(100):
increment(c,times)
print('count is ',c.count)
print('times is ',times)
def increment(c,times):
c = Count(times)
times += 1
main()
-
隐藏数据域
- 缺陷:数据肯能会被篡改; 不利于维护
- 定义:__radius 通过2个下划线来定义私有数据域
- 私有数据域和方法仅能在类内部被访问,类外部不能被访问,除非提供一个方法返回它的值
- 类如果只是在程序内使用,而不是被其他程序使用,那么没有必要定义私有数据域
第七章 字符串、列表、集合和字典
-
创建字符串 s = ''
s1 = 'amber'
s = str()
s1 = str('amber')
-
字符串的相关函数 len('\t')
len('\t 12')
-
索引操作符[] index:[0,len(s) - 1] s[-1] = s[-1 + len(s)] -
切片操作符
-
s[start:end]:返回指定索引值从start到end -1的字符切片 s = 'welcome'
s[1:4]
-
默认情况:start = 0,end 为最后一个 s[ :6]
s[4: ]
-
如果 s[i:j]中的索引值i或j为负数,将它替换为len(s)+i或j 如果j > len(s),j默认为len(s) 如果i >= j,那么切片值为空字符 s[1:-1]
s[2:-3]
-
in 和 not in操作符 测试一个字符是否在另一个字符串中 返回布尔值 -
迭代字符串 s = 'welcome'
for ch in s :
print(ch,end = " ")
number = 123456
s = str(number)
for i in range(len(s)):
print(s[len(s) - i -1],end = ' ')
num = ''
for i in range(len(s)):
num = num + s[len(s)- i - 1]
int(num)
-
列表方法 list1 = [2,3,4,2,6,5,3,56]
list1.append(19)
list1.count(3)
list2 = [99,54]
list1.extend(list2)
list1
list1.insert(3,77)
list1.pop(3)
list1.pop()
[2, 3, 4, 2, 6, 5, 3, 56, 19, 99]
list1.remove(56)
list1.reverse()
list1.sort()
a,b = [1,2,3],[99,100]
a.append(b)
a.append('a')
a.append(['b'])
x的范围是1~10,将x中的每个元素值扩大3倍,并存入一个列表中
法1:
list = [ i * 3 for i in range(1,11)]
list
法2:
list2 = []
for i in range(1,11):
list2.append(i * 3)
list2
-
列表解析 a = [x + y for x in 'ab' for y in '123']
a
-
复制列表 list2 = list1
-
这条语句不是将list1中的内容赋给list2,而是将参考对象赋给list2,即他们指向同一个对象 -
a = [1,2,3,4]
b = a
b
a[0] = -1
b
b = a + []
a[0] = -2
a
b
-
举例 ? 易混淆 def main():
list1 = add(1)
print(list1)
list2 = add(2)
print(list2)
list3 = add(3,[11,12,13,14])
print(list3)
list4 = add(4)
print(list4)
main()
[1]
[1, 2]
[11, 12, 13, 14, 3]
[1, 2, 4]
def add(x,lst = None):
if lst == None:
lst = []
if x not in lst:
lst.append(x)
return lst
def main():
list1 = add(1)
print(list1)
list2 = add(2)
print(list2)
list3 = add(3,[11,12,13,14])
print(list3)
list4 = add(4)
print(list4)
main()
[1]
[2]
[11, 12, 13, 14, 3]
[4]
查找列表
def linearSearch(lst,key):
for i in range(len(lst)):
if key == lst[i]:
return i
return -1
lst = [1,2,3,4,5,1,2,3,5]
print(linearSearch(lst,5))
print(linearSearch(lst,9))
def binarySearch(lst,key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (high + low) // 2
if key <lst[mid]:
high = mid - 1
elif key > lst[mid]:
low = mid + 1
else:
return mid
return - low - 1
lst = [1,2,3,4,5,1,2,3,5]
print(binarySearch(lst,5))
print(binarySearch(lst,9))
第八章 多维列表集合和字典numpy
-
打印列表 matrix = [[1,2,3],[4,5,6],[7,8,9]]
法1:
for row in range(len(matrix)):
for colum in range(len(matrix[row])):
print(matrix[row][colum],end = ' ')
print()
法2:
for row in matrix:
for value in row:
print(value,end = ' ')
print()
1 2 3
4 5 6
7 8 9
-
随机打乱顺序,random.shuffle(list)函数只能处理一维列表,不能处理多维列表 import random
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for row in range(len(matrix)):
for column in range(len(matrix[row])):
i = random.randint(0,len(matrix) - 1)
j = random.randint(0,len(matrix[row]) - 1)
matrix[row][column],matrix[i][j] = matrix[i][j], matrix[row][column]
print(matrix)
-
排序 --sort() points = [[4,2],[1,4],[2,5],[6,7],[1,2],[4,1]]
points.sort()
print(points)
-
易混淆 matrix = []
matrix.append(3 * [1])
matrix.append(3 * [1])
matrix.append(3 * [1])
print(matrix)
matrix[0][0] = 2
print(matrix)
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[2, 1, 1], [1, 1, 1], [1, 1, 1]]
matrix = []
matrix.append([3 * [1]])
matrix.append([3 * [1]])
matrix.append([3 * [1]])
print(matrix)
matrix[0] = 3
print(matrix)
[[[1, 1, 1]], [[1, 1, 1]], [[1, 1, 1]]]
[3, [[1, 1, 1]], [[1, 1, 1]]]
-
初始化列表 and 求和
import random
matrix = []
row = eval(input('Enter the row:'))
column = eval(input('Enter the column:'))
for i in range(row):
matrix.append([])
for j in range(column):
value = random.randint(0,99)
matrix[i].append(value)
print(matrix)
def isSum(matrix):
sum = 0
if matrix != None:
for row in matrix:
for value in row:
sum = sum + value
'''
for value in row:
sum = sum + value
也可替换为:
sum = sum + sum(row)
sum()求列表的和
'''
return sum
else:
return False
matrix = [[2, 1, 1], [1, 1, 1], [1, 1, 1]]
print(isSum(matrix))
-
元组 和列表一样,但元素不可变,且元组的效率更高 元组一旦创建,就不能增删,替换元素,也不能改变顺序 注意 tuple([1,2,3]) == (1,2,3); tuple(list1.sort())会报错 t1 = ()
t2 = (1,2,3)
t3 = tuple([2 * x for x in range(3)])
t4 = tuple('abac')
tuple1 = ('a','b','c')
tuple2 = tuple([1,2,3])
tuple3 = tuple1 + tuple2
tuple3
('a','b','c',1,2,3)
tuple1 = tuple([7,8,5,6,1,2,3,4])
list1 = list(tuple1)
list1.sort()
-
集合 集合中没有重复的元素,也没有顺序,如果不考虑顺序的话,用集合比用列表的效率要高 集合无序,没有index方法 初始化
s1 = set()
s2 = {1,2,3}
s3 = set([1,2,3])
s4 = set([x for x in range(5)])
s5 = set('abad')
相关操作
s1 = {1,2,3}
s1.add(5)
len(s1)
max(s1)
sum(s1)
3 in s1
s1.remove(2)
子集与超集
如果s1中所有元素都在s2中,那么s1是s2的子集 s1.issubset(s2)
如果s2中所有元素都在s1中,那么s1是s2的超集 s1.issuperset(s2)
s1 = {1,2,4}
s2 = {1,4,5,2,6}
s1.issubset(s2)
s2.issuperset(s1)
集合操作符
并集
s1 = {1,2,4}
s2 = {1,3,5}
s1.union(s2)
{1,2,3,4,5}
交集
s1.intersection(s2)
{1}
差集
s1.difference(s2)
{2,4}
对称差(异或)
s1.symmetric_difference(s2)
{2, 3, 4, 5}
-
字典 存储键值对集合的容器对象。通过关键字实现快速获取、删除和更新值 字典中的关键字有点像列表中的索引,每个索引对应一个值,关键字不能相同,但其对应值可以相同 key:value key只能是不可变对象,所以列表不能用来做key a = {'1':'a','2':'b'}
a = {}
添加、修改、获取值
students = {'201931990201':'a','201931990202':'b','201931990203':'3'}
students['201931990209'] = 'amber'
students['201931990201'] = 'wenzhou'
print(students['201931990209'])
vegetables = [('celery',1.58),('brocoli',1.29),('lettuce',2.19)]
dict = dict(vegetables)
print(dict)
{'celery': 1.58, 'brocoli': 1.29, 'lettuce': 2.19}
删除与循环条目
a = {'abc':123,'cde':456}
del a ['cde']
print(a)
a = {'abc':123,'cde':456}
for key in a:
print(a[key])
123
456
字典方法
keys()返回关键字序列 tuple
students = {'001':'amber1','002':'amber2','003':'amber3'}
tuple(students.keys())
('001', '002', '003')
values()返回值序列 tuple
tuple(students.values())
('amber1', 'amber2', 'amber3')
tuple(students.items())
(('001', 'amber1'), ('002', 'amber2'), ('003', 'amber3'))
get(key)
print(students.get('001'))
amber1
pop(key)返回值,并删除
print(students.pop('001'))
amber1
删除所有条目
students.clear()
{}
numpy常用生成数组的函数 -->多维数组
-
np.zero() np.empty() np.ones() import numpy as np
x= np.zeros(6)
x
array([0., 0., 0., 0., 0., 0.])
x = np.zeros((2,3))
array([[0., 0., 0.],[0., 0., 0.]])
np.empty((2,3))
array([[0., 0., 0.],[0., 0., 0.]])
np.ones((2,3))
array([[1., 1., 1.],[1., 1., 1.]])
np.ones([2,3])
array([[1., 1., 1.], [1., 1., 1.]])
-
利用arange(a,b,step)函数创建[a,b)之间以step为步长的一维数组
- 默认以0开始步长为1的整数序列
- arrange的参数可以是浮点数
array.shape 返回数组的维数 array.size 返回数组的元素个数 a = np.arange(6)
array([0, 1, 2, 3, 4, 5])
a.shape
(6,)
a.size
6
np.arange(1,10,2)
array([1, 3, 5, 7, 9])
np.arange(1,2,0.2)
array([1. , 1.2, 1.4, 1.6, 1.8])
np.arange(1.2,3.1,0.3)
array([1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3. ])
-
array.reshape(n,m,k)将数组array转换为n* m* k维矩阵 a = np.arange(12)
a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
b = a.reshape(2,3,2)
b
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]])
b = a.reshape(2,3,-1)
b
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]])
第九章 文件操作
-
文件分为二进制文件和文本文件 -
打开文件 fileopen = open(filename,mode)
'r' 为读取打开一个文件
'w' 为写入打开一个文件,如果文件已存在,则销毁
'a' 打开一个文件从文件尾部追加数据
'rb'为读取二进制数据而打开文件
'wb'为写入二进制数据打开文件
fl = open('score.txt','r')
f2 = open(r'C:\Users\LiuYixiu\Desktop\score.txtt','r')
f2 = open('C:\\Users\\LiuYixiu\\Desktop\\score.txt','r')
-
当我们对该目录下已存在的文件进行写操作时,已有的文件数据将会被新的文本覆盖或销毁 测试文件是否存在: import os.path os.path.isfile(‘score.txt’) 存在返回True ,否则False -
读写文件 !!!读取完要关闭 outfile = open('score.txt','w')
outfile.write('Bill Clintor\n')
outfile.write('George Bush\n')
outfile.write('Barack Obama')
outfile.close()
-
从文件中读取所有数据:
-
read():读取剩下所有的数据,以字符串的形式返回 -
readlines():读取剩下所有的数据,以字符串列表的形式返回,这里的字符串是原始数据 -
注意:数据量太大以致于存储器无法存下,read(),readlines()方法都不可行,可以循环利用readline()解决 while line! = ‘’: line = inflie.readline() -
open(‘xxx.txt’,‘a’)打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 def main():
inflie = open('score.txt','r')
print('(1) Using read ():')
print(inflie.read())
inflie.close()
inflie = open('score.txt','r')
print('\n(2) Using read (number):')
s1 = inflie.read(4)
print(s1)
s2 = inflie.read(4)
print(repr(s2))
inflie.close()
inflie = open('score.txt','r')
print('\n(3) Using readline ():')
line1 = inflie.readline()
line2 = inflie.readline()
line3 = inflie.readline()
line4 = inflie.readline()
print(repr(line1))
print(repr(line2))
print(repr(line3))
print(repr(line4))
inflie.close()
inflie = open('score.txt','r')
print('\n(4) Using readlines ():')
print(inflie.readlines())
inflie.close()
main()
'''
(1) Using read ():
Bill Clintor
George Bush
Barack Obama
(2) Using read (number):
Bill
' Cli'
(3) Using readline ():
'Bill Clintor\n'
'George Bush\n'
'Barack Obama'
''
(4) Using readlines ():
['Bill Clintor\n', 'George Bush\n', 'Barack Obama']
'''
from os import path
import os.path
import sys
def main():
f1 = input('Enter a source file:').strip()
f2 = input('Enter a target file:').strip()
if os.path.isfile(f2):
print(f2 + 'already exists')
sys.exit()
infile = open(f1,'r')
outfile = open(f2,'w')
countLines = countChars = 0
for line in infile:
countLines += 1
countChars += len(line)
outfile.write(line)
print(countLines,'lines and',countChars,'chars copied')
infile.close()
outfile.close()
main()
def main():
outfile = open('score.txt','a')
outfile.write('\nhello amber\n')
outfile.close()
main()
from random import randint
def main():
outfile = open('score.txt','w')
for i in range(10):
outfile.write(str(randint(0,9))+' ')
outfile.close()
inflie = open('score.txt','r')
s = inflie.read()
numbers = [eval(x) for x in s.split()]
for number in numbers:
print(number,end = ' ')
inflie.close()
main()
def main():
filename = input('Enter a filename:')
infile = open(filename,'r')
counts = [0] * 26
for line in infile:
countLetters(line.lower(),counts)
for i in range(len(counts)):
if counts[i] != 0:
print(chr(ord('a') + i) + ' appears ' + str(counts[i]) + (' time ' if counts[i] == 1 else ' times'))
infile.close()
def countLetters(line,counts):
for ch in line:
if ch.isalpha():
counts[ord(ch) - ord('a')] += 1
main()
'''
Enter a filename:score.txt
a appears 6 times
b appears 5 times
c appears 12 times
d appears 15 times
f appears 11 times
v appears 14 times
'''
-
从网站上获取数据 打开URL:使用函数urlopen(‘http://hao123.com’) import urllib.request
infile = urllib.request.urlopen('http://www.hao123.com')
print(infile.read().decode())
import urllib.request
def main():
url = input('Enter a URL for a file:')
infile = urllib.request.urlopen(url)
s = infile.read().decode()
counts = countLetters(s.lower())
for i in range(len(counts)):
if counts[i] != 0:
print(chr(ord('a') + i) + ' appears ' + str(counts[i]) + (' time' if counts[i] == 1 else ' times'))
def countLetters(s):
counts = 26 * []
for ch in s:
if ch.isalpha():
counts[ord(ch) - ord('a')] += 1
return counts
main()
第十章 异常处理
def main():
try :
n1 ,n2 = eval(input('Enter two numbers,separated by a comma:'))
result = n1 / n2
print('Result is',result)
except ZeroDivisionError:
print('Division by zero!')
except SyntaxError:
print('A comma may be missing in the input')
except:
print('Something wrong in the input')
else:
print('No exceptions')
finally:
print('The finally clause is executed')
main()
'''
Enter two numbers,separated by a comma:3,4
Result is 0.75
No exceptions
The finally clause is executed
Enter two numbers,separated by a comma:2,0
Division by zero!
The finally clause is executed
Enter two numbers,separated by a comma:2 3
A comma may be missing in the input
The finally clause is executed
Enter two numbers,separated by a comma:a,v
Something wrong in the input
The finally clause is executed
'''
try :
statement1
statement2
except Exception1:
except Exception2:
except Exception3:
finally:
statement4
statement5
'''
若异常未被捕获,那么statement5不会执行,但会执行finally(statement4)
若异常类型是Exception3,那么statement4会执行,statement5也会执行
'''
try:
lst = [0] * 10
x = lst[9]
print('Done')
except IndexError:
print('Index out of bound')
else:
print('Nothing is wrong')
finally:
print('Finally we are here')
print('Coutinue')
'''
Done
Nothing is wrong
Finally we are here
Coutinue
'''
def annonnegative():
a = eval(input('asdsa:'))
if a < 0:
raise RuntimeError('Negative radius')
else:
return a
try:
a1 = annonnegative()
print(a1)
except RuntimeError:
print('Invalid enter value.')
'''
asdsa:-1
Invalid enter value.
asdsa:2
2
'''
实验课
def isMinPrime(n):
i = 2
while True:
if n % i == 0:
print(i,end = ',')
n = n // i
else:
i = i + 1
if n == i:
print(i)
break
isMinPrime(120)
2,2,2,3,5
n = eval(input('Enter 1 ~ 15 :'))
for i in range(1,n + 1):
print(' ' * 4 * (n - i ),end = ' ')
for j in range(1 , i + 1):
print(format(i - j + 1,'3d'),end = ' ')
for j in range(1 , i):
print(format(j+1,'3d'),end = ' ')
print()
for j in range(10000,100001,10000):
e = 1
item = 1
for i in range(1 , j + 1):
item *= i
e += 1/item
print("i = %d 时, e = %.19f"%(j,e))
sum = 0
for i in range(1,50):
sum = ( 2 * i - 1)/(2 * i + 1) + sum
print(sum)
def isPrime(num):
tag = True
for i in range(2,(num // 2 + 1)):
if num % i != 0:
i = i + 1
else:
tag = False
return tag
def isPalindrome(num):
tag = True
s = str(num)
if s[::-1 ] == s[::]:
return True
else:
return False
def print1():
count = 0
k = 2
while count < 100:
if isPalindrome(k) and isPrime(k):
count = count + 1
print(format(k,'6d'),end = ' ')
if count % 10 == 0:
print()
k = k + 1
print1()
def finder(str1,str2):
if str2 in str1:
return True
else:
return False
print(finder('abc','a'))
输入1到100之间的整数,统计出现的次数
a = input('Enter integers between 1 and 100:').split()
counts = []
b = list(set( eval(x) for x in a))
b.sort()
for i in range(len(b)):
item = a.count(str(b[i]))
print(b[i],'occurs ', item ,' time' if item == 1 else 'times')
matrix = []
def sumMajorDiagonal(matrix):
sum = 0
for i in range(len(matrix)):
sum = sum + float(matrix[i][i])
print('Sum of the elements in the major diagonal is',sum)
for i in range(4):
a = input('Enter a 4-by-4 matrix row for row '+str(i)+':').split()
matrix.append(a)
sumMajorDiagonal(matrix)
def main():
matrix1 = []
matrix2 = []
s = input("Enter a 3-by-3 matrix1: ")
items = s.split()
for i in range(3):
list = [eval(items[j]) for j in range(3 * i, 3 * i + 3)]
matrix1.append(list)
s = input("Enter a 3-by-3 matrix2: ")
items = s.split()
for i in range(3):
list = [eval(items[j]) for j in range(3 * i, 3 * i + 3)]
matrix2.append(list)
matrix3 = multiplyMatrix(matrix1, matrix2)
printResult(matrix1, matrix2, matrix3, "*")
def multiplyMatrix(m1, m2):
list = len(m2[0]) * [0]
result = []
for i in range(len(m1)):
result.append([x for x in list])
for i in range(len(result)):
for j in range(len(result[0])):
for k in range(len(m2)):
result[i][j] += m1[i][k] * m2[k][j]
return result
def printResult(m1, m2, m3, op):
for i in range(len(m1)):
for j in range(len(m1[0])):
print(" " + str(m1[i][j]), end = "")
if i == len(m1) // 2:
print( " " + op + " ", end = "")
else:
print( " ", end = "")
for j in range(len(m2[0])):
print(" " + str(m2[i][j]), end = "")
if i == len(m1) // 2:
print(" = ", end = "")
else:
print(" ", end = "")
for j in range(len(m3[0])):
print(" " + str(m3[i][j]), end = "")
print()
main()
'''
Enter a 3-by-3 matrix1: 1 2 3 4 5 6 7 8 9
Enter a 3-by-3 matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
1 2 3 0 2 4 5.300000000000001 23.9 24.0
4 5 6 * 1 4.5 2.2 = 11.600000000000001 56.3 58.2
7 8 9 1.1 4.3 5.2 17.9 88.69999999999999 92.4
'''
filename = input('Enter a filename:')
content = input('Enter the string to be removed:')
infile = open(filename,'r')
for line in infile:
line = line.replace(content,'')
print(line)
infile.close()
'''
Enter a filename:score.txt
Enter the string to be removed:okk
Amber!
good moring!
haha!1
abchsfndvjmfkvmfjvfvjfjivjvjnj!
'''
'''
Enter a filename:score.txt
Enter the string to be removed:1
Amber!
good moring!
haha!okkokk
abchsfndvjmfkvmokkfjvfvjokkfjivjvjnjokk!
'''
def main():
f1 = input("Enter a filename: ").strip()
infile = open(f1, "r")
s = infile.read()
print(str(len(s)) + " characters")
print(str(len(s.split())) + " words")
print(str(len(s.split('\n'))) + " lines")
infile.close()
main()
'''
Enter a filename: score.txt
69 characters
6 words
7 lines
'''
|