有一堆硬币,每次只能拿一个或者两个,求最少多少次可以拿完硬币
[10, 8, 5, 3, 27, 99]
"""有一堆硬币,每次只能拿一个或者两个,求最少多少次可以拿完硬币"""
#[10, 8, 5, 3, 27, 99]
s = [10, 8, 5, 3, 27, 99]
num = 0
for i in s:
x = i %2
if x == 0:
num = i // 2 + num
else:
num = i // 2 + num + 1
print(f'需要取{num}次')
如果两个素数之差为2,这样的两个素数就叫作"孪生数",找出100以内的所有"孪生数".
zhi = []
for num in range(2,101):
k = 0
for i in range(2,num):
if num % i == 0:
k = 1
break
if k == 0:
zhi.append(num)
else:
pass
print("100以内的素数有:")
print(zhi)
i = 1
while i < len(zhi):
if zhi[i] - zhi[i - 1] == 2:
print("%d和%d是孪生数"%(zhi[i],zhi[i-1]))
i += 1
给定一个列表,求最大值(不能使用系统api),求最小值,求平均值、求和
a = [1,3,4,6,7,2,10,2,6,9]
print(f"最大值是{max(a)}")
print(f"最小值是{min(a)}")
print(f"和是{sum(a)}")
print(f"平均值是{sum(a)/len(a)}")
a_max = a[0]
a_min = a[0]
a_sum = 0
for i in a:
if i > a_max:
a_max = i
if i < a_min:
a_min = i
a_sum += i
print(f"最大值是:{a_max}最小值是:{a_min}和为:{a_sum}平均值是:{a_sum/len(a)}")
将list中的重复数据去重,至少使用两种方案
a = [1, 1, 2, 4, 5, 11, 2, 2]
c = a
a = set(a)
print(a)
lx = [10, 70, 80, 50, 20, 90, 20, 30, 40, 50, 60, 70, 80, 90, 100]
ly = []
for i in lx:
if i not in ly:
ly.append(i)
print('列表lx去重后的元素为:', ly)
两个列表进行合并操作
a = {1,2,3,4,5,6}
b = {2,3,5,6,7,8,9,10}
print(a.union(b))
a = [5,6,7,8]
b = [10,2,3,4]
for i in b:
a.append(i)
print(a)
使用列表判断一个列表是否在另外一个列表中
a = [1,2,3,4]
b = [1,2,3,4,5,6,7]
for i in a:
if i not in b:
print("a不在列表b中")
break
else:
print("a在列表b中")
break
a = [1,2,5,89,1,0,23]
a.reverse()
print(f"反转后的列表为{a}")
a.sort()
print(f"排序后的列表为{a}")
如何将0-10随机存入列表中
import random
arr = list()
for i in range(20):
a = random.randint(0,10)
arr.append(a)
print(arr)
'''使用一行代码生成一个列表,列表推导式'''
# arr = [i for i in range(20) if i % 2 == 0]
# arr = [i * j for i in range(1,10) for j in range(1,10)]
# print(arr)
存在一个1~n的连续列表,在其中不小心重复了一个值,请找出这个重复值
[1,2,3,4,5]
res = 0
arr = [1,2,3,4,5,5]
for i in range(0,len(arr)):
res ^= i ^ arr[i]
print(res)