练手编编程

1. 求一个数的阶乘

def factorial(n): 

    if n == 1:

        return 1

    else:

        return n * factorial (n-1)

2. 求任意输入字符的全排列

def permutation(xxs, y):

"""

: xxs: 已经排好的序列list,例如["ab", "ba"]

: y : 新添的元素,例如'c'

: return: yys: 新的序列list,例如["cab", "acb", "abc", "cba", "bca", "bac"]

    """

    yys = []

    for xx in xxs:

        for i in range(len(xx) + 1):

            yy = "{}{}{}".format(xx[:i], y, xx[i:])

            yys.append(yy)

    return yys

def full_permutation(s):

    yys = []

    if len(s) > 1: 

        yys = permutation(full_permutation(s[:-1], s[-1]))

    else:

        yys = [s]

    return yys

# Test

test_str = "abc"

new_str = full_permutation(test_str)

new_str结果 = ['cba', 'bca', 'bac', 'cab', 'acb', 'abc']

3. 求两个有序数列的并集

例如,A = [2, 4, 4, 6, 9], B = [4, 5, 7], 输出[2, 4, 5, 6, 7, 9]

注意A和B中可能会有重复元素

def union(A, B):

    C = []

    c = None

    cc = None    # Candidate of c

    ia, ib, ic = 0, 0, 0

    while (ia < len(A) and ib < len(B)):

        if A[ia] <= B[ib]:

            cc = A[ia]

            ia += 1

        else:

            cc = B[ib]

            ib += 1

    # 去重复

    if cc != c:

        c = cc

        C.append(c)

    # 看A或B是否还有残余

    if ia <= len(A):

        if A[ia] != c:

            c = A[ia]

            C.append(c)

        ia += 1

    elif ib <= len(B):

        if B[ib] != c: 

            c = B[ib]

            C.append(c)

    return C

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PYTHON-进阶-ITERTOOLS模块小结转自wklken:http://wklken.me/posts/20...
    C_Y_阅读 1,032评论 0 2
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,905评论 0 38
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,053评论 0 2
  • 感赏培姐!从我7月15号进着力点到今天,两个多月吧,我居然从对鸟类的抗拒、排斥、负面,到连续感赏了他12天! ...
    猫公主喵阅读 213评论 0 1
  • 前天才收到谷口先生的威尼斯和画集,结果昨天谷口先生就逝世了,真是说不出的震惊。 谷口先生的书就是他来过这世界最好的...
    zzpku阅读 600评论 4 6