1. 给定一个包含n+1个整数的数组nums,其数字在1到n之间(包含1和n),可知至少存在一个重复的整数,假设只有一个重复的整数,请找出这个重复的数
python
def find_difnumber(ls):
for index in range(0, len(ls)):
for num in range(index + 1, len(ls)):
if ls[index] == ls[num]:
print(f"{ls[index]}这个数字出现了重复")
ls = [1,5,8,6,2,4,1,5,22,13,15,4]
print(ls)
find_difnumber(ls)
2. 找出10000以内能被5或6整除,但不能被两者同时整除的数(函数)
python
def find_number():
for number in range(0, 10000):
if number % 5 == 0 or number % 6 == 0:
if number % 5 != number % 6:
ls.append(number)
print(ls)
ls = []
find_number()
3. 写一个方法,计算列表所有偶数下标元素的和(注意返回值)
python
def count_even():
count = 0
for index in range(0, len(ls)):
if ls[index] % 2 == 0:
count += index
print(count)
ls = [1,2,3,4,5,6,7,8,9,10]
count_even()
4. 【选做】某个人进入如下一个棋盘中,要求从左上角开始走,
最后从右下角出来(要求只能前进,不能后退),
问题:共有多少种走法?
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
python
def count_paths(m, n):
dp = [[0] * n for _ in range(m)]
# 初始化第一行和第一列
for i in range(m):
dp[i][0] = 1
for j in range(n):
dp[0][j] = 1
# 计算其他位置的路径数
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
# 用户输入行数和列数
m = int(input("请输入棋盘的行数:"))
n = int(input("请输入棋盘的列数:"))
total_paths = count_paths(m, n)
print("从左上角到右下角的所有可能路径数为:", total_paths)
5. 【选做】汉诺塔:
python
def hanoi(n, source, target, auxiliary):
global move_count
if n == 1:
move_count += 1
print(u"将圆盘 1 从 {} 移动到 {}".format(source, target))
return
hanoi(n - 1, source, auxiliary, target)
move_count += 1
print(u"将圆盘 {} 从 {} 移动到 {}".format(n, source, target))
hanoi(n - 1, auxiliary, target, source)
# 初始化移动次数为0
move_count = 0
# 测试
num_disks = 4
hanoi(num_disks, 'A', 'C', 'B')
print("总共移动次数:", move_count)
我这里是4层