这里收集一些短小精悍的py代码
这里收集一些短小精悍的py代码
# https://ac.nowcoder.com/acm/contest/88455/B
# 对于一个整数 $\mathrm{n}$,存在一种操作:将 $\mathrm{n}$ 对一个不大于 $\mathrm{n}$ 的正整数 $\mathrm{mod}$ 取余($\mathrm{1\leq mod\leq n}$),并将结果再赋值给 $\mathrm{n}$。(即:$\mathrm{n = n \% mod}$)
# 请问 $\mathrm{n}$ 变为 $\mathrm{0}$ **最多**需要多少次操作?
from math import ceil
t=int(input())
while t:
t=t-1
n=int(input())
cnt = 0
while (n):
n = ceil(n / 2.0) - 1
cnt +=1
print(cnt)
# 实现行列式
def determinant(matrix):
# Base case for 2x2 matrix
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
# Recursive case for larger matrices
det = 0
for c in range(len(matrix)):
# Create submatrix for minor
submatrix = [row[:c] + row[c+1:] for row in matrix[1:]]
# Calculate determinant recursively
det += ((-1) ** c) * matrix[0][c] * determinant(submatrix)
return det
# 重写`__call__`魔术方法
class add(int):
def __call__(self,n):
return add(self+n)
# add(1)(2)(3) # 6
# add(1)(2)(3)(4); # 10
# add(1)(2)(3)(4)(5) # 15
# Python字典树 Trie
def in_array(array1, array2):
_end = '_end' # Define _end as a unique marker for the end of a word
def make_trie(*words):
root = dict()
for word in words:
current_dict = root
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict[_end] = _end
return root
def in_trie(trie, word):
current_dict = trie
for letter in word:
if letter not in current_dict:
return False
current_dict = current_dict[letter]
return _end in current_dict
my_trie = make_trie(*array2)
return list(filter(lambda word: in_trie(my_trie, word), array1))
# 递归方式翻转链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse_func(H):
if (not H) or (not H.next):
return H
newHead=reverse_func(H.next)
H.next.next=H
H.next=None
return newHead
return reverse_func(head)
# 不进行四舍五入,小数点两位以后的小数,直接舍弃
from math import ceil
n=int(input())
for i in range(n):
a,b=map(int,input().split())
# 如果最终得分(总成绩)是小数,老师们会先保留两位小数(不进行四舍五入,小数点两位以后的小数,直接舍弃),然后向上取整。
#ans=
total_score=0.4*a+0.6*b
truncated_score = int(total_score * 100) / 100 # Truncate to two decimal places
ans = ceil(truncated_score) # Round up to the nearest whole number
print(ans)
# https://ac.nowcoder.com/acm/contest/17942/H
# Python的datetime类型获取 day_of_week和day_of_month
from datetime import datetime, timedelta
# Initialize start and end dates
start_date = datetime(2000, 1, 1)
end_date = datetime(2020, 10, 1)
# Initialize the ans variable
ans = 0
# Loop through each day in the date range
current_date = start_date
while current_date <= end_date:
# print(f"{current_date.weekday()=} {current_date.day=}")
if current_date.weekday() == 0 or current_date.day == 1: # Check if it's Monday (0) or the first day of the month (1)
ans += 2
else:
ans += 1
current_date += timedelta(days=1) # Move to the next day
# Print the result
print(f"{ans}")
# 计算二维lists的行列式
# https://ac.nowcoder.com/acm/contest/87255/J
def determinant(matrix):
if len(matrix)==1 and len(matrix[0])==1:
return matrix[0][0]
# Base case for 2x2 matrix
if len(matrix) == 2 and len(matrix[0]) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
# Recursive case for larger matrices
det = 0
for c in range(len(matrix)):
submatrix = [row[:c] + row[c+1:] for row in matrix[1:]]
sign = (-1) ** c
det += sign * matrix[0][c] * determinant(submatrix)
return det
# Read inputs
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int, input().split())))
# Function to get a submatrix of size (size_x, size_y)
def slice_of_2d_lists(a, size_x, size_y):
submatrix = []
for i in range(size_y):
row = []
for j in range(size_x):
if i < len(a) and j < len(a[i]):
row.append(a[i][j])
else:
row.append(0)
submatrix.append(row)
return submatrix
# Calculate the minimum determinant
min_det = int(1e12)
for size in range(1, max(n, m) + 1):
submatrix = slice_of_2d_lists(a, size, size)
det = determinant(submatrix)
# print(f"{det=}")
min_det = min(min_det, det)
print(min_det)
# 和常规认识一致的四舍五入 https://stackoverflow.com/a/13963509/15497427
def trueround(number, places=0):
'''
trueround(number, places)
example:
>>> trueround(2.55, 1) == 2.6
True
uses standard functions with no import to give "normal" behavior to
rounding so that trueround(2.5) == 3, trueround(3.5) == 4,
trueround(4.5) == 5, etc. Use with caution, however. This still has
the same problem with floating point math. The return object will
be type int if places=0 or a float if places=>1.
number is the floating point number needed rounding
places is the number of decimal places to round to with '0' as the
default which will actually return our interger. Otherwise, a
floating point will be returned to the given decimal place.
Note: Use trueround_precision() if true precision with
floats is needed
GPL 2.0
copywrite by Narnie Harshoe <signupnarnie@gmail.com>
'''
place = 10**(places)
rounded = (int(number*place + 0.5if number>=0 else -0.5))/place
if rounded == int(rounded):
rounded = int(rounded)
return rounded
def trueround_precision(number, places=0, rounding=None):
'''
trueround_precision(number, places, rounding=ROUND_HALF_UP)
Uses true precision for floating numbers using the 'decimal' module in
python and assumes the module has already been imported before calling
this function. The return object is of type Decimal.
All rounding options are available from the decimal module including
ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN,
ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.
examples:
>>> trueround(2.5, 0) == Decimal('3')
True
>>> trueround(2.5, 0, ROUND_DOWN) == Decimal('2')
True
number is a floating point number or a string type containing a number on
on which to be acted.
places is the number of decimal places to round to with '0' as the default.
Note: if type float is passed as the first argument to the function, it
will first be converted to a str type for correct rounding.
GPL 2.0
copywrite by Narnie Harshoe <signupnarnie@gmail.com>
'''
from decimal import Decimal as dec
from decimal import ROUND_HALF_UP
from decimal import ROUND_CEILING
from decimal import ROUND_DOWN
from decimal import ROUND_FLOOR
from decimal import ROUND_HALF_DOWN
from decimal import ROUND_HALF_EVEN
from decimal import ROUND_UP
from decimal import ROUND_05UP
if type(number) == type(float()):
number = str(number)
if rounding == None:
rounding = ROUND_HALF_UP
place = '1.'
for i in range(places):
place = ''.join([place, '0'])
return dec(number).quantize(dec(place), rounding=rounding)
# https://ac.nowcoder.com/acm/contest/1/K
mod=1000000007
# https://oeis.org/A091894
# https://math.stackexchange.com/questions/2172676/number-of-ordered-unlabeled-binary-rooted-trees-with-n-nodes-and-k-leafs
# binomial取模
def binomial_mod(n, k, mod):
if k > n:
return 0
if k == 0 or k == n:
return 1
# Initialize numerator and denominator
num = den = 1
# Compute n! / (k! * (n-k)!) % mod
for i in range(k):
num = num * (n - i) % mod
den = den * (i + 1) % mod
# Compute the modular inverse of denominator
den_inv = pow(den, mod - 2, mod)
return num * den_inv % mod
# 利用快速幂计算分数取模
def fraction_mod_inverse(a,b,mod):
# a*(b**(mod-2))%mod
return pow(b,mod-2,mod)*a%mod
# Number of ordered, unlabeled binary rooted trees with n nodes and k leaves
# 也是The number of Dyck paths of semilength n, having k-1 ddu's [here u = (1,1) and d = (1,-1)].
while True:
try:
n,k=map(int,input().split())
k=k-1
if n==0 and k==0:
ans=1
elif n==0:
ans=0
elif k<=(n)//2:
numerator=pow(2, (n-2*k-1), mod)*binomial_mod(n-1, 2*k, mod)%mod*binomial_mod(2*k, k, mod)%mod
denominator=k+1
ans=fraction_mod_inverse(numerator, denominator, mod)
else:
ans=0
print(ans)
except:
break
# https://ac.nowcoder.com/acm/contest/79877/K
# 环形数组(easy) 可以直接模拟
n,m=map(int,input().split())
ans=[[0 for j in range(m)]for i in range(n)]
vis=[[False for j in range(m)]for i in range(n)]
cur_direction_list=[[0,1], [1,0], [0,-1], [-1,0]]
cur_direction_index=0
cur_direction_x,cur_direction_y=cur_direction_list[cur_direction_index]
tot=1
cur_x=0
cur_y=0
ans[0][0]=1
vis[0][0]=True
def is_valid_position(new_try_x,new_try_y):
return 0<=new_try_x and new_try_x<=n-1 and\
0<=new_try_y and new_try_y<=m-1 and (not vis[new_try_x][new_try_y])
while tot<=m*n-1:
while True:
new_try_x=cur_x+cur_direction_x
new_try_y=cur_y+cur_direction_y
if is_valid_position(new_try_x,new_try_y):
break
else:
cur_direction_index=(cur_direction_index+1)%4
cur_direction_x,cur_direction_y=cur_direction_list[cur_direction_index]
cur_x=new_try_x
cur_y=new_try_y
tot+=1
ans[cur_x][cur_y]=tot
vis[cur_x][cur_y]=True
# print(f"{ans=}")
for line in ans:
print(" ".join(map(str,line)))
# https://ac.nowcoder.com/acm/contest/82672/H
# f[x_] := 1 + Sum[f[d], {d, Drop[Divisors[x], -1]}]
# f /@ {1, 2, 5, 10}
from functools import lru_cache
# 预处理,对于1<=n<=1e5的每个数拿到divisor
# Function to precompute divisors for all numbers up to max_n
def precompute_divisors(max_n):
divisors = [[] for _ in range(max_n + 1)]
for i in range(1, max_n + 1):
for j in range(i, max_n + 1, i):
divisors[j].append(i)
return divisors
# Precompute divisors for 1 <= x <= 10^5
max_n = 10**5
divisors_table = precompute_divisors(max_n)
# Recursive function with memoization to calculate f[x]
@lru_cache(None)
def f(x):
if x == 1:
return 1
return 1 + sum(f(d) for d in divisors_table[x][:-1])
# Precompute f[x] for all 1 <= x <= 10^5
f_values = [f(i) for i in range(1, max_n + 1)]
# Input
n = int(input())
a = list(map(int, input().split()))
# Output f[x] for each x in a
results = [f_values[x-1] for x in a]
print(" ".join(map(str, results)))
# https://ac.nowcoder.com/acm/contest/85910/E
# 给你三种三色物品,你每次可以选择3个同色物品或者3个相互异色物品进行消除,问你最多可以消除多少次?
# 类似的问题,每次选2个异色物品进行消除,问你最多可以消除多少次?
a,b,c=map(int,input().split())
min_value=min([a//3,b//3,c//3])
ans=0
gain1= min_value*3
ans +=gain1
a-=gain1
b-=gain1
c-=gain1
a,b,c=sorted([a,b,c])
if a==0:
ans+=b//3+c//3
elif a==1:
ans+=max(1+(b-1)//3+(c-1)//3, b//3+c//3 )
elif a==2:
ans+=max([1+(b-1)//3+(c-1)//3, 2+(b-2)//3+(c-2)//3, b//3+c//3 ] )
print(ans)
# https://ac.nowcoder.com/acm/contest/85910/B
# 原码、反码、补码定义例题
s = input() # e.g., "10000000000000000000000011000011"
# Ensure the input is 32 bits
if len(s) != 32 or not all(bit in '01' for bit in s):
raise ValueError("Input must be a 32-bit binary string")
# Function 补码
def complement_code(bin_str):
if bin_str[0]=='0':
return bin_str
else:
return add_one(reverse_code(bin_str))
# Function 反码
def reverse_code(bin_str):
if bin_str[0]=='0':
return bin_str
else:
return bin_str[0]+(''.join('1' if bit == '0' else '0' for bit in bin_str[1::]))
def add_one(bin_str):
bin_list = list(bin_str)
carry = 1
for i in range(len(bin_list) - 1, -1, -1):
if bin_list[i] == '1' and carry == 1:
bin_list[i] = '0'
elif carry == 1:
bin_list[i] = '1'
carry = 0
break
return ''.join(bin_list)
complement_str = complement_code(s)
print(f"{complement_str}")
# https://csacademy.com/ieeextreme-practice/task/9ca8fafd184f553a903734761546a224/
# 满二叉树中寻找两个节点之间的最短距离
def find_distance(a, b):
# Convert a and b to their binary representations without the '0b' prefix
bin_a = bin(a)[2:]
bin_b = bin(b)[2:]
# Strip leading zeros
bin_a = bin_a.lstrip('0')
bin_b = bin_b.lstrip('0')
depth_a = len(bin_a)
depth_b = len(bin_b)
# Pad the binary strings with leading zeros to make them the same length
max_len = max(len(bin_a), len(bin_b))
min_len = min(len(bin_a), len(bin_b))
# Find the longest common prefix
i = 0
while i < min_len and bin_a[i] == bin_b[i]:
i += 1
# Calculate the distance as the sum of the depths minus twice the length of the common prefix
common_prefix_length = max(0,i)
# print(f"{depth_a=} {depth_b=} {common_prefix_length=} {bin_a=} {bin_b=}")
distance = (depth_a - common_prefix_length) + (depth_b - common_prefix_length)
return distance
q = int(input())
while q:
q -= 1
a, b = map(int, input().split())
print(find_distance(a, b))
# https://ac.nowcoder.com/acm/contest/75483/E
def days_in_year_range(start_year, end_year):
def leap_years_count(year):
return year // 4 - year // 100 + year // 400
# Total years in the range
total_years = end_year - start_year + 1
# Total leap years in the range
leap_years = leap_years_count(end_year) - leap_years_count(start_year - 1)
# Regular years are the total years minus the leap years
regular_years = total_years - leap_years
# Calculate total days
total_days = regular_years * 365 + leap_years * 366
return total_days
t = int(input())
while t:
t -= 1
a_year, b_year = map(int, input().split())
print(days_in_year_range(a_year, b_year))
# https://ac.nowcoder.com/acm/contest/75483/B
# 24 hours notation to 12 hours notation
t = int(input())
while t:
t -= 1
h, m = map(int, input().split()) # 24 hours notation
# Determine AM or PM
if h == 0:
hh = 12
am_or_pm = "AM"
elif h == 12:
hh = 12
am_or_pm = "PM"
elif h > 12:
hh = h - 12
am_or_pm = "PM"
else:
hh = h
am_or_pm = "AM"
# Format minutes to be always two digits
# mm = f"{m:02}"
mm = f"{m}"
print(f"{hh} {mm} {(am_or_pm).lower()}") # 12 hours notation
# 二分查找
# https://ac.nowcoder.com/acm/contest/77231/B
import bisect
n,x=map(int,input().split())
a=list(map(int,input().split()))
a=sorted(a)
happy_number=0
# index=bisect.bisect_left(a,x)
index=bisect.bisect_right(a,x,lo=0,hi=len(a))
print(f"{index} {x-a[index-1]}")
# 链接:https://ac.nowcoder.com/acm/contest/80998/I
# 来源:牛客网
# Given n numbers between 0 and 9, use them to make two positive integers without leading zeros to minimize the product.
def minimize_product(numbers):
# Sort the numbers to easily distribute them
numbers.sort()
# Find the smallest digit that is not 0 as `num1`
num1 = 0
for i in range(len(numbers)):
if numbers[i] != 0:
num1 = numbers[i]
numbers.pop(i)
break
# Adjust to avoid leading zeros in `num2`
if numbers[0] == 0 and len(numbers) > 1:
for i in range(1, len(numbers)):
if numbers[i] != 0:
# Swap the leading zero with the first non-zero digit
numbers[0], numbers[i] = numbers[i], numbers[0]
break
# The remaining digits form `num2`
num2 = int(''.join(map(str, numbers)))
return num1 * num2
T = int(input())
for _ in range(T):
n = int(input())
a = list(map(int, input().split()))
result = minimize_product(a)
print(result)
# Prime factorization, find the smallest power. faster better
def smallest_prime_power(n):
if n == 1:
return "Infinity"
min_power = float('inf')
i = 2
while i * i <= n:
if n % i == 0:
power = 0
while n % i == 0:
n //= i
power += 1
min_power = min(min_power, power)
i += 1
if n > 1: # If there's any prime factor greater than sqrt(n)
min_power = min(min_power, 1)
if min_power == float('inf'):
return "Infinity"
else:
return min_power
n = int(input())
print(smallest_prime_power(n))
# 斐波那契数取模
def multiply(a, b, MOD):
c = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
c[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % MOD
return c
def pow_matrix(a, n, MOD):
sum_matrix = [[1, 0], [0, 1]]
base_matrix = a
while n > 0:
if n % 2 == 1:
sum_matrix = multiply(sum_matrix, base_matrix, MOD)
base_matrix = multiply(base_matrix, base_matrix, MOD)
n //= 2
return sum_matrix
def fib(n):
if n < 2:
return n
m = [[1, 1], [1, 0]]
mn = pow_matrix(m, n - 1, 10) # MOD = 10
return mn[0][0]
if __name__ == "__main__":
t = int(input())
for _ in range(t):
m = int(input())
print(fib(m + 1))
# binomial取模
def binomial_mod(n, k, mod):
if k > n:
return 0
if k == 0 or k == n:
return 1
# Initialize numerator and denominator
num = den = 1
# Compute n! / (k! * (n-k)!) % mod
for i in range(k):
num = num * (n - i) % mod
den = den * (i + 1) % mod
# Compute the modular inverse of denominator
den_inv = pow(den, mod - 2, mod)
return num * den_inv % mod
# 质因数分解
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return Counter(factors)
# 利用快速幂计算分数取模
def fraction_mod_inverse(a,b,mod):
# a*(b**(mod-2))%mod
return pow(b,mod-2,mod)*a%mod
# 考察Python中List的insert和del操作
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
n=len(arr)
pre_n=n
idx=-1
while True:
if idx==n-1:
break
idx+=1
if arr[idx]==0:
arr.insert(idx,0)
idx+=1
n+=1
del arr[pre_n:n]
# 装饰器例子
import time
def printarg(fn):
def wrapper(*args):
print(*args)
return wrapper
def timer(fn):
def wrapper(*args):
t1=time.time()
fn()
t2=time.time()
t=t2-t1
print("%s cost %.1f"%(fn.__name__,t))
return wrapper
@printarg
@timer
def func_a(*args):
time.sleep(1.0)
func_a(3,4,5)
# 指定4个位宽,右对齐
print('{:4}'.format(cur),end="")
# 从头到尾遍历
a=[2,3,5,6,88]
for i,_ in enumerate(a):
print(i,',',a[i])
#encoding:UTF-8
msg = 'www.BAIDU.com.123'
print(msg.upper()) #upper()函数,将所有字母都转换成大写
print(msg.lower()) #lower()函数,将所有字母都转换成小写
print(msg.capitalize()) #capitalize()函数,将首字母都转换成大写,其余小写
print(msg.title()) #title()函数,将每个单词的首字母都转换成大写,其余小写
char.isalpha()
char.isdigit()
# 字典按key排序
cnt4num=sorted(cnt4num.items(),key=lambda x:x[0])
# 判断两个list内容相同
import operator
a=[1,2,3]
b=[1,2,3]
if operator.eq(a,b):
print("same")
# 线性筛,对EulerPhi函数打表
# O(n)复杂度
phi=[0 for i in range(10005)]
prime=[0 for i in range(10005)]
vis=[False for i in range(100005)]
def phi_init(n):
phi[1]=1
cnt=0
for i in range(2,n+1):
if not vis[i]:
cnt=cnt+1
prime[cnt]=i
phi[i]=i-1
for j in range(1,cnt+1):
if i*prime[j]>n:
break
vis[i*prime[j]]=True
if i%prime[j]==0:
phi[i*prime[j]]=phi[i]*prime[j]
break
else:
phi[i*prime[j]]=phi[i]*phi[prime[j]]
# python生成幂集
# 参考https://www.cnblogs.com/Alan-LJP/p/11831228.html
from itertools import combinations
L = [1, 2, 3, 1]
result_list = sum([list(map(list, combinations(L, i))) for i in range(len(L) + 1)], [])
print('result_list =', result_list)
# 整数转二进制表示
print(bin(1)) # 0b1
print(bin(-1)) # -0b1
print(bin(10)) # 0b1010
print(bin(-10)) # -0b1010
print("{0:b}".format(10)) # 1010
print("{0:#b}".format(10)) # 0b1010 , with 0b prefix
print("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bits
print(format(10, "b")) # 1010
print(format(10, "#b")) # 0b1010, with 0b prefix
print(format(10, "b").zfill(16)) # 0000000000001010, pad zero, show 16 bits
# with hex, oct bin
# int: 10; hex: a; oct: 12; bin: 1010
result = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(10)
print(result)
# with 0x, 0o, or 0b as prefix:
# int: 10; hex: 0xa; oct: 0o12; bin: 0b1010
result = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(10)
print(result)
def generate_random_str(randomlength=16):
"""
生成一个指定长度的随机字符串
"""
str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
random_str = ''.join(str_list)
return random_str
def common_request(method, url, config={}):
response = session.request(method, url, json=config, headers=header)
print("\nstart################################################################################################start")
print("\n******************************[url]******************************\n", response.request.url)
print("\n*****************************[header]****************************\n", header)
if config:
print("\n*****************************[config]****************************\n", config)
print("\n*************************[response.header]***********************\n", response.headers)
print("\n***************************[status_code]**************************\n", response.status_code)
print("\n****************************[response]***************************\n", response.text)
print("\nend##################################################################################################end")
return response
如果 type(obj) 是<class NoneType>
if语句可以这么写:
if obj is None:
十进制转任意进制
def trans_map(cint):
# cint: int
# return: str
# 把数字转化为相应字符,比如10-a, 11-b
if cint < 0:
return None
elif cint < 10: # 数字转为字母
return str(cint)
elif cint >= 10: # ASCII码转为字母A-Z
return chr(cint - 10 + 65)
def tenToAny(n, origin):
# n进制: int
# origin: int
# return: str
res = ''
while origin:
res = trans_map(origin % n) + res # 需要逆序
origin = origin // n # 一定要整除,不然除3会进入死循环
return res
# 统计模式字符串出现了多少次(可重叠)
# 方案1,缺点是regex是第三方的模块
import regex as re
s=input()
t=input()
t_pattern=re.compile(t)
print(len(re.findall(t_pattern, s,overlapped=True)))
# 方案2,最朴素的做法,时间却是最省的,但是依然可能超时
def count_substrings(string, substring):
string_size = len(string)
substring_size = len(substring)
count = 0
for i in range(0,string_size-substring_size+1):
if string[i:i+substring_size] == substring:
count+=1
return count
s=input()
t=input()
print(count_substrings(s, t))
# 方案3,使用re模块把匹配位置也找到
import re
s=input()
t=input()
print([match.start() for match in re.finditer('(?=%s)' % t, s)])
######################################
# 统计模式字符串出现了多少次(不可重叠)
s=input()
t=input()
print(s.count(t))
```python3
# 建议熟背 最长公共子串和最长公共子序列的代码
# 最长公共子串
# 参考https://zhuanlan.zhihu.com/p/268342434
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n1=len(nums1)
n2=len(nums2)
dp=[[0 for i in range(1005)]for j in range(1005)]
ret=0
for i in range(1,n1+1):
for j in range(1,n2+1):
if i==0 or j==0:
dp[i][j]=0
else:
if nums1[i-1]==nums2[j-1]:
dp[i][j]=dp[i-1][j-1]+1
ret=max(ret,dp[i][j])
else:
pass
return ret
# 最长公共子序列
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# 这不是dp题目吗
n1=len(text1)
n2=len(text2)
dp=[[0 for i in range(n2+1)]for j in range(n1+1)]
for i in range(0,n1):
for j in range(0,n2):
if text1[i]==text2[j]:
dp[i+1][j+1]=dp[i][j]+1
else:
dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])
return (dp[-1][-1])
from queue import PriorityQueue
class DualPriorityQueue(PriorityQueue):
def __init__(self, maxPQ=False):
PriorityQueue.__init__(self)
self.reverse = -1 if maxPQ else 1
def put(self, priority, data):
PriorityQueue.put(self, (self.reverse * priority, data))
def get(self, *args, **kwargs):
priority, data = PriorityQueue.get(self, *args, **kwargs)
return self.reverse * priority, data
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param a int整型一维数组
# @param k int整型
# @param x int整型
# @return int整型
#
class Solution:
def minMax(self , a: List[int], k: int, x: int) -> int:
# write code here
pq=DualPriorityQueue(maxPQ=True)
for i in a:
pq.put(i,i)
for t in range(k):
if not pq.empty():
ele=pq.get()[1]
pq.put(ele-x,ele-x)
return pq.get()[1]
# pq.get()方法默认是取最小元素,
# 如果需要取最大元素,一种曲线救国方法是-1*元素插入队列
# 掌握PriorityQueue用法
# 贪心法,解决哈夫曼编码问题(合并果子问题)
from queue import PriorityQueue as PQ
pq = PQ()
cost=0
n=int(input())
a=list(map(int,input().split()))
for i in range(0,n):
pq.put(a[i])
while not pq.empty():
if pq.qsize()==1:
break
else :
a=pq.get()
b=pq.get()
cost=cost+a+b
pq.put(a+b)
print(cost)
from Queue import PriorityQueue
class DualPriorityQueue(PriorityQueue):
def __init__(self, maxPQ=False):
PriorityQueue.__init__(self)
self.reverse = -1 if maxPQ else 1
def put(self, priority, data):
PriorityQueue.put(self, (self.reverse * priority, data))
def get(self, *args, **kwargs):
priority, data = PriorityQueue.get(self, *args, **kwargs)
return self.reverse * priority, data
minQ = DualPriorityQueue()
maxQ = DualPriorityQueue(maxPQ=True)
minQ.put(10, 'A')
minQ.put(100, 'A')
maxQ.put(10, 'A')
maxQ.put(100,'A')
print "Min DQ: {}".format(minQ.get())
print "Max DQ: {}".format(maxQ.get())
# 统计1到2048出现多少次“1”
sum1=0;
for i in range(1,2048):
k=str(i)
sum1=sum1+k.count('1')
print(sum1)
# 统计n的二进制表示中有多少个1
n=int(input())
if n<0 :
n=n&0xffffffff
cnt = 0
while n:
cnt+=1
n=(n-1)&n
print(cnt)
# 句子反转 Hello World -> World Hello
s_input = input()
l_input = s_input.split(' ')
print(' '.join(l_input[::-1]))
# 斐波那契数
def fib_yield_for(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
yield a
# Generate the Fibonacci sequence up to the nth number
fib_sequence = list(fib_yield_for(n))
# 快速计算Fibonacci数,尤其是index为负数的情况
def fib(n):
"""Calculates the nth Fibonacci number using matrix exponentiation."""
def matrix_mult(A, B):
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
]
def matrix_pow(mat, exp):
result = [[1, 0], [0, 1]] # Identity matrix
base = mat
while exp > 0:
if exp % 2 == 1:
result = matrix_mult(result, base)
base = matrix_mult(base, base)
exp //= 2
return result
if n == 0:
return 0
elif n < 0:
# Use the property: F(-n) = (-1)^(n+1) * F(n)
return fib(-n) * (-1 if n % 2 == 0 else 1)
transformation_matrix = [[1, 1], [1, 0]]
result_matrix = matrix_pow(transformation_matrix, n - 1)
return result_matrix[0][0]
# Example usage
# print(fib(10)) # Output: 55
# 求整数的阶乘(高精度)
n=int(input())
ans=1;
for i in range(1,n+1,1):
ans*=i
print(ans)
# 求整数的阶乘
import math
print(math.factorial(30))
# 计算两个string类型的01串表示的二进制数相加的结果
return bin(int(a,2)+int(b,2))[2:]
# 拼接数字串得到最小的数
# 这份py代码思路是暴力,但是也能过。。。
# -*- coding:utf-8 -*-
import itertools
class Solution:
def PrintMinNumber(self, numbers):
# write code here
ret=[]
numbers=list(map(str,numbers))
mm=itertools.permutations(numbers)
for i in mm:
ret.append(''.join(i))
ret.sort()
return ret[0]
# 得到前k个单词的截断
class Solution(object):
def truncateSentence(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
a=list(s.split(" "))
b=a[0:k]
c=' '.join(b)
return c
# 读入一行不定个数整数
num=list(map(int,input().split()))
# Input a hexadecimal IPV6 address, store it into 4 integers and output them.
def trans(v):
if v&0x80000000 :
return v-4294967296
else :
return v
a=list(input().strip().split(':'))
for i in range(8):
a[i]=a[i].zfill(4)
print(trans( int((a[0]+a[1]),16) ),end=" ")
print(trans( int((a[2]+a[3]),16) ),end=" ")
print(trans( int((a[4]+a[5]),16) ),end=" ")
print(trans( int((a[6]+a[7]),16) ),end="\n")
# 给定n个字符串,请对n个字符串按照字典序排列
a=[]
n=int(input())
for i in range(0,n):
a.insert(-1,input())
a.sort()
for i in a:
print(i)
from decimal import Decimal
# 保留两位小数,并做四舍五入处理
def TwoDigits(a):
return Decimal(a).quantize(Decimal("0.00"))
# 判断一个全部由小写字母构成的字符串是否正好用了26个英文字母
# 练习python里的set用法
class Solution:
def checkIfPangram(self, sentence: str) -> bool:
s=set()
for i in sentence:
if not i in s:
s.add(i)
if len(s)==26:
return True
else :
return False
# 二分查找
import bisect
idx=bisect_left(a,x)
# 直接查找
idx=str_a.find(x)
看 https://www.php.cn/python-tutorials-424214.html
print("%.2f" % a) #四舍五入保留2位小数
# 四舍五入保留小数点后2位
print("{:.2f}".format(3.1495926))
# 四舍五入保留小数点后2位,带符号
print("{:+.2f}".format(3.1495926))
# python读文件,建议熟背
file_object = open('test.txt','r')
try:
# line可接收换行符
for line in file_object:
do_somthing_with(line)
finally: #做清尾工作
file_object.close()
# python和java都有垃圾回收机制,不需要程序员写资源释放代码
# 但是
# Python 垃圾回收机制,只能帮我们回收变量、类对象占用的内存,而无法自动完成类似关闭文件、数据库连接等这些的工作。
# finally代码块做清尾工作,一般来说总是执行
#当 try 块中代码发生异常,导致程序崩溃时,在崩溃前 Python 解释器也会执行 finally 块中的代码。
Pthon切片语法 https://zhuanlan.zhihu.com/p/79541418
简述python的垃圾回收机制
python的内存管理是通过引用计数+清理来完成的。因此python的垃圾回收机制,很大一部分主要是处理引用计数无法解决的循环引用。
1、标记清除算法:算法分为“标记”和“清除”两个阶段,首先标记所有需要回收的对象,在标记完成后统一回收所有被标记的对象。有两个不足:一是效率问题,标记和清除两个过程的效率都不高;另一个是空间问题,标记清除之后会产生大量不连续的内存碎片,空间碎片太多可能会导致以后在程序运行过程中需要分配较大对象时,无法找到足够的连续内存而不得不提前触发一次垃圾收集动作
2、复制算法:将内存分为两块,每次只使用其中的一块。当这一块内存用完了,就将还存活的对象复制到另一块上,然后再把已使用过的内存空间一次清理掉。这样使得每次都是对一整块内存回收,内存分配时候也不用考虑内存碎片等复杂情况,只要移动堆顶指针,按顺序分配即可,实现简单,运行高效。缺点是一次只能使用一部分内存,会有一些浪费。一般新生代会选择这种算法。
3、标记-整理算法:复制算法存在两个问题,1)会浪费50%的空间 2)如果被使用的内存中所有对象都100%存活的极端情况,就需要有额外的空间进行分配担保,因此老年代一般不能直接选用复制算法。有人提出了另外一种“标记-整理”(Mark-Compact)算法,标记过程仍然与“标记-清除”一样,后续步骤让所有存活的对象都向一端移动,然后直接清理掉端边界以外的内存。
4、分代回收算法:分代回收算法并没有什么新的思想,只是根据对象存活周期的不同将内存划分为几块。比如新生代和老年代,不同代使用不同的回收算法。比如新生代使用复制算法,而老年代使用标记-清除或标记-整理算法
python装饰器了解过吗?
装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。
概括的讲,装饰器的作用就是为已经存在的函数或对象添加额外的功能。