Re: [问题] 排列组合只取一半

楼主: cutekid (可爱小孩子)   2017-08-22 17:46:36
def middle_permutation(string):
arr = sorted(list(string))
arrLen = len(arr)
half = (arrLen - 1) // 2
if(arrLen % 2):
ans = arr.pop(half) + arr.pop(half - 1)
else:
ans = arr.pop(half)
return ans + ''.join(reversed(arr))
※ 引述《ptt0720 (湿湿)》之铭言:
: ※ 引述《uranusjr (←这人是超级笨蛋)》之铭言:
: : 推文有提到递回方法
: : 不过 CPython 对递回支援那么差我猜一定爆炸慢, 就不管了
: : 解释一下用 next 的做法
: : itertools.permutations 是回传一个 permutation iterator
: : 而 Python 内建的 next() 函式可以得到一个 iterator 的“下一个”结果
: : 当你对 iterator 做 for 运算时, Python 其实也就是不断取得下一项
: : 所以像下面的程式
: : for i in iter('abc'):
: : print(i)
: : 可以大概翻译成
: : it = iter('abc')
: : try:
: : while True:
: : i = next(it)
: : print(i)
: : except StopIteration: # 代表没有下一个了
: : pass
: : 那所以你就可以这样找到中间项, 而避免执行整个 iterator
: : perm_it = itertools.permutations(input_value)
: : for _ in range(中间项的位置):
: : next(perm_it)
: : print('item in the middle:', next(perm_it))
: : 好那下一个问题就是要怎么知道中间项的位置
: : 幸好 permutation 的数量有公式解
: : Python 没有 product 函式 (如果有 numpy 就简单了)
: : 所以你得自己算
: : permutation_count = 1
: : for i in range(1, len(input_value) + 1):
: : permutation_count *= i
: : 中间项的位置就是 permutation_count // 2 - 1
: 感谢您的解释 算是稍微了解迭代器(iterator)的运作方式了
: 我也把code改成这样
: http://i.imgur.com/40wI9d8.png
: 但送出之后 系统还是觉得我的运算时间太长了
: 我也直接把题目po出来 希望能够抛砖引玉囉
: https://www.codewars.com/kata/simple-fun-number-159-middle-permutation/train/python

Links booklink

Contact Us: admin [ a t ] ucptt.com