20180806学习日报-第四章列表、元组、字典练习题

第四章列表学习:
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。
举例:

list2 = [1,2,3,4,5,6,7]
list1 = [1,2,8,9,10]
listnew = list1+list2
listnew
[1, 2, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7] #列表组合在一起,不会去重

list3 = list1*4
list3
[1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10]

Python的列表截取与字符串操作类似,均使用切片完成

list3
[1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10]
list3[0] # 取位置为0的值
1
list3[-2] # 取位置为倒数第2个的值
9
list3[2:] # 取位置为2和位置2以后的值
[8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10]
list3[2:2] # 取起始位置为2,终止位置为开区间的2,实际终止位置为1区间的值。位置只能顺着一个方向(由左向右)取值
[] ,所以没有这样的位置存在,值为空
list3[2:5] # 取起始位置为2,终止位置为开区间的5,实际终止位置为4区间的值。
[8, 9, 10]
list3[:-1] # 取除了倒数第一位置的其他的所有的值
[1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9, 10, 1, 2, 8, 9]
list3[-3:-1]
[8, 9]
list3[-3:-5] # 只能由左向右取值
[]
list3[-3:1]
[]

注意一点:
元组是不可变 list。 一旦创建了一个 tuple 就不能以任何方式改变它的对象。
不过可以通过将其改变成list后,改变对象后,再改回元组的方式,实现对元组的改变
举例:

tuple1 = (1,2,3,4)
list5 = list(tuple1)
list5
[1, 2, 3, 4]
list5.append(5)
list5
[1, 2, 3, 4, 5]
tuple1 = tuple(list5)
tuple1
(1, 2, 3, 4, 5)

操作符函数(operator):对象比较、逻辑比较、算术运算和序列操

import operator
operator.add(1,2) #相加
3
operator.sub(1,2) #相减
-1
operator.sub(2,1)
1
operator.truediv(5,5) #除法
1.0
operator.floordiv(5,6) #取整除法
0
operator.floordiv(10,7)
1
operator.mod(10,7) #取模
3
operator.mod(11,7)
4
operator.mul(1,2) #乘法
2
operator.mul(2,3)
6
operator.neg(2) #取负数
-2
operator.neg(3)
-3
operator.pos(-1) #取正数
-1
operator.pos(1)
1
operator.lt(1,2) #小于
True
operator.le(1,1) #小于等于
True
operator.eq(1,1) #等于
True
operator.gt(1,2) #大于
False
operator.ge(1,2) #大于等于
False
operator.gt(1,1)
False
operator.ne(1,2) #不等于
True
operator.ne(1,1)
False

operator.concat(“abc”,”bcd”) #字符串拼接
‘abcbcd’
operator.contains(“abc”,”a”) #包含测试
True
operator.contains(“abc”,”d”)
False
operator.and_(1,1) #按位于
1
operator.and_(1,0)
0
operator.and_(0,0)
0
operator.or_(1,1) #按位或
1
operator.or_(1,0)
1
operator.or_(0,1)
1
operator.or_(0,0)
0
operator.xor(1,1) #按位异或
0
operator.xor(1,0)
1
operator.xor(0,0)
0
operator.xor(0,1)
1
operator.invert(1) #按位取反(取反码再去补码得到)
-2
operator.not_(2) #非运算
False
operator.not_(0)
True
operator.not_([])
True
operator.not_(False)
True
operator.pow(2,3) #指数运算
8
operator.is_(1,2) #识别,a is b
False
operator.is_not(1,2) #识别,a is not b
True
temp = [1,2,3]
operator.setitem(temp,2,5) #索引赋值
temp
[1, 2, 5]
operator.delitem(temp,2) #索引删除
temp
[1, 2]
operator.lshift(1,2) #左移
4
operator.lshift(1,5)
32
operator.lshift(2,1)
4
operator.lshift(3,1)
6
operator.lshift(2,2)
8
operator.lshift(2,3)
16
operator.lshift(1,3)
8
operator.lshift(3,3)
24
operator.rshift(1,1) #右移
0
operator.rshift(1,2)
0
operator.rshift(1,3)
0
operator.rshift(3,1)
1
operator.rshift(2,1)
1
operator.rshift(1,1)
0
operator.rshift(5,2)
1
operator.rshift(5,5)
0
operator.rshift(10,2)
2
temp = [1,2,3,4,5,6]
operator.delitem(temp,slice(2,3)) #切片删除
temp
[1, 2, 4, 5, 6]
operator.getitem(temp,slice(2,3)) #切片取值
[4]
operator.truth(0) #判断真值
False
operator.truth(1)
True

列表中常用的函数:
append(),insert(),pop(),remove(),index(),entend(),reverse(),sort(),count()

按照序列的长度倒序排序
list1 = [(1,5,3),(1,3,6,3),(1,1,2,4,5,6),(1,9)]
def L(tup) :
return len(tup)

list1.sort(key = L,reverse = True)
print(list1)

执行结果:
[(1, 1, 2, 4, 5, 6), (1, 3, 6, 3), (1, 5, 3), (1, 9)]

请大家修改代码实现,使用元组的最后一个元素大小比较来实现 list 的排序
list1 = [(1,5,3),(1,3,6,3),(1,1,2,4,5,6),(1,9)]
def L(tup) :
return tup[-1]

list1.sort(key = L,reverse = True)
print(list1)

执行结果:
[(1, 9), (1, 1, 2, 4, 5, 6), (1, 5, 3), (1, 3, 6, 3)]

列表复制:
引用复制的list,它们的内存地址是相同的,修改任何一个list,另一个list中的元素的值都会被改变

list1 = [1,2,3,4]
list2 = list1
list2
[1, 2, 3, 4]
list2.append(5)
list2
[1, 2, 3, 4, 5]
list1
[1, 2, 3, 4, 5]
id(list1)
19304776
id(list2)
19304776

非引用list,它们的内存地址不一样,所以修改任何一个list都不会影响另一个list

list_a=[1,2,3,4,5]
list_b=list_a[:] #将list_a非引用的复制给list_b
list_b
[1, 2, 3, 4, 5]
id(list_a)
19307256
id(list_b)
19307216
list_a.append(7)
list_a
[1, 2, 3, 4, 5, 7]
list_b
[1, 2, 3, 4, 5]
id(list_a)
19307256
id(list_b)
19307216

列表推导:
二维矩阵的转置

a=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print ([ [j[i] for j in a] for i in [0,1,2]]) #相当于两个for循环,将元列表中每个对象的相同位置的值组成在一起组成[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] 新列表中的单个对象

a=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print ([ [j[i] for j in a] for i in range(3)])
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

a=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
print ([[i[j] for j in [1,2]]for i in a]) #生成的列表只包含原列表中每个对象第一个位置和第二个位置的值,相当于删[[2, 3], [5, 6], [8, 9], [11, 12]] 除二维矩阵的某一列

第四章列表学习:
1.迭代器
通过iter()方法获得了list的迭代器对象,然后就可以通过next()
方法来访问list中的元素了。当容器中没有可访问的元素后,next()方法将会抛出一个
StopIteration异常终止迭代器。

举例:

encoding=utf-8

li=[5,6,7]
it=iter(li)
print (it)
print (next(it))
print (next(it))
print (next(it))
print (next(it))

执行结果:
Traceback (most recent call last):
File “C:/Users/Vivian/Desktop/自动化/jfyan/test”, line 8, in
print (next(it))
StopIteration

5
6
7

迭代器特点:L是一个可迭代的对象。当你使用一个列表生成式来建立一个列表的时候,就建立了一个可迭代的对象。
此时所有的值都存在内存中,所以不适合大量数据

举例2:
L = [x * x for x in range(10)]
print(“L:”,L)
for n in L:
print(n)

执行结果:
L: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
0
1
4
9
16
25
36
49
64
81

2.生成器
如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整
的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器

生成器特点:可迭代,

只能读取一次

实时生成数据,不全存在内存中

举例:
g = (x * x for x in range(10))
print (“g:”,g)
print (“next(g):”,next(g))
print (“next(g):”,next(g))
print (“next(g):”,next(g))
print (“next(g):”,next(g))
for n in g:
print(n)

执行结果:
g:

encoding=utf-8

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(“stack:”,stack)
print(“stack1:”,stack.pop())
print(“stack2:”,stack)
print(“stack3:”,stack.pop())
print(“stack4:”,stack)
print(“stack5:”,stack.pop())
print(“stack6:”,stack)

执行结果:
stack: [3, 4, 5, 6, 7]
stack1: 7
stack2: [3, 4, 5, 6]
stack3: 6
stack4: [3, 4, 5]
stack5: 5
stack6: [3, 4]

7.通过 list 实现队列
举例:
from collections import deque
queue = deque([“Eric”, “John”, “Michael”])
queue.append(“Terry”)
queue.append(“Graham”)
print(“queue:”,queue)
print(queue.popleft()) #队列向左移动
print(queue.popleft())
print(“queue:”,queue)

执行结果:
queue: deque([‘Eric’, ‘John’, ‘Michael’, ‘Terry’, ‘Graham’])
Eric
John
queue: deque([‘Michael’, ‘Terry’, ‘Graham’])

练习题:
练习题1:操作一个list做增删改查操作(写一个图书管理系统)
library = []

def add(book):
if book not in library:
library.append(book)
return book,”添加成功!”,book,”的编号为:”,len(library)
else:
print(book,”在图书馆中已存在!”)
for i in range(len(library)):
if library[i] == book:
return book,”的编号为:”,i+1

def delete(book):
if book in library:
for i in range(len(library)):
if library[i] == book:
del library[i]
return book,”删除成功!”
else:
return book,”不在图书馆中!”

def quary(book):
if book in library:
print(book,”在图书馆中!”)
for i in range(len(library)):
if library[i] == book:
return book,”的编号为:”,i+1
else:
return book,”不在图书馆中!”

def quaryall():
if len(library) == 0:
return “图书馆没有书!”
else:
return “图书馆有这些书:”,library

def update(book,newbook):
if book in library:
if newbook in library:
return “要更换的书”,newbook,”在图书馆中已存在!”
else:
for i in range(len(library)):
if library[i] == book:
library[i] = newbook
return book,”换成”,newbook,”成功!”,newbook,”的编号为:”,i+1
else:
print(book,”不在图书馆中!”)
if newbook in library:
return “要更换的书”,newbook,”在图书馆中已存在!”
else:
library.append(newbook)
return newbook,”添加成功!”,newbook,”的编号为:” ,len(library)

while 1:
command = input(“请输入您的操作:”)
if command not in (‘add’, ‘delete’, ‘quary’, ‘update’,’quaryall’, ‘exit’):
print(“您输入的操作不存在!”)

elif command in ('add', 'delete', 'quary'):
    book = input("请输入要操作的书名:")
    if command == 'add':
        print(add(book))
    elif command == 'delete':
        print(delete(book))
    else:
        print(quary(book))

elif command == 'update':
    book = input("请输入要修改的书名:")
    newbook = input("请输入修改的书名:")
    print(update(book, newbook))

elif command == 'quaryall':

    print(quaryall())

else:
    print("退出图书馆系统!")

执行结果:
C:\Users\admin\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/admin/PycharmProjects/untitled1/test.py
请输入您的操作:math
您输入的操作不存在!
请输入您的操作:math
您输入的操作不存在!
请输入您的操作:quaryall
图书馆没有书!
请输入您的操作:add
请输入要操作的书名:java
(‘java’, ‘添加成功!’, ‘java’, ‘的编号为:’, 1)
请输入您的操作:java
您输入的操作不存在!
请输入您的操作:add
请输入要操作的书名:java
java 在图书馆中已存在!
(‘java’, ‘的编号为:’, 1)
请输入您的操作:add
请输入要操作的书名:math
(‘math’, ‘添加成功!’, ‘math’, ‘的编号为:’, 2)
请输入您的操作:add
请输入要操作的书名:c++
(‘c++’, ‘添加成功!’, ‘c++’, ‘的编号为:’, 3)
请输入您的操作:add
请输入要操作的书名:python
(‘python’, ‘添加成功!’, ‘python’, ‘的编号为:’, 4)
请输入您的操作:add
请输入要操作的书名:english
(‘english’, ‘添加成功!’, ‘english’, ‘的编号为:’, 5)
请输入您的操作:quary
请输入要操作的书名:语文
(‘语文’, ‘不在图书馆中!’)
请输入您的操作:
您输入的操作不存在!
请输入您的操作:quary
请输入要操作的书名:java
java 在图书馆中!
(‘java’, ‘的编号为:’, 1)
请输入您的操作:quaryall
(‘图书馆有这些书:’, [‘java’, ‘math’, ‘c++’, ‘python’, ‘english’])
请输入您的操作:update
请输入要修改的书名:java
请输入修改的书名:math
(‘要更换的书’, ‘math’, ‘在图书馆中已存在!’)
请输入您的操作:update
请输入要修改的书名:java
请输入修改的书名:cobol
(‘java’, ‘换成’, ‘cobol’, ‘成功!’, ‘cobol’, ‘的编号为:’, 1)
请输入您的操作:update
请输入要修改的书名:c##
请输入修改的书名:jsp
c## 不在图书馆中!
(‘jsp’, ‘添加成功!’, ‘jsp’, ‘的编号为:’, 6)
请输入您的操作:update
请输入要修改的书名:asp
请输入修改的书名:asp
asp 不在图书馆中!
(‘asp’, ‘添加成功!’, ‘asp’, ‘的编号为:’, 7)
请输入您的操作:delete
请输入要操作的书名:asp2
(‘asp2’, ‘不在图书馆中!’)
请输入您的操作:quaryall
(‘图书馆有这些书:’, [‘cobol’, ‘math’, ‘c++’, ‘python’, ‘english’, ‘jsp’, ‘asp’])
请输入您的操作:add
请输入要操作的书名:java
(‘java’, ‘添加成功!’, ‘java’, ‘的编号为:’, 8)
请输入您的操作:quaryall
(‘图书馆有这些书:’, [‘cobol’, ‘math’, ‘c++’, ‘python’, ‘english’, ‘jsp’, ‘asp’, ‘java’])
请输入您的操作:delete
请输入要操作的书名:jsp
(‘jsp’, ‘删除成功!’)
请输入您的操作:quaryall
(‘图书馆有这些书:’, [‘cobol’, ‘math’, ‘c++’, ‘python’, ‘english’, ‘asp’, ‘java’])
请输入您的操作:delete
请输入要操作的书名:jsp
(‘jsp’, ‘不在图书馆中!’)
请输入您的操作:quaryall
(‘图书馆有这些书:’, [‘cobol’, ‘math’, ‘c++’, ‘python’, ‘english’, ‘asp’, ‘java’])
请输入您的操作:qyary all
您输入的操作不存在!
请输入您的操作:quary
请输入要操作的书名:jsp
(‘jsp’, ‘不在图书馆中!’)
请输入您的操作:exit
退出图书馆系统!

Process finished with exit code 0

给大家出道题:
给定一个字符串,找出不含有重复字符的最长子串。
示例:
给定”abcabcbb”?,没有重复字符的最长子串是?”abc”?。
给定”bbbbb”?,最长的子串就是?”b”?。
给定”pwwkew”?,最长子串是?”wke”?。请注意答案必须是一个子串,”pwke”?是?子序列??而不是子串。

s = “ppppppabcpwekwkwkefghk”
t = “”
result = []
for i in range(len(s)):
t = s[i]
for j in range(i+1,len(s)):
if s[j] not in t:
t+=s[j]
else:
break
result.append(t)
result.sort(key=len,reverse=True)
print(result[0])

执行结果:
[‘p’, ‘p’, ‘p’, ‘p’, ‘p’, ‘pabc’, ‘abcpwek’, ‘bcpwek’, ‘cpwek’, ‘pwek’, ‘wek’, ‘ekw’, ‘kw’, ‘wk’, ‘kw’, ‘wkefgh’, ‘kefgh’, ‘efghk’, ‘fghk’, ‘ghk’, ‘hk’, ‘k’]
abcpwek

第二种:
s = “ppppppabcpwekwkwkefghk”
t = “”
result = [s[0]]
for i in range(len(s)):
t = s[i]
for j in range(i+1,len(s)):
if s[j] not in t:
t+=s[j]
else:
break
if len(t) > len(result[0]):
result[0] = t
print(result)

执行结果:
[‘abcpwek’]

第四章列表练习题目:
练习题2:完成引用复制和非引用复制的一个例子

list1 = [‘a’,’b’,’c’,’d’,[1,2,3,4]]
list2 = list1
list3 = list1[:]

list1.append(1)
list1[4].append(5)
print(list2)
print(list3)

执行结果:
[‘a’, ‘b’, ‘c’, ‘d’, [1, 2, 3, 4, 5], 1]
[‘a’, ‘b’, ‘c’, ‘d’, [1, 2, 3, 4, 5]]

练习题3:找到两个列表中不同的元素和相同元素
list1 = [‘a’,1,’b’,2,3,4,5,6]
list2 = [‘a’,4,5,6,’c’,’d’]
same_list = []
diff_list = []

for i in list1:
if i in list2:
same_list.append(i)
else:
diff_list.append(i)
for j in list2:
if j not in same_list:
diff_list.append(j)

print(“相同元素列表为:”,same_list)
print(“不同元素列表为:”,diff_list)

执行结果:
相同元素列表为: [‘a’, 4, 5, 6]
不同元素列表为: [1, ‘b’, 2, 3, ‘c’, ‘d’]

练习题4:数字和字母混合的list中,奇数位元素加1,偶数位加2
list1 = [‘a’,1,’b’,2,3,4,5,6,’d’,’k’]
for i in range(len(list1)):
if i%2 == 0:
if isinstance(list1[i],int):
list1[i] = list1[i]+2
else:
list1[i] = chr(ord(list1[i])+2)
else:
if isinstance(list1[i],int):
list1[i] = list1[i]+1
else:
list1[i] = chr(ord(list1[i])+1)
print(list1)

执行结果:
[‘c’, 2, ‘d’, 3, 5, 5, 7, 7, ‘f’, ‘l’]
练习题5:递归处理嵌套的list
list1 = [‘java’,’python’,[1,2,3,4,5,[‘a’,’b’,’c’],6],’c’,6]
result = []
for i in list1:
if isinstance(i,list):
for j in i:
if isinstance(j,list):
for k in j:
result.append(k)
else:
result.append(j)
else:
result.append(i)
print(result)

执行结果:
[‘java’, ‘python’, 1, 2, 3, 4, 5, ‘a’, ‘b’, ‘c’, 6, ‘c’, 6]

练习题6: 遍历list,但是list中元素的数据类型不定,有可能有嵌套的list,嵌套的tuple,dict等。(没有多重嵌套)
list1 = [{“name”:”vivian”,”age”:18},[[3.4j,[“this”,”is”,”the”,”list”],(1,2,”adf”)],3,4],’a’,’b’,(‘a’,”cc”,’d’),1,{“name”:”tenni”,1:2}]
result = []

for i in list1:
if isinstance(i,list) or isinstance(i,tuple):
for j in i:
if isinstance(j,list) or isinstance(i,tuple):
for k in j:
if isinstance(k,list) or isinstance(k,tuple):
for l in k:
result.append(l)
else:
result.append(k)
else:
result.append(j)

elif isinstance(i,dict):
    for m in i.items():
        result.append(m)
else:
    result.append(i)

print(result)

执行结果:
[(‘name’, ‘vivian’), (‘age’, 18), 3.4j, ‘this’, ‘is’, ‘the’, ‘list’, 1, 2, ‘adf’, 3, 4, ‘a’, ‘b’, ‘a’, ‘c’, ‘c’, ‘d’, 1, (‘name’, ‘tenni’), (1, 2)]

练习题7: 通过遍历list去掉重复部分
list1 = [‘a’,’b’,’c’,’d’,’a’,’b’,’c’,’d’,1,1,2,4,5,4,6]
result = []
for i in list1:
if i not in result:
result.append(i)

print(result)

执行结果:
[‘a’, ‘b’, ‘c’, ‘d’, 1, 2, 4, 5, 6]

练习题8:1个纯数字的list中,分别输出奇数坐标数字或偶数坐标数字

def getnumber(list1):
oddlocation_number =[]
enevlocation_number =[]
if isinstance(list1,list):
for i in range(len(list1)):
if i%2 == 0:
enevlocation_number.append(list1[i])
else:
oddlocation_number.append(list1[i])
return “oddlocation_number:”,oddlocation_number,”enevlocation_number:”,enevlocation_number
else:
return “输入的参数不是列表”

list1 = [5,6,10,23,54,56,78,100,1,1,2,4,5,4,6]
list2 = (5,6,10,23,54,56,78,100,1,1,2,4,5,4,6)
print(getnumber(list1))
print(getnumber(list2))

执行结果:
(‘oddlocation_number:’, [6, 23, 56, 100, 1, 4, 4], ‘enevlocation_number:’, [5, 10, 54, 78, 1, 2, 5, 6])
输入的参数不是列表

练习题9:找到序列中最大的元素,自己写算法实现,不能用现有函数
def getMaxelement(list1):
if isinstance(list1,list):
if list1:
maxelement = list1[0]
for i in list1:
if isinstance(i,int):
if isinstance(maxelement,int):
if i > maxelement:
maxelement = i
else:
if ord(str(i)) > ord(maxelement):
maxelement = i
else:
if isinstance(maxelement,int):
maxelement = i
else:
if ord(i) > ord(maxelement):
maxelement = i

        return maxelement
    else:
        return "列表不能为空"
else:
    return "输入的参数不是列表"

list1 = [5,6,10,23,54,56,78,100,1,1,2,4,5,4,6]
list2 = [5,6,7,10,’a’,’d’,’c’,’b’]
list3 = []
list4 = ”
print(getMaxelement(list1))
print(getMaxelement(list2))
print(getMaxelement(list3))
print(getMaxelement(list4))

执行结果:
100
d
列表不能为空
输入的参数不是列表

练习题10:返回列表中第二大元素
list1 = [5,6,7,10,10,12,13,100]
result = sorted(list1,reverse=True)
print(result[1])

执行结果:
13

练习题11:键盘读入一字符串,逆序输出
s = input(“请输入了一个字符串:”)
result = s[::-1]
print(result)

执行结果:
请输入了一个字符串:hlakjlsk989p899-89pp31njr95859
95859rjn13pp98-998p989ksljkalh

1.求10以内所有数字平方之和
代码:
sum = 0
for i in range(11):
sum += i*i
print(“10以内所有数字平方之和为:%d”%sum)

执行结果:
10以内所有数字平方之和为:385

2.输出10行内容,每行的内容都是第一行10个行,第二行9个,第三行8个。。。。最后一行1个星

for i in range(10):
print((10-i)“)

执行结果:









**
*

3.输出9行内容,第1行输出1,第2行输出12,第3行输出123,以此类推,第9行输出123456789

for i in range(1,10):
for j in range(1,i+1):
if j == i:
print(j)
else:
print(j,end=”“)

执行结果:
1
12
123
1234
12345
123456
1234567
12345678
123456789

4.计算2的20次方。不允许用**和pow()

result = 1
for i in range(1,21):
result *= 2

print(“2的20次方为:%d”%result)

执行结果:
2的20次方为:1048576

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

result = 0
for i in range(1,1001):
if i%3 == 0 or i%17 == 0:
result += i

print(“从1到1000以内所有能被3或者17整除的数的和:%d”%result)

执行结果:
从1到1000以内所有能被3或者17整除的数的和:186230

6.计算从1到1000以内所有能同时被3,5和7整除的数的和并输出

sum = 0
for i in range(1,1001):
if i%3 == 0 and i%5 == 0 and i%7 ==0:
sum += i
print(“从1到1000以内所有能同时被3,5和7整除的数的和:%d”%sum)

执行结果:
从1到1000以内所有能同时被3,5和7整除的数的和:4725

7.计算1到100以内能被7或者3整除但不能同时被这两者整除的数的个数

result = []
for i in range(1,101):
if (i%7 == 0 and i%3 !=0) or (i%3 == 0 and i%7 !=0):
result.append(i)
print(“1到100以内能被7或者3整除但不能同时被这两者整除的数为%s,个数为:%d”%(result,len(result)))

执行结果:
1到100以内能被7或者3整除但不能同时被这两者整除的数为[3, 6, 7, 9, 12, 14, 15, 18, 24, 27, 28, 30, 33, 35, 36, 39, 45, 48, 49, 51, 54, 56, 57, 60, 66, 69, 70, 72, 75, 77, 78, 81, 87, 90, 91, 93, 96, 98, 99],个数为:39

8.计算1到100以内能被7整除但不是偶数的数的个数。

result = []
for i in range(1,101):
if i%7 == 0 and i%2 !=0:
result.append(i)
print(“1到100以内能被7整除但不是偶数的数%s,个数为:%d”%(result,len(result)))

执行结果:
1到100以内能被7整除但不是偶数的数[7, 21, 35, 49, 63, 77, 91],个数为:7

9.计算从1到100临近两个整数的合并依次输出。比如第一次输出3(1+2),第二次输出5(2+3),最后一次输出199

result = []
for i in range(1,100):
a = i+(i+1)
result.append(a)

print(result)

执行结果:
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199]

10.给定一个整数n,判断是否是质数(质数是只能被1和它自身整除的数)

import math

def isprime(num):
if not isinstance(num,int):
print(“请输入整数!”,end=”)
return False
if num == 1:
return False
else:
for i in range(2,int(math.sqrt(num))+1):
if num%i == 0:
return False
return True

print(isprime(1))
print(isprime(2))
print(isprime(10))
print(isprime(97))
print(isprime(11))
print(isprime(‘11’))
print(isprime(‘a’))

执行结果:
False
True
False
True
True
请输入整数!False
请输入整数!False

11.给定一个n位(不超过10)的整数,将该数按位逆置,例如给定12345变成54321,12320变成02321.

第一种:

def Reverse_num(num):
reverse_num = []
if not isinstance(num,int):
print(“请输入整数!”,end=”)
return False
else:
for i in range(len(str(num))):
reverse_num.insert(0,str(num)[i])
return ”.join(reverse_num)

print(Reverse_num(1))
print(Reverse_num(12345))
print(Reverse_num(123457))
print(Reverse_num(‘a%’))
print(Reverse_num(‘12345’))

执行结果:
1
54321
754321
请输入整数!False
请输入整数!False

第二种:
def Reverse_num(num):
if not isinstance(num,int):
return False
else:
return int(str(num)[::-1])

print(Reverse_num(1))
print(Reverse_num(12345))
print(Reverse_num(123457))
print(Reverse_num(‘a%’))
print(Reverse_num(‘12345’))

执行结果:
1
54321
754321
False
False

12.某电信公司的市内通话费计算标准如下:三分钟内0.2元,三分钟后每增加一分钟增加0.1元,不足一分钟的按一分钟计算。要求编写程序,给定一个通话时间(单位:秒)计算出应收费金额。
import math
def communications_expense(times):
if not isinstance(times,(float,int)):
return False
elif times <= 3:
return 0.2
else:
return 0.2+math.ceil((times-3))*0.1

print(communications_expense(1))
print(communications_expense(1.5))
print(communications_expense(3))
print(communications_expense(3.00001))
print(communications_expense(5.25))
print(communications_expense(5))
print(communications_expense(‘5’))

执行结果:
0.2
0.2
0.2
0.30000000000000004
0.5
0.4
False

注意:为啥0.1+0.2 = 0.30000000000000004 ?
由于内部,电脑使用的格式(二进制浮点)不能准确地重新present一个像0.1,0.2或0.3的.当code编译或间preTED,你的“0.1”已经四舍五入到该格式的最接近的数字,甚至计算发生之前导致小的舍入误差。

改进方法:
import math
def communications_expense(times):
if not isinstance(times,(int,float)):
return False
elif times <= 3:
return 0.2
else:
return (0.2*10+math.ceil((times-3))*0.1*10)/10

print(communications_expense(1))
print(communications_expense(1.5))
print(communications_expense(3))
print(communications_expense(3.00001))
print(communications_expense(5.25))
print(communications_expense(5))
print(communications_expense(‘5’))

执行结果:
0.2
0.2
0.2
0.3
0.5
0.4
False

1 统计一句话有多少个字母
sentence = input(“please enter one sentence:”)
count = 0
for i in sentence:
if i.isalpha():
count += 1
print(count)

执行结果:
please enter one sentence:this is a boy ! 12345
10

2 统计一句话的共出现过多少个不重复的字母。不能用set方法。
sentence = input(“please enter one sentence:”)
result = []
for i in sentence:
if i.isalpha():
if i not in result:
result.append(i)
print(len(result))

执行结果:
please enter one sentence:this is boy ,he is 2 old!2009-8809888 iiii
10

3 统计出现的每个字母个数

sentence = input(“please enter one sentence:”)
result = []
for i in sentence:
if i.isalpha():
if i not in result:
result.append(i)

for j in result:
print(j,sentence.count(j)

执行结果:
please enter one sentence:this is boy ,he is 2 old!2009-8809888 iiii
t 1
h 2
i 7
s 3
b 1
o 2
y 1
e 1
l 1
d 1

4 将一句话的单词进行反转显示。

sentence = input(“please enter one sentence:”)
result = sentence[::-1]
print(result)

执行结果:
please enter one sentence:this is a boy
yob a si siht

5 将一句话的每个单词,进行反转显示
sentence = input(“please enter one sentence:”)
result = ’ ‘.join(sentence.split()[::-1])
print(result)

执行结果:
please enter one sentence:this is boy
boy is this

6 讲一句话的每个单词反转,将每个单词的字母进行反转显示
sentence = input(“please enter one sentence:”)
result = ’ ‘.join(sentence.split()[::-1])
result = result[::-1]
print(result)

执行结果:
please enter one sentence:this is a boy
siht si a yob

7 统计一句话有多少个单词
sentence = input(“please enter one sentence:”)
for i in sentence:
if i.isalpha()== False:
sentence.replace(i,” “)
result= sentence.split()
print(len(result))
7 统计一句话有多少个单词
8 统计每个单词出现的次数
9 统计一句话中不重复出现的单词数量。不能用set方法。
sentence = input(“please enter one sentence:”)
not_alpha = []
letter_not_repeat_num = 0
for i in sentence:
if i.isalpha() == False:
not_alpha.append(i)

for j in not_alpha:
sentence_new = sentence.replace(j,” “)
sentence = sentence_new

result = sentence_new.split()

for k in result:
print(k,result.count(k))
if result.count(k) == 1:
letter_not_repeat_num += 1

print(“一句话中不重复出现的单词数量为%d”%letter_not_repeat_num)

执行结果:
please enter one sentence:this is a boy ,boy boy, this is a girl,a,a,a,man,&&*())()__
this 2
is 2
a 5
boy 3
boy 3
boy 3
this 2
is 2
a 5
girl 1
a 5
a 5
a 5
man 1
一句话中不重复出现的单词数量为2

10.输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数,面试概率极高的题目

sentence = input(“please enter one sentence:”)
result =[]
letter_count = 0
number_count = 0
space_count = 0
other_count = 0
for i in sentence:
if i.isalpha() == True:
letter_count += 1
elif i.isdigit() == True:
number_count += 1
elif i == ’ ‘:
space_count += 1
else:
other_count +=1

print(“英文字母个数为:%d”%letter_count)
print(“数字个数为:%d”%number_count)
print(“空格个数为:%d”%space_count)
print(“其它字符个数为:%d”%other_count)

执行结果:
please enter one sentence:this is a man,123*** *
英文字母个数为:10
数字个数为:3
空格个数为:4
其它字符个数为:5

输入任意数输出任意数形成的方阵
n = int(input(“输入任意一个数:”))
for i in range(n):
for j in range(n):
if j

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值