函数与结构体
1.坐标函数
需要知道tuple概念
from math import sqrt
def dis(p1, p2): // p1, p2 为双元组
distance = (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
return sqrt(distance)
2.简单素数筛
def prime(x):
if x < 2:
return False
else:
for i in range(2, int(x ** 0.5 ) + 1):
if x % i == 0:
return False
return True
3.判断闰年
def leap_year(n):
if n % 4 == 0 and n % 100 != 0:
return True
elif n % 400 == 0:
return True
else:
return False
4.简单结构体示范:
class grade:
def __init__(self):
self.name = ''
self.a = 0
self.b = 0
self.c = 0
self.total = 0
n = int(input())
s = [grade() for i in range(n)] // 必须这样写
for i in range(n):
s[i].name, a, b, c = input().split()
s[i].a = int(a)
s[i].b = int(b)
s[i].c = int(c)
s[i].total = int(a) + int(b) + int(c)
for i in range(n - 1):
for j in range(i+1, n):
if abs(s[i].a - s[j].a) <= 5 and abs(s[i].b - s[j].b) <= 5 and abs(s[i].c - s[j].c) <= 5 and abs(s[i].total - s[j].total) <= 10:
print(s[i].name, s[j].name)
5.如果要使用全局变量
在函数内加上: global cc
评论
发表评论