zoukankan      html  css  js  c++  java
  • 巧妙变换

    题目分析来自“待字闺中”微博公众平台。

    一个数组,arr = ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4'],变换为:arr = ['a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'b4']

    第一次使用Python编写程序,肯定有许多不妥的地方。

    第一种方法:

    __author__ = 'ledao'
    
    arr = ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4']
    
    length = len(arr)
    halfLen = length/2
    counter = halfLen-1
    
    for i in xrange(halfLen, length-1):
    
        local_counter = counter
        counter -= 1
        if -1 == counter:
            break
        local_index = i
        while local_counter > 0:
            val = arr[local_index]
            arr[local_index] = arr[local_index-1]
            arr[local_index-1] = val
            local_index -= 1
            local_counter -= 1
    
    print arr
    

     第二种方法:

    __author__ = 'ledao'
    
    arr = ['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'b5']
    
    length = len(arr)
    halflen = length/2
    
    for i in xrange(1, halflen):
        for j in xrange(0, i):
            local_val = arr[halflen+i-1-2*j]
            arr[halflen+i-1-2*j] = arr[halflen+i-1-2*j-1]
            arr[halflen+i-1-2*j-1] = local_val
    
    print arr
    

     第三种方法:

    __author__ = 'ledao'
    
    arr = ['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'b5']
    
    def finalIndex(old_index, halflen):
        return (2*old_index)%(2*halflen-1)
    
    length = len(arr)
    modified = ['False']*length
    
    for i in xrange(0,length-1):
        if modified[i] == 'False':
            firstIndex = i
            stored_val = arr[firstIndex]
            while True:
                local_value = stored_val
                if modified[firstIndex] == 'False':
                    modified[firstIndex] = 'True'
                else:
                    break;
                local_finalIndex = finalIndex(firstIndex, length/2)
                stored_val = arr[local_finalIndex]
                arr[local_finalIndex] = local_value
                firstIndex = local_finalIndex
    
    print arr
    

     第四种方法由于水平有限,没看懂……T-T,讲解连接如下,请教高手!

    http://www.newsmth.net/bbscon.php?bid=1032&id=47005

  • 相关阅读:
    HDU4507 吉哥系列故事――恨7不成妻(数位dp)
    UCF Local Programming Contest 2017 G题(dp)
    ICPC Latin American Regional Contests 2019 I题
    UCF Local Programming Contest 2017 H题(区间dp)
    HDU2089 不要62
    AcWing1084 数字游戏II(数位dp)
    UCF Local Programming Contest 2017 F题(最短路)
    Google Code Jam 2019 Round 1A Pylons(爆搜+贪心)
    AcWing1083 Windy数(数位dp)
    Vue
  • 原文地址:https://www.cnblogs.com/ledao/p/3620450.html
Copyright © 2011-2022 走看看