西工大–人工智能程序设计noj–前60道
前言
截止到2022.12.10,本课程的noj61——90道,由于需要用到numpy、pandas、scipy等库,系统暂时没有这些库,无法评判,所以暂且分享一下前60道。前60道都已经AC(AC的截图我放在最后了)。有些题我小题大做了,程序写的很复杂,比如前10道;另外有些题的代码写的不太好,最近考试要紧,以后有时间再优化吧。如果有问题或者需要改进的地方,欢迎大家提供意见批评指正。
此文章仅供学习交流参考。本人也是初学python不久。
ps:前几道题没有截图,后面的都有。and图片有点大emm
1.Hello World
print("Hello World")
2.整数运算
a = int(input())
b = int(input())
c = input()
if (c == '+'):
print("%d+%d=%d" % (a, b, a+b))
elif (c == '-'):
# print("{}{}{}={}".format(a, c, b, a-b))
print("%d-%d=%d" % (a, b, a-b))
elif (c == '*'):
# print("{}{}{}={}".format(a, c, b, a*b))
print("%d*%d=%d" % (a, b, a*b))
elif (c == '/'):
if (b == 0):
print("ERROR")
else:
# print("{}{}{}={}".format(a, c, b, a/b))
print("%d/%d=%f" % (a, b, a/b))
elif (c == '//'):
if (b == 0):
print("ERROR")
else:
# print("{}{}{}={}".format(a, c, b, a//b))
print("%d//%d=%d" % (a, b, a//b))
elif (c == '%'):
if b == 0:
print("ERROR")
# print("{}{}{}={}".format(a, c, b, a % b))
else:
print("%d%%%d=%d" % (a, b, a % b))
elif (c == '**'):
if a==0 and b == 0:
print("ERROR")
else:
# print("{}{}{}={}".format(a, c, b, a**b))
print("%d**%d=%d" % (a, b, a**b))
else:
print("ERROR")
3.动态宽度
a = int(input())
b = int(input())
m = ''
while a > 0:
m += str(a % 2)
a = a//2
if len(m) > b:
print(m[len(m)-b-1:-1])
else:
for i in range(b-len(m)):
print("0", end="")
print(m[::-1])
4.二进制,八进制和十六进制
b = input()
d = input()
o = input()
h = input()
hhh = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
'9': 9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
h_list = ['0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
bb = 0
dd = 0
oo = 0
hh = 0
for i in range(len(b)):
bb += int(b[i]) * 2 ** (len(b)-i-1)
for i in range(len(d)):
dd += int(d[i]) * 8 ** (len(d)-i-1)
oo = int(o)
for i in range(len(h)):
hh += hhh[h[i]] * 16 ** (len(h)-i-1)
# print(bb,dd,oo,hh)
max_number = max(bb, dd, oo, hh)
# print(max_number)
a = max_number
m = ''
while a > 0:
m += str(a % 2)
a = a//2
print("0b"+m[::-1], end=",")
a = max_number
m = ''
while a > 0:
m += str(a % 8)
a = a//8
print("0o"+m[::-1], end=",")
print(max_number, end=",")
a = max_number
m = ''
while a > 0:
m += h_list[a % 16]
a = a//16
print("0x"+m[::-1])
5.回文数
这题我之前在别的地方写过,不过要求更多,这里就直接拿过来用了
def dp(sstr):
lenth = len(sstr)
l, r = 0, 0
dp = [[False] * lenth for i in range(lenth)]
for i in range(lenth - 1, -1, -1):
for j in range(i, lenth):
if sstr[i] == sstr[j]:
if j - i <= 1:
dp[i][j] = True
elif dp[i+1][j-1]:
dp[i][j] = True
if dp[i][j] and j - i > r - l:
l, r = i, j
return sstr[l:r+1]
if __name__ == '__main__':
num=int(input())
str1=[]
for i in range(num):
str=input()
str1.append(str)
if num != 0:
for i in range(num-1):
if len(str1[i]) == len(dp(str1[i])):
print("True",end=",")
else: print("False",end=",")
if len(str1[-1]) == len(dp(str1[-1])):
print("True")
else: print("False")
6.加密
a = int(input())
b = int(input())
c = int(input())
a = (a+b) % c
a = str(a)
if len(a) >= 4:
for i in range(4):
print(a[-i-1],end="")
else:
print(a[::-1],end="")
for i in range(4-len(a)):
print("0",end="")
7.字符串处理
import sys
n = int(input())
slist = []
min_length = 10000
same_length = 0
for i in range(n):
strlist = input()
if (len(strlist) < min_length):
min_length = len(strlist)
slist.append(strlist)
if n != 0 and n!=1:
for i in range(min_length):
s = slist[0][i]
same_length = i+1
for j in range(n):
if (slist[j][i] == s):
continue
else:
same_length = i
if same_length == 0:
print("None")
sys.exit()
else:
for i in range(same_length):
print(slist[0][i], end="")
sys.exit()
for i in range(same_length):
print(slist[0][i], end="")
elif n == 1:
print(slist[0])
else:
print("None")
8.复数的和差积商
c1=complex(input())
c2=complex(input())
print(c1+c2,end=",")
print(c1-c2,end=",")
print(c1*c2,end=",")
print(c1/c2,end=",")
print(c1.conjugate(),end=",")
print(abs(c1))
复盘:
这题我考虑复杂了,没想到python提供了复数类型complex
,在知道提供了complex类型后,我还想要自己实现共轭和模,本来是想找到实部和虚部,然后输出self.x2+self.y2,然后再用cmath.sqrt()方法取根号,结果取完根号它输出的并不是一个数(形式),而是复数的形式,比如3+4j的模是5,这样输出的结果并不是5而是5+0j,这样一种复数形式。查找资料后找到原因:
在网上找到了complex的源码:
# 用类实现复数的运算
class Complex: # 定义Complex类
def __init__(self, x, y):
self.x = x
self.y = y
# 定义方法 加 ,可用魔法方法__add__()
def __add__(self, other):
return Complex(self.x + other.x, self.y + other.y) # 返回两个值的相加结果
# 定义方法 减 ,可用魔法方法__sub__()
def __sub__(self, other):
return Complex(self.x - other.x, self.y - other.y) # 返回两个值的相减结果
# 定义方法 乘 ,可用魔法方法__mul__()
def __mul__(self, other):
return Complex(self.x * other.x - self.y * other.y, other.x * self.y + self.x * other.y) # 返回两个值的复数相乘结果
# 定义方法 除 ,可用魔法方法__truediv__()
def __truediv__(self, other):
return Complex((self.x * other.x + self.y * other.y) / (other.x * other.x + other.y * other.y),
(other.x * self.y - self.x * other.y) / (other.x * other.x + other.y * other.y)) # 返回两个值的复数相除结果
def __str__(self):
return "%d + %di" % (self.x, self.y)
c1 = Complex(2, 4) # 2 + 4i,传入实部2,虚部4
c2 = Complex(3, 1) # 3 + i,传入实部3,虚部1
c3 = c1 + c2 # 将相加结果赋值给c3 ,这里由于加号,自动触动上面的魔法方法add,下同
c4 = c1 - c2 # 将相减结果赋值给c4
c5 = c1 * c2 # 将相乘结果赋值给c5
c6 = c1 / c2 # 将相除结果赋值给c6
print(c3)
print(c4)
print(c5)
print(c6)
重点在于25行的
def str(self):
return “%d + %di” % (self.x, self.y)
魔术方法,意思是所有类输出的结果的形式都要类似于这样"%d + %di"。
9.all-any
num=int(input())
a=[]
flag=0
for i in range(num):
if flag==0:
flag+=1
else:
print(",",end="")
a=bin(int(input()))
b=list(a[2:])
for i in range(len(b)):
b[i]=int(b[i])
print(all(b),end="")
10.罗马数字
num=int(input())
flag=0
dist = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
for i in range(num):
if flag==0:
flag+=1
else:
print(",",end="")
st=input()
result=0
for j in range(len(st)):
if j>0 and dist[st[j-1]] < dist[st[j]]:
result=result+dist[st[j]]-2*dist[st[j-1]]
else:
result+=dist[st[j]]
print(result,end="")
这题啥波一了,最后每次输出多了一个换行,忘记end=""
了。。。。写了一个多小时。
11.搜索插入位置
num_list=input().split(",")
look_for=input()
if look_for in num_list:
print(num_list.index(look_for))
else:
for i in range(len(num_list)):
if look_for > num_list[i]:
continue
else:
print(i)
break
12.重复数字
test_list=input().split(",")
for i in range(len(test_list)):
test_list[i]=int(test_list[i])
data_dict={}
for i in test_list:
if i not in data_dict.keys():
data_dict[i]=1
else:
data_dict[i]+=1
# print(dict(sorted(data_dict.items(),key=lambda x: -x[1])))
print(dict(sorted(data_dict.items())))
这题学到的东西还是比较多的。
注释的那一行是按照values降序排序
参考一个很好的博客:http://t.csdn.cn/btqpV
13.百分制成绩转换五分制
score=int(input())
if score>100:
print("data error!")
elif score>=90:
print("A")
elif score>=80:
print("B")
elif score>=70:
print("C")
elif score>=60:
print("D")
elif score>=0:
print("E")
else:
print("data error!")
这题写错了就把手剁了吧。
14.三角函数的使用
import math
x=int(input())
y=math.radians(x)
z=math.sin(y)+math.cos(y)-math.tan(y/4)*math.tan(y/4)
print("%.4f"%y)
print("%.4f"%z)
15.类型转换
def isfloat(str):
s=str.split(".")
if len(s)>2:
return False
else:
for i in s:
if not i.isdigit():
return False
return True
def str2float(str):
s=str.split(".")
return int(s[0])+int(s[1])/(10**len(s[1]))
num=0
num_str_list=input().split()
for i in range(len(num_str_list)):
if num_str_list[i].isdigit():
num_str_list[i]=int(num_str_list[i])
num+=num_str_list[i]
elif isfloat(num_str_list[i]):
num_str_list[i]=str2float(num_str_list[i])
num+=num_str_list[i]
print(num_str_list)
print(num)
16.反转元组
tuple1=tuple(int(i) for i in input().split())
tuple2=tuple(sorted(tuple1,reverse=True))
tuple3=tuple(i+j for i,j in zip(tuple1,tuple2))
print(tuple3)
17.水仙花数
for i in range(100,1000):
if (i//100)**3+(i//10%10)**3+(i%10)**3 == i:
print(i)
18.今年多少天
year = int(input())
if year % 400 == 0:
print("366")
elif year % 100 == 0:
print("365")
elif year % 4 == 0:
print("366")
else:
print("365")
19.用内置函数操作列表
data_list=list(map(int,input().split()))
print(len(data_list),max(data_list),min(data_list),sum(data_list),sep=",")
dl=sorted([abs(i) for i in data_list])
print(dl)
20. 1-10的立方
a=[i**3 for i in range(1,11)]
print(a)
21.解方程
import math
num=int(input())
start=0
end=num
middle=(start+end)/2
while abs(middle-math.sqrt(num))>=0.0001:
if middle**2>num:
end=middle
middle=(start+end)/2
else:
start=middle
middle=(start+end)/2
print("%.4f"%middle)
22.列表中不相邻整数和的最大值
a=list(map(int, input().split()))
b=[0 for i in a]
c=[0 for i in a]
for i in range(len(b)):
b[i]=max(a[:i+1])
for i in range(len(c)-2):
c[i+2]=b[i]+a[i+2]
print(max(c))
23.字符统计
A_num=0
a_num=0
data_num=0
dl=input().split()
for i in range(len(dl)):
for j in dl[i]:
if 'A'<=j<='Z':
A_num+=1
elif 'a'<=j<='z':
a_num+=1
elif '0'<=j<='9':
data_num+=1
print(A_num,a_num,data_num)
24.100~200素数累加求和
nsum=0
for i in range(100,201):
for j in range(2,i):
if i%j==0:
break
elif j==i-1:
nsum+=i
else:
continue
print(nsum)
25.水上石阶
num=int(input())
arr=[0 for i in range(num+1)]
arr[0]=arr[1]=1
for i in range(num-1):
arr[i+2]=arr[i]+arr[i+1]
print(arr[num])
26.神奇的计算
num=0
for x in range(1,10):
for y in range(1,10):
if y == x:
continue
for z in range(1,10):
if z == x or z==y:
continue
for m in range(1,10):
if m == x or m==y or m==z:
continue
for n in range(1,10):
if n == x or n==y or n==z or n==m:
continue
if (x*10+y)*(z*100+m*10+n)==(x*100+m*10+y)*(z*10+n):
num+=1
print(num)
27.数字规律相加
(这什么破规律??)
num=int(input())
nsum=0
for i in range(num):
nsum=nsum+(num-i)*10**(i)
nsum+=num-1
print(nsum)
一次循环就能解决的事情干嘛要用两次循环(抖
28.逆时针原地逆转图像
num=int(input())
b=[]
for i in range(num):
a=list(map(int, input().split()))
b.append(a)
for i in range(num//2):
for j in range(num//2):
b[i][j],b[j][num-1-i],b[num-j-1][i],b[num-i-1][num-j-1]= \
b[j][num-1-i],b[num-1-i][num-1-j],b[i][j],b[num-j-1][i]
if num%2 !=0:
n=num//2
for i in range(n):
b[i][n],b[n][num-1-i],b[num-1-i][n],b[n][i]=\
b[n][num-1-i],b[num-1-i][n],b[n][i],b[i][n]
for i in range(num):
for j in range(num):
print(b[i][j],end=" ")
print("")
这题值得思考。
29.三个忍者
arr = list(map(int, input().split()))
limit = list(map(int, input().split()))
num=0
for i in range(len(arr)):
for j in range(i, len(arr)):
if i != j:
for k in range(j, len(arr)):
if k != j and abs(arr[i]-arr[j])<=limit[0] and abs(arr[i]-arr[k])<=limit[1] \
and abs(arr[j]-arr[k])<=limit[2]:
num+=1
print(num)
30.长城最长凸起
def judge_longest_length(arr):
m=arr.index(max(arr))
if m>0:
for i in range(0,m):
if arr[i]>=arr[i+1]:
return 0
elif m != len(arr)-1:
for i in range(m,len(arr)-1):
if arr[i]<=arr[i+1]:
return 0
return len(arr)
num = 0
arr = list(map(int, input().split()))
re = [[0 for i in range(len(arr))] for i in range(len(arr))]
for i in range(len(arr)-2):
for j in range(i, len(arr)):
if j - i < 2:
continue
else:
a=judge_longest_length(arr[i:j])
if a>num:
num=a
print(num)
31.闭包函数实现计数器
刚开始忘记题目要求是用闭包写了,第一次写的用的是yeild。
def counter():
count=0
while True:
count+=1
print(count)
yield count
g=counter()
for i in range(5):
next(g)
闭包:
32.“python”的编辑距离
a=input()
b="python"
len_a=len(a)
len_b=len(b)
c=[[0 for i in range(len_b+1)] for j in range(len_a+1)]
for i in range(len(a)+1):
for j in range(len(b)+1):
if i == 0:
c[i][j]=j
elif j==0:
c[i][j]=i
else:
c[i][j]=min(c[i-1][j]+1,c[i][j-1]+1,c[i-1][j-1]+ (0 if a[i-1]==b[j-1] else 1))
print(c[len_a][len_b])
33.找出目标在数组中的位置
34.n的平方和立方
def nnn(n):
def pf_lf():
print(n**2,n**3,sep="\n")
return pf_lf
n=int(input())
a=nnn(n)# 环境
a()# n值
35.分发水果
aa=list(map(int, input().split()))
num,m=aa[0],aa[1]
nn=[0 for i in range(num)]
n=0
while n*(n+1)/2<m:
n=n+1
for i in range(n-1):
nn[i%num]=nn[i%num]+i+1
nn[(n-1)%num]+=int(m-n*(n-1)/2)
for i in nn:
print(i,end=" ")
36.sort和lambda函数
num,t=map(int,input().split())
l=list(map(int, input().split()))
a=sorted(l, key=lambda x: abs(x-t))
# l.sort(key=lambda x: abs(x-t))
# print(l)
for i in range(num):
print(a[i],end=" ")
37.使用lambda函数
除法先转化成地板除
str1=input()
list_str1=list(str1)
b=0
for i in range(len(str1)):
if str1[i]=='/':
list_str1.insert(i+b,'/')
b+=1
str2=[]
str2="".join(list_str1)
a=lambda s: eval(s)
print(a(str2))
38.斐波那契数
n=int(input())
if n==0:
print(0)
elif n==1:
print(1)
else:
f_n2=0
f_n1=1
f_n=0
for i in range(1,n):
f_n=f_n2+f_n1
f_n2=f_n1
f_n1=f_n
print(f_n)
39.数列求和
递归
def digui(n):
if n==1:
return 1
else:
return n+digui(n-1)
n=int(input())
print(digui(n))
40.合并区间
注意需要排个序,最后的数组顺序必须是按顺序的。
num=int(input())
if num>0:
edge_ran=list(map(int, input().split()))
for i in range(num):
for j in range(0,num-i):
if j!=num-1:
if edge_ran[2*j] > edge_ran[2*(j+1)]:
edge_ran[2*j],edge_ran[2*(j+1)]=edge_ran[2*(j+1)],edge_ran[2*j]
edge_ran[2*j+1],edge_ran[2*(j+1)+1]=edge_ran[2*(j+1)+1],edge_ran[2*j+1]
# print(edge_ran)
is_print=[1 for i in range(num)]
for i in range(num):
for j in range(i,num):
if j!=i and edge_ran[2*i]<=edge_ran[2*j+1] and edge_ran[2*i+1]>=edge_ran[2*j]:
is_print[i]=0
edge_ran[2*j]=min(edge_ran[2*i],edge_ran[2*j])
edge_ran[2*j+1]=max(edge_ran[2*j+1],edge_ran[2*i+1])
for i in range(num):
if is_print[i]:
if i!=num-1:
print(edge_ran[2*i],edge_ran[2*i+1],sep=" ",end=" ")
else:
print(edge_ran[2*i],edge_ran[2*i+1],sep=" ")
41.判断点是否在圆内
class circle():
def __init__(self,x,y,r):
self.x=x
self.y=y
self.r=r
def is_in_circle(self,m,n):
if (m-self.x)**2+(n-self.y)**2 <= self.r**2:
print("1")
else:
print("-1")
m,n,x,y,r=map(int,input().split())
c=circle(x,y,r)
c.is_in_circle(m,n)
42.朋友圈
class UnionFindSet():
def __init__(self,num):
self.num=num
self.fathermap={}
self.size={}
for node in range(num):
self.fathermap[node]=node # 自己的父节点是自己
self.size[node]=1 # 后代节点的数量初始化为1
# 查找
def search(self,node):
father=self.fathermap[node]
if node!=father:
if father!=self.fathermap[father]:
self.size[father]+=1
father=self.search(father)
self.fathermap[node]=father
return father
# 合并
def union(self,a,b):
if a is None or b is None:
return
a_root=self.search(a)
b_root=self.search(b)
if(a_root!=b_root):
a_size=self.size[a_root]
b_size=self.size[b_root]
if a_size>b_size:
self.fathermap[b_root]=a_root
self.size[a_root]=a_size+b_size
else:
self.fathermap[a_root]=b_root
self.size[b_root]=a_size+b_size
# 多少个圈子
def findnum(self):
n=0
for i in range(self.num):
if self.fathermap[i]==i:
n+=1
print(n)
# return n
num_node=int(input())
num_rela=int(input())
u1=UnionFindSet(num_node)
for i in range(num_rela):
a,b=map(int,input().split())
u1.union(a,b)
u1.findnum()
43.转换大小写
class include2func():
def __init__(self):
self.s=""
def getString(self):
self.s=input()
def printString(self):
print(self.s.upper())
a=include2func()
a.getString()
a.printString()
44.简单计算器
class zhengshu_calc():
def __init__(self):
self.list=[]
def calc(self,list):
self.list=list
str1="".join(list)
print(eval(str1))
strlist1=input().split()
a=zhengshu_calc()
a.calc(strlist1)
45.BMI指数计算
class person():
def __init__(self,name,weight,height,gender):
self.name=name
self.weight=weight
self.height=height
self.gender=gender
self.__bmi=0
def read_bmi(self):
if self.gender=="female":
self.__bmi=int((self.height-70)*0.6)
else:
self.__bmi=int((self.height-80)*0.7)
return self.__bmi
name,weight,height,gender=input().split()
weight=int(weight)
height=int(height)
p=person(name,weight,height,gender)
print(p.read_bmi())
46.计算阶乘
class bigint():
def __init__(self,num):
self.num=num
def jiecheng(self):
r=1
for i in range(1,self.num+1):
r=r*i
return r
n=int(input())
a=bigint(n)
print(a.jiecheng())
47.实例计数
class person():
count=0
def __init__(self):
person.count+=1
a=person()
b=person()
c=person()
d=person()
e=person()
print(person.count)
48.计算时间差
def this_year_is_run_year(thisyear):
if thisyear % 400 == 0:
return True
elif thisyear % 100 == 0:
return False
elif thisyear % 4 == 0:
return True
else:
return False
def one_day_is_which_day(year,month,day):
run=this_year_is_run_year(year)
if month==1:
return day
elif month==2:
return 31+day
elif month==3:
return run+59+day
elif month==4:
return run+90+day
elif month==5:
return run+120+day
elif month==6:
return run+151+day
elif month==7:
return run+181+day
elif month==8:
return run+212+day
elif month==9:
return run+243+day
elif month==10:
return run+273+day
elif month==11:
return run+304+day
elif month==12:
return run+334+day
year1, month1, day1 = map(int, input().split())
year2, month2, day2 = map(int, input().split())
how_many_days=365+this_year_is_run_year(year1)-one_day_is_which_day(year1,month1,day1)+one_day_is_which_day(year2,month2,day2)
if year1==year2:
how_many_days=how_many_days-365-this_year_is_run_year(year1)
elif year2-year1>1:
for i in range(year1+1,year2):
how_many_days+=this_year_is_run_year(i)+365
print(how_many_days)
49.计算重叠部分面积
class sequare():
def __init__(self,x1,y1,x2,y2):
self.x1=x1
self.y1=y1
self.x2=x2
self.y2=y2
def calc_same_s(self,bx1,by1,bx2,by2):
if (bx1<=self.x1<=bx2 or bx1<=self.x2<=bx2 or self.x1<=bx1<=self.x2 or self.x1<=bx2<=self.x2) and \
(by2<=self.y1<=by1 or by2<=self.y2<=by1 or self.y2<=by1<=self.y1 or self.y2<=by2<=self.y1):
return (min(self.x2,bx2)-max(self.x1,bx1))*(min(self.y1,by1)-max(self.y2,by2))
else:
return 0
ax1,ay1,ax2,ay2=map(int,input().split())
bx1,by1,bx2,by2=map(int,input().split())
a=sequare(ax1,ay1,ax2,ay2)
print(a.calc_same_s(bx1,by1,bx2,by2))
50.实现栈
class stack():
def __init__(self):
self.list=[]
def push_stack(self,p):
self.list.append(p)
def pop_stack(self):
self.list.pop()
def print_stack(self):
for i in self.list:
print(i,end=" ")
s=stack()
while(True):
a=input().split()
# print()
if a[0]=='0':
break
elif a[0]=='1':
s.push_stack(a[1])
else:
s.pop_stack()
s.print_stack()
51.和为k的子数组
a=list(map(int,input().split()))
key=int(input())
numk=0
for i in range(len(a)):
for j in range(i,len(a)):
num=0
for k in range(i,j+1):
num+=a[k]
if num==key:
numk+=1
print(numk)
52.判断回文字符串
def is_huiwen(ll):
for i in range(len(ll)):
if ll[i]!=ll[len(ll)-i-1]:
return False
return True
def digui_huiwen(ll,delete_num):
if is_huiwen(ll):
return True
elif delete_num>0:
for i in range(len(ll)):
p=ll.pop(i)
if is_huiwen(ll):
return True
elif digui_huiwen(ll,delete_num-1):
return True
ll.insert(i,p)
return False
a=input()
b=[i for i in a]
delete_num=int(input())
print(digui_huiwen(b,delete_num))
52.合并两个有序链表
53.集群数
import copy
row, col = map(int, input().split())
a = []
for i in range(row):
b = list(map(int, input().split()))
a.append(b)
c = copy.deepcopy(a)
def dfs(i, j):
if a[i][j] == 1 and c[i][j] == -1:
flag = 0
# 更新c[i][j],如果它周围的有父节点,那么它也等于该点的父节点
if i > 0 and a[i-1][j] == 1 and c[i-1][j] != -1:
c[i][j] = c[i-1][j]
flag = 1
if i+1 < row and a[i+1][j] == 1 and c[i+1][j] != -1:
c[i][j] = c[i+1][j]
flag = 1
if j > 0 and a[i][j-1] == 1 and c[i][j-1] != -1:
c[i][j] = c[i][j-1]
flag = 1
if j+1 < col and a[i][j+1] == 1 and c[i][j+1] != -1:
c[i][j] = c[i][j+1]
flag = 1
if flag == 0:
c[i][j] = i*row+j
# 更新上下左右
if i > 0 and a[i-1][j] == 1 and c[i-1][j] == -1:
dfs(i-1, j)
if j+1 < col and a[i][j+1] == 1 and c[i][j+1] == -1:
dfs(i, j+1)
if i+1 < row and a[i+1][j] == 1 and c[i+1][j] == -1:
dfs(i+1, j)
if j > 0 and a[i][j-1] == 1 and c[i][j-1] == -1:
dfs(i, j-1)
for i in range(row):
for j in range(col):
c[i][j] = -1
for i in range(row):
for j in range(col):
dfs(i, j)
d = []
for i in range(row):
for j in range(col):
if a[i][j] == 1 and c[i][j] not in d:
d.append(c[i][j])
print(len(d))
55.有序数组去重
a=list(map(int, input().split()))
for i in a:
if a.count(i) > 1:
a.remove(i)
print(len(a))
56.数组中出现的奇异数
a=list(map(int, input().split()))
b=[]
for i in a:
if a.count(i)==1:
b.append(i)
b.sort()
print(b)
57.每日温度
a=list(map(int, input().split()))
for i in range(len(a)):
for j in range(i,len(a)):
if i!=j and a[j]>a[i]:
print(j-i,end=" ")
break
if j == len(a)-1:
print("0",end=" ")
58.数组实现循环队列
n=int(input())
b=[]
m=int(input())
for i in range(m):
a=input().split()
if a[0]=='1':
if len(b)+1>n:
print("False")
else:
b.append(int(a[1]))
print("True")
elif a[0]=='2':
if len(b)==0:
print("-1")
else:
print(b.pop(0))
59.最接近成功的三位同学
a=list(map(int, input().split()))
t=int(input())
num=0
for i in range(len(a)):
for j in range(i,len(a)):
if i!=j:
for k in range(j,len(a)):
if k!=j and a[i]+a[j]+a[k]<t:
num+=1
print(num)
60.环游世界
文章来源:https://www.toymoban.com/news/detail-794155.html
nextVisit = list(map(int, input().split()))
n = len(nextVisit)
numVisit = [0 for i in range(n)]
i = 0
visitNum = -1
while 0 in numVisit:
numVisit[i] += 1
if numVisit[i] % 2 == 1:
i = nextVisit[i]
else:
i = (i + 1) % n
visitNum += 1
visitNum = visitNum % (1e9+7)
print(int(visitNum))
AC截图:
文章来源地址https://www.toymoban.com/news/detail-794155.html
到了这里,关于西工大--人工智能程序设计noj--前60道的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!