第5季 类
41题
import math
class Rectangle():
def __init__(self,x1,y1,x2,y2):
x1, y1, x2, y2=int(x1), int(y1), int(x2), int(y2)
self.x1,self.x2 = min(x1,x2),max(x1,x2)
self.y1,self.y2= min(y1,y2),max(y1,y2)
def calculate_overlapping_area(self,x3,y3,x4,y4):
if (self.x2<=x3 or x4<=self.x1) and (self.y2 <= y3 or y4<=self.y1):
return 0
else:
lens = min(self.x2, x4) - max(self.x1, x3)
wide = min(self.y2, y4) - max(self.y1, y3)
return lens * wide
x1, y1, x2, y2 = input().split(" ")
rectangle1 = Rectangle(x1,y1,x2,y2)
x3, y3, x4, y4 = input().split(" ")
rectangle2 = Rectangle(x3,y3,x4,y4)
res = rectangle1.calculate_overlapping_area(rectangle2.x1,rectangle2.y1,rectangle2.x2,rectangle2.y2)
print(res)
42题
class integer_calculation():
def __init__(self,operand1,operator,operand2):
self.operand1 = int(operand1)
self.operator = operator
self.operand2 = int(operand2)
def calculate(self):
if operator == '+':
return self.operand1 + self.operand2
elif operator == '-':
return self.operand1 - self.operand2
elif operator == '*':
return self.operand1 * self.operand2
elif operator == '/':
return int(self.operand1 / self.operand2)
operand1,operator,operand2 = input().split(" ")
calculator = integer_calculation (operand1,operator,operand2)
res = calculator.calculate()
print(res)
43题
class Person():
count = 0
def __init__(self):
Person.count = self.count + 1
p1 = Person()
p2 = Person()
p3 = Person()
p4 = Person()
p5 = Person()
print(p5.count)
44题
class BigInt():
def __init__(self,n):
self.n = int(n)
def factorial(self):
if self.n == 0:
return 1
else:
res = 1
for i in range(1,self.n + 1):
res = res * i
return res
x = input()
obj = BigInt(x)
print(obj.factorial())
45题 并查集UnionFind
class UnionFind:
def __init__(self,person_num):
#malloc新空间
self.root = [-1] * person_num#(row*col)
for i in range(person_num):#(row*col):
self.root[i] = i
def find(self,x):
#判断是否等于根节点,等于就是最终值
if x == self.root[x]:
return self.root[x]
#否则寻找上一节点的根节点
else:
return self.find(self.root[x])
def union(self,x,y):
rootX = self.find(x)
rootY = self.find(y)
#从root上更新新root
if rootX != rootY:
self.root[rootX] = rootY
def count_category(self):
count = 0
for i in range(len(self.root)):
if i == self.root[i]:
count = count + 1
return count
person_num = int(input())
friendship_num = int(input())
uf = UnionFind(person_num)
for i in range(friendship_num):
input_list = input().split(' ')
x = int(input_list[0])
y = int(input_list[1])
uf.union(x,y)
print(uf.count_category())
46题
class Stack:
stack_list = []
def stack_operation(self,input_str):
if input_str[0] == '1':
self.stack_list.append(int(input_str[1]))
return
#不用else防非法输入
if input_str[0] == '2':
self.stack_list.pop()
return
stack = Stack()
while True:
input_str = input().split(' ')
if input_str[0] == '0':
break
else:
stack.stack_operation(input_str)
for i in range(len(stack.stack_list)):
print(stack.stack_list[i],end = " ")
47题
class Person:
def __init__(self,input_str):
self.name = input_str[0]
self.weight = int(input_str[1])
self.height = int(input_str[2])
self.gender = input_str[3]
self.__bmi = 0
def calculate_bmi(self):
if self.gender == 'female':
self.__bmi = int((self.height - 70) * 0.6)
return
if self.gender == 'male':
self.__bmi = int((self.height - 80) * 0.7)
return
def get_bmi(self):
return self.__bmi
input_str = input().split(' ')
person = Person(input_str)
person.calculate_bmi()
print(person.get_bmi())
48题
class StringTransform:
def getString(self):
self.s = input()
return
def printString(self):
print(self.s.upper())
st = StringTransform()
st.getString()
st.printString()
49题
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
class Circle:
def __init__(self,x,y,r,point):
self.x = x
self.y = y
self.r = r
self.point = point
def judge(self):
distance = (self.point.x-self.x)**2+(self.point.y-self.y)**2
if distance > self.r**2:
return -1
elif distance <= self.r**2:
return 1
point_x,point_y,circle_x,circle_y,circle_r = input().split(' ')
point = Point(int(point_x),int(point_y))
circle = Circle(int(circle_x),int(circle_y),int(circle_r),point)
print(circle.judge())
50题
import datetime
class TimeDifference:
def __init__(self,input_str1,input_str2):
self.year1,self.month1,self.day1 = input_str1.split(' ')
self.year2,self.month2,self.day2 = input_str2.split(' ')
self.date1 = datetime.datetime(int(self.year1),int(self.month1),int(self.day1))
self.date2 = datetime.datetime(int(self.year2),int(self.month2),int(self.day2))
def calculate_difference(self):
return (self.date2 - self.date1).days
input_str1 = input()
input_str2 = input()
td = TimeDifference(input_str1,input_str2)
print(td.calculate_difference())
第6季 数据结构与算法
51题
class Solution:
def dailyTemperatures(self,T):
length = len(T)
ans = [0]*length
stack = []
for i in range(length):
temperature = T[i]
while stack and temperature > T[stack[-1]]:
prev_index = stack.pop()
ans[prev_index] = i - prev_index
stack.append(i)
return ans
input_list = input().split(' ')
T = []
for i in input_list:
T.append(int(i))
s = Solution()
for i in s.dailyTemperatures(T):
print(i,end=' ')
52题 三数之和小于目标值
class Solution:
def threeSumSmaller(self, nums, target):
res = 0
nums.sort()
for i, num in enumerate(nums):
t = target - num
left, right = i + 1, len(nums) - 1
while left < right:
if nums[left] + nums[right] >= t:
right -= 1
elif nums[left] + nums[right] < t:
res += right - left
left += 1
return res
input_list = input().split(' ')
target = int(input())
nums = []
for i in input_list:
nums.append(int(i))
s = Solution()
print(s.threeSumSmaller(nums, target))
53题
class Solution:
def removeDuplicates(self, nums):
s = 0
for i in range(len(nums)):
if nums[i] !=nums[s]:
s += 1
nums[s] = nums[i]
return s+1
tmp = input().split(' ')
input_list = []
s = Solution()
for i in tmp:
input_list.append(int(i))
print(s.removeDuplicates(input_list))
54题
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
#head作为头返回,才能完整打印结果
head = ListNode(None)
#l3类似于遍历的临时变量
l3 = head
while l1 and l2:
#temp = l1.next
if l1.val < l2.val:
l3.next = l1
l3 = l3.next
l1 = l1.next
else:
l3.next = l2
l3 = l3.next
l2 = l2.next
if l1 :
l3.next = l1
if l2:
l3.next = l2
return head.next
input_list1 = input().split(' ')
input_list2 = input().split(' ')
s = Solution()
#输入:1->2->3
l1 = ListNode(int(input_list1[0]))
pre = l1
for i in range(1,len(input_list1)):
tmp = ListNode(int(input_list1[i]))
pre.next = tmp
pre = tmp
#列表尾
if i == (len(input_list1)-1):
pre.next == None
#输入: 2->4->6
l2 = ListNode(int(input_list2[0]))
pre = l2
for j in range(1,len(input_list2)):
tmp = ListNode(int(input_list2[j]))
pre.next = tmp
pre = tmp
#列表尾
if i == (len(input_list2)-1):
pre.next == None
# 输出:1->2->2->3->4->6
r = s.mergeTwoLists(l1,l2)
print(r.val,end = ' ')
# 先判断是否到末尾了 再print
while r.next != None:
r = r.next
print(r.val,end = ' ')
55题
class CircularQueue:
def __init__(self,capacity):
self._head, self._tail = 0,0
self._capacity = capacity + 1
self._items = [None] * self._capacity
def is_full(self):
return (self._tail + 1) % self._capacity == self._head
def is_empty(self):
return self._tail == self._head
def dequeue(self):
if self.is_empty():
return -1
else:
dequeue_element = self._items[self._head]
self._items[self._head] = None
self._head = (self._head + 1) % self._capacity
return dequeue_element
def enqueue(self,val):
if self.is_full():
return False
else:
self._items[self._tail] = val
self._tail = (self._tail + 1) % self._capacity
return True
def prior(self):
return self._items[self._head] if not self.is_empty() else -1
def tail(self):
return self._items[(self._tail - 1 + self._capacity) % self._capacity] if not self.is_empty() else -1
n = int(input())
m = int(input())
queue = CircularQueue(n)
res = []
for i in range(m):
input_str = input().split(' ')
if input_str[0] == '1':
res.append(queue.enqueue(int(input_str[1])))
if input_str[0] == '2':
res.append(queue.dequeue())
for i in res:
print(i)
56题 岛屿数量
class Solution:
def numIslands(self, grid):
count = 0
def bfs(i,j):
if j >= len(grid[0]) or i >= len(grid) or j < 0 or i < 0 or grid[i][j] == '0' :
return
grid[i][j] = '0'
bfs(i-1,j)
bfs(i,j-1)
bfs(i+1,j)
bfs(i,j+1)
for i, row in enumerate(grid):
for j, col in enumerate(row):
if col == '1':
bfs(i,j)
count += 1
return count
s = Solution()
input_list = input().split(' ')
row = int(input_list[0])
col = int(input_list[1])
grid = []
for i in range(row):
row_list = input().split(' ')
grid.append(row_list)
print(s.numIslands(grid))
57题 前缀和
class Solution:
#python函数注释
#def subarraySum(self,nums:List[int],k:int) -> int:
def subarraySum(self,nums,k):
cur_sum = 0
adict = {}
adict[0] = 1
count = 0
for num in nums:
cur_sum += num
if cur_sum - k in adict:
count += adict[cur_sum-k]
if cur_sum in adict:
adict[cur_sum] += 1
else:
adict[cur_sum] = 1
return count
input_list = input().split(' ')
nums = []
for i in input_list:
nums.append(int(i))
k = int(input())
s = Solution()
print(s.subarraySum(nums,k))
58题
#MOD防止出现负数
MOD = 1e9+7
nextVisit = list(map(int,input().split()))
length = len(nextVisit)
ans = [0] * length
for i in range(1,length):
ans[i] = (ans[i-1] + 1 + (ans[i-1] - ans[nextVisit[i-1]]) + 1 + MOD) % MOD
print(int(ans[length-1]))
59题
class Solution:
def singleNumbers(self, nums):
res = 0
# 全员进行异或
for num in nums:
res ^= num
# 找出不为 0 的最低位
# & 位运算的使用
div = 1
while (div & res == 0):
div <<= 1
# 进行分组
p, q = 0, 0
for num in nums:
if num & div:
p ^= num
else:
q ^= num
return [p, q]
input_list = input().split(' ')
nums = []
for i in input_list:
nums.append(int(i))
s = Solution()
print(s.singleNumbers(nums))
60题 回文字符串
def isKPalindrom(input_string,k):
N = len(input_string)
answers = [[0 for col in range(N+1)] for row in range(N+1)]
for i in range(N+1):
for j in range(N+1):
answers[i][j] = 0
for gap in range(1,N+1):
l = 1
h = l + gap
while(h <= N):
if(input_string[l-1] == input_string[h - 1]):
answers[l][h] = answers[l+1][h-1]
else:
answers[l][h] = 1 + min(answers[l+1][h], answers[l][h-1])
l = l + 1
h = h + 1
return answers[1][N] <= k
input_string = input()
k = int(input())
print(isKPalindrom(input_string,k))