當前位置:首頁 » 編程語言 » python排列組合函數

python排列組合函數

發布時間: 2025-08-11 12:54:03

⑴ 如何用python列出N個數字的所有排列組合

>> from itertools import combinations, permutations
>> permutations([1, 2, 3], 2)
<itertools.permutations at 0x7febfd880fc0>
# 可迭代對象
>> list(permutations([1, 2, 3], 2)) #排列
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
>> list(combinations([1, 2, 3], 2)) #組合
[(1, 2), (1, 3), (2, 3)]

⑵ Python實現,輸入一個正整數數組,把數組里所有數字拼接起來排成一個數,列印能拼接

你的例子第一列全是 3,我給個例子吧:[321, 32, 3, 4],輸出該是 321,32,3,4。

第一個數越大,則應該排在後面,畢竟 4XXX 是比 3XXX 大的。

setp1:[0][1][2]
321
32
3
4
排序第0列,越大的排越後。
ret=[?,?,?,4]

setp2:[0][1][2]
321
32
3<3><-補位3,因為3是同3組第一個元素。
排序第1列,越大的排越後。
ret=[?,?,3,4]

setp3:[0][1][2]
321
32<3><-補位3,因為3是同3組第一個元素。
排序第2列,越大的排越後。323比321大,所以……
ret=[?,32,3,4]

只剩一個,那個排第一:
ret=[321,32,3,4]

以上就是基本思路了。綜上可得:

1. 先按 [0] 列分組:

2. 組中每個數都補位到同樣長度,然後再排序。

完整代碼:

defjoinmin(ls):
groups={}
foriteminls:
prefix=item
n=0
whileprefix>10:
prefix//=10
n+=1
groups.setdefault(prefix,[]).append([item,n])
sorted_keys=list(sorted(groups))
ret=0
forprefixinsorted_keys:
items=groups[prefix]
max_n=max([t[1]fortinitems])
presort_items=[]
foritem,item_ninitems:
padding=item
n=item_n
whilemax_n>n:
padding*=10
padding+=prefix
n+=1
presort_items.append((padding,item,item_n))
for_,item,ninsorted(presort_items):
whilen>-1:
ret*=10
n-=1
ret+=item
returnret

不是看在你的分上答的,不過這種小題目蠻有趣的。

熱點內容
壓縮機滲油 發布:2025-08-11 16:56:06 瀏覽:316
手機2g配置能玩什麼游戲 發布:2025-08-11 16:46:32 瀏覽:468
不適合編程 發布:2025-08-11 16:46:31 瀏覽:924
wdcpphp版本 發布:2025-08-11 16:44:05 瀏覽:542
我的世界進入忍者伺服器 發布:2025-08-11 16:36:43 瀏覽:66
怎麼隱藏u盤里的文件夾 發布:2025-08-11 16:09:31 瀏覽:778
小鵬特斯拉比亞迪哪個配置高 發布:2025-08-11 16:08:36 瀏覽:193
相機相片存儲 發布:2025-08-11 16:06:17 瀏覽:667
安卓機怎麼拍出高清視頻 發布:2025-08-11 15:55:52 瀏覽:332
staticlinux 發布:2025-08-11 15:51:37 瀏覽:58