當前位置:首頁 » 編程語言 » 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

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

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:711
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:973
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:684
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:836
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:742
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1083
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:313
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:193
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:881
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:839