HackerRank python练习——Sequence Equation

Sequence Equation

题目链接

# 方法一
def permutationEquation1(p):    # 列表元素无重复值时,以列表值为键值
    p_dic = dict()    
    result = []
    
    for i in range(len(p)):
        p_dic[p[i]] = i + 1

    for i in range(1,len(p) + 1):
        p_y = p_dic[i]
        y = p_dic[p_y]
        result.append(y)
    return result
# 方法二
def permutationEquation2(p):    # 以索引值为键值
    p_dic = dict()
    py_y = []
    result = []
    
    for i in range(n):
        p_dic[i+1] = p[i]
    for i in range(1,n+1):
        for key,value in p_dic.items():
            if value == i:
                py_y.append(key)
    for i in py_y:
        for key,value in p_dic.items():
            if value == i:
                result.append(key)
    return result
# 方法三
def permutationEquation3(p):
    result = []
    for i in range(1,len(p)+1):
        py_y = p.index(i) + 1    # 当x = i时,p(y)的y值
        ppy_y = p.index(py_y) + 1    # 当p(y)=py_y,而p(p(y)=i时,p(p(y))的y值对应py_y在列表p里的索引值+1
        result.append(ppy_y)        
    return result   

你可能感兴趣的:(HackerRank练习)