把一個Python程式改寫為Julia

lt發表於2017-05-08

Python

def f(m):
    if m < 3: return m
    k = 0
    # remainders[ r ] is the smallest n, which is composed from at most
    # k digits (0, 1, 2) and which satisfies n % m == r
    remainders = {0:0}
    best = None
    while best == None:
        k += 1
        for i in list(remainders.values()):
            for d in range(3):
                n = 10*i+d
                r = n % m
                if r not in remainders or n < remainders[ r ] :
                    remainders[ r ] = n
        # Find the smallest integer n with at most 2*k digits composed
        # from the digits 0, 1 and 2 which satisfies n % m == 0.
        mult = (-pow(10, k, m))%m
        for r in remainders:
            u = r * mult % m #;print(u)
            if u in remainders:
                n = 10**k * remainders[ r ] + remainders[ u ]
                if best == None or n < best:
                    if n != 0:
                      best = n
    return best

Julia

function f(m)
    if m < 3 return m end
    k = 0
    # remainders[ r ] is the smallest n, which is composed from at most
    # k digits (0, 1, 2) and which satisfies n % m == r
    remainders = Dict{Int,Int64}();remainders[0]=0
    max64=typemax(Int64)
    best = max64

    while best == max64 
        k += 1 

        rl=[i for (_,i) in remainders]
        for i in rl #remainders value list
            for d in 0:2
                n = Int64(10)*i+d
                r = n % m
                if get(remainders,r,-1)==-1 || n < remainders[ r ] 
                    remainders[ r ] = n
                end
            end
        end


        # Find the smallest integer n with at most 2*k digits composed
        # from the digits 0, 1 and 2 which satisfies n % m == 0.
        mult = (m-powermod(Int64(10), k, m))%m
        for (r,_) in remainders
            u = r * mult % m 
            if get(remainders,u,-1)>-1
                n = Int128(10)^k * remainders[ r ] + remainders[ u ]
                if best == max64 || n < best
                    if n != 0
                      best = n
                    end
                end
            end
        end #for

    end #while
    return best
end

程式碼行數增加了不少。主要是Julia需要end語句,還不支援None和value 語句,還有一個區別是取模運算的符號依賴於第一個運算元。所以,執行速度也變慢了。

PS:
在julia中也是有values的,還有一個keys

help?> values
search: values SSAValue

  values(a::Associative)

  Return an iterator over all values in a collection. collect(values(a))
  returns an array of values. Since the values are stored internally in a hash
  table, the order in which they are returned may vary. But keys(a) and
  values(a) both iterate a and return the elements in the same order.

  julia> a = Dict('a'=>2, 'b'=>3)
  Dict{Char,Int64} with 2 entries:
    'b' => 3
    'a' => 2

  julia> collect(values(a))
  2-element Array{Int64,1}:
   3
   2


  julia> collect(keys(a))
  2-element Array{Char,1}:
   'b'
   'a'

相關文章