Python 在问答频道中刷题积累到的小技巧(三)

简介: Python 在问答频道中刷题积累到的小技巧(三)

1. sum() 二维元组降维,本质就是多个元组也能相加。

>>> tpl = ( (1,2,3),(1,2) )
>>> sum(tpl,())
(1, 2, 3, 1, 2)
>>> sum(tpl,(0,))
(0, 1, 2, 3, 1, 2)
>>> tpl = ( (1,2,3),(4,5) )
>>> sum(tpl,())
(1, 2, 3, 4, 5)
>>> sum(tpl,(0,))  # 单元素元组要加逗号:(0,),否则 (0)==0
(0, 1, 2, 3, 4, 5)
>>> (1,2,3)+(4,5)
(1, 2, 3, 4, 5)
>>> (0,)+(1,2,3)+(4,5)
(0, 1, 2, 3, 4, 5)
>>> 



【实例】编写函数,接收数列,返回一个元组,其中第一个元素为所有参数的平均值,其他元素为所有参数中大于平均值的实数。


以下两个函数等价:

def func1(lst):
    t = sum(lst)/len(lst)
    return sum((tuple(i for i in lst if i>t),),(t,))
def func2(lst):
    t = sum(lst)/len(lst)
    return (t,)+tuple(i for i in lst if i>t)

相关阅读:上期第2点列表降维Python 在问答频道中刷题积累到的小技巧(二)_Hann Yang的博客-CSDN博客


2. '#'号输出日期短格式:'%Y-%#m-%#d' => '2022-6-6'。

附datetime.date常用属性及方法:

>>> import datetime as dt
>>> d = dt.date(2022,6,6)
>>> d.year
2022
>>> d.month
6
>>> d.day
6
>>> d.weekday()
0
>>> d.isoweekday()
1
>>> d.max
datetime.date(9999, 12, 31)
>>> d.min
datetime.date(1, 1, 1)
>>> d.ctime()
'Mon Jun  6 00:00:00 2022'
>>> d.timetuple()
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=157, tm_isdst=-1)
>>> d.strftime('%Y-%#m-%#d') #日期短格式
'2022-6-6'
>>> d.isoformat()
'2022-06-06'
>>> d.isocalendar()
(2022, 23, 1) #当年第23周第1天
>>> d.resolution
datetime.timedelta(days=1)
>>> d + dt.timedelta(2)
datetime.date(2022, 6, 8)
>>> d.toordinal()
738312
>>> d-d.min
datetime.timedelta(days=738311)
>>> d - dt.timedelta(d.toordinal()-1)
datetime.date(1, 1, 1)
>>> d.max-d
datetime.timedelta(days=2913747)
>>> dt.date(2023,1,1)-d
datetime.timedelta(days=209)
datetime.date(2022, 6, 6)
>>> d.replace(2023)
datetime.date(2023, 6, 6)
>>> d.replace(d.year,7)
datetime.date(2022, 7, 6)
>>> d.replace(d.year,d.month,8)
datetime.date(2022, 6, 8)
>>> d.replace(d.year,7,8)
datetime.date(2022, 7, 8)
>>> d.replace(2002,7,8)
datetime.date(2002, 7, 8)
>>> d
datetime.date(2022, 6, 6) #d未变更


3. 列表指定位置插入、替换或删除元素:lst[m:m] = [x] 。

>>> lst = [1,2,3,4,5]
>>> lst
[1, 2, 3, 4, 5]
>>> lst[3:3] = [0]
>>> lst
[1, 2, 3, 0, 4, 5]
>>> lst[3] = [0]  # 对比
>>> lst
[1, 2, 3, [0], 4, 5]
>>> lst[3:4] = [] # 删除索引为3的元素
>>> lst
[1, 2, 3, 4, 5]
>>> lst[3:3] = [] # 这样lst没有变动
>>> lst
[1, 2, 3, 4, 5]
>>> lst[3:3] = [6,7,8]
>>> lst
[1, 2, 3, 6, 7, 8, 4, 5]
>>> lst[3:6] = []  # 恢复原状
>>> lst
[1, 2, 3, 4, 5]
>>> lst[-1:] = [7,8,9] # 列表去尾相接
>>> lst
[1, 2, 3, 4, 7, 8, 9]
>>> lst[4:] = [5] # 恢复原状
>>> lst
[1, 2, 3, 4, 5]
>>> lst[1:4] = [0, 0, 0] # 替换
>>> lst
[1, 0, 0, 0, 5]
>>> lst[2:3] = [1, 1] # 替换+插入
>>> lst
[1, 0, 1, 1, 0, 5]
>>> lst.insert(3, 2) # 单个元素插入等价于 lst[3:3]=[2]
>>> lst
[1, 0, 1, 2, 1, 0, 5]
>>>
>>> lst = [*range(1,6)]
>>> lst[-1:] = range(1,6)[::-1] 
>>> lst
[1, 2, 3, 4, 5, 4, 3, 2, 1]
>>> lst[:4] = [] # 删除前面的字符
>>> lst
[5, 4, 3, 2, 1]



4. 多项式求和时循环变量设置成题目中的一致,只要照抄。

例1: 2/(1*3) - 3/(2*5) + 4/(3*7) - 5/(4*9) + ... +  (-1)^(n-1) * (n+1) / [ n*(2*n+1) ]

m = int(input())
s = 0 
for n in range(1,m+1):
    s += (-1)**(n-1) * (n+1) / ( n*(2*n+1) )
print(round(s, 4))



例2: 1 - 1/2! + 1/4! - 1/6! + ... + (-1)^(n-1)/(2n-2)!

m = int(input())
res, t = 1.0, 1
for n in range(1,m):
    t *= (2*n - 1) * n*2 //最后一项是(n-1),代入n*2即(2*n-2)
    res += (-1)**n/t
print(res)



5. 任意多个递增序列合并一个递增序列(非相加后排序)。

L0 = [3, 21, 24, 30, 36, 43, 46, 71, 82, 84, 96]
L1 = [7, 15, 22, 23, 32, 39, 41, 51, 74, 76, 87, 89]
L2 = [1, 18, 27, 31, 34, 35, 37, 48, 53, 57, 58, 81, 85, 97, 100]
L = [list(i) for i in (L0, L1, L2)]
res = []
while sum(map(lambda x:len(x),L)):
    t, dic = [], {}
    for i in range(len(L)):
        if L[i]:
            dic[L[i][0]] = i
            t.append(L[i][0])
    res.append(min(t))
    L[dic[min(t)]][:1] = []
print(res)



附录:

Help on class date in module datetime:
class date(builtins.object)
 |  date(year, month, day) --> date object
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(...)
 |      Formats self with strftime.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __reduce__(...)
 |      __reduce__() -> (cls, state)
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  ctime(...)
 |      Return ctime() style string.
 |  
 |  isocalendar(...)
 |      Return a 3-tuple containing ISO year, week number, and weekday.
 |  
 |  isoformat(...)
 |      Return string in ISO 8601 format, YYYY-MM-DD.
 |  
 |  isoweekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 1 ... Sunday == 7
 |  
 |  replace(...)
 |      Return date with new specified fields.
 |  
 |  strftime(...)
 |      format -> strftime() style string.
 |  
 |  timetuple(...)
 |      Return time tuple, compatible with time.localtime().
 |  
 |  toordinal(...)
 |      Return proleptic Gregorian ordinal.  January 1 of year 1 is day 1.
 |  
 |  weekday(...)
 |      Return the day of the week represented by the date.
 |      Monday == 0 ... Sunday == 6
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  fromisocalendar(...) from builtins.type
 |      int, int, int -> Construct a date from the ISO year, week number and weekday.
 |      
 |      This is the inverse of the date.isocalendar() function
 |  
 |  fromisoformat(...) from builtins.type
 |      str -> Construct a date from the output of date.isoformat()
 |  
 |  fromordinal(...) from builtins.type
 |      int -> date corresponding to a proleptic Gregorian ordinal.
 |  
 |  fromtimestamp(timestamp, /) from builtins.type
 |      Create a date from a POSIX timestamp.
 |      
 |      The timestamp is a number, e.g. created via time.time(), that is interpreted
 |      as local time.
 |  
 |  today(...) from builtins.type
 |      Current date or datetime:  same as self.__class__.fromtimestamp(time.time()).
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  day
 |  
 |  month
 |  
 |  year
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  max = datetime.date(9999, 12, 31)
 |  
 |  min = datetime.date(1, 1, 1)
 |  
 |  resolution = datetime.timedelta(days=1)
目录
相关文章
|
10月前
|
存储 索引 Python
Python小技巧:单下划线 '_' 原创
Python小技巧:单下划线 '_' 原创
135 3
|
11月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
231 2
|
8月前
|
自然语言处理 Python
使用Python和Qwen模型实现一个简单的智能问答Agent
使用Python和Qwen模型实现一个简单的智能问答Agent
758 4
|
10月前
|
开发者 索引 Python
7个提升python编程的小技巧
7个提升python编程的小技巧
109 1
7个提升python编程的小技巧
|
9月前
|
搜索推荐 Python
Leecode 101刷题笔记之第五章:和你一起你轻松刷题(Python)
这篇文章是关于LeetCode第101章的刷题笔记,涵盖了多种排序算法的Python实现和两个中等难度的编程练习题的解法。
88 3
|
10月前
|
开发工具 git Python
Python小技巧:满意的逗号放置
Python小技巧:满意的逗号放置
56 4
|
9月前
|
算法 C++ Python
Leecode 101刷题笔记之第四章:和你一起你轻松刷题(Python)
这篇博客是关于LeetCode上使用Python语言解决二分查找问题的刷题笔记,涵盖了从基础到进阶难度的多个题目及其解法。
84 0
|
9月前
|
算法 C++ Python
Leecode 101刷题笔记之第三章:和你一起你轻松刷题(Python)
本文是关于LeetCode算法题的刷题笔记,主要介绍了使用双指针技术解决的一系列算法问题,包括Two Sum II、Merge Sorted Array、Linked List Cycle II等,并提供了详细的题解和Python代码实现。
92 0
|
9月前
|
算法 C++ 索引
Leecode 101刷题笔记之第二章:和你一起你轻松刷题(Python)
本文是关于LeetCode 101刷题笔记的第二章,主要介绍了使用Python解决贪心算法题目的方法和实例。
77 0
|
10月前
|
存储 索引 Python
Python小技巧:单下划线 ‘_‘
Python小技巧:单下划线 ‘_‘
69 0

推荐镜像

更多