裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

簡単なプログラミング問題を Julia で解く

2021年01月25日 | ブログラミング

以下では Python の解答例が示されているので,Julia でやったらどうなるか書いてみた。

10 Algorithms To Solve Before your Python Coding Interview

関数として定義したが,一般的に Python よりは短く簡潔に書ける。

1. Reverse Integer

Given an integer, return the integer with reversed digits. 
Note: The integer could be either positive or negative.

func1(x) = (x < 0 ? "-" : "") * reverse(string(abs(x)))

println(func1(-123))
println(func1(123))

-321
321

2. Average Words Length

For a given sentence, return the average word length. Note: Remember to
remove punctuation first.

たかが mean() を使うだけで using Statistics するのは,大げさだなあ。

using Statistics
func2(sentence) = mean(length.(split(replace(sentence, r"[!?':,,.]" => ""))))

sentence1 = "Hi all, my name is Tom... I am originally from Australia."
sentence2 = "I need to work very hard to learn more about algorithms in Python!"
println(func2(sentence1))
println(func2(sentence2))

3.8181818181818183
4.076923076923077

3. Add Strings

Given two non-negative integers num1 and num2 represented as string,
return the sum of num1 and num2. You must not use any built-in
BigInteger library or convert the inputs to integer directly. Notes:
Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not
contain any leading zero

func3(a, b) = parse(Int, a) + parse(Int, b)

num1 = "364"
num2 = "1836"
println(func3(num1, num2))

2200

4. First Unique Character

Given a string, find the first non-repeating character in it and return
its index. If it doesn’t exist, return -1. Note: all the input strings
are already lowercase.

function func4(s)
    t = split(s, "")
    for i in 1:length(t)
        if count(t .t[i]) 1
            return i
        end
    end
    return -1
end

println(func4("alphabet")) # Julia では,文字位置は1から数える
println(func4("barbados"))
println(func4("ppaap"))

2
3
-1

5. Valid Palindrome

Given a non-empty string s, you may delete at most one character. Judge
whether you can make it a palindrome. The string will only contain
lowercase characters a-z.

function func5(s)
    len = length(s)
    for i = 1:len
        t = s[1:i-1] * s[i+1:len]
        if t reverse(t)
            return true
        end
    end
    return false
end

s = "radkar"
println(func5(s))
println(func5("abcde"))

true
false

6. Monotonic Array

Given an array of integers, determine whether the array is monotonic or
not.

func6(x) = x sort(x) || x sort(x, rev=true)

println(func6([6, 5, 4, 4]))
println(func6([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]))
println(func6([1, 1, 2, 3, 7]))

true
false
true

7. Move Zeroes

Given an array nums, write a function to move all zeroes to the end of
it while maintaining the relative order of the non-zero elements.

発想の転換をすれば,解は簡単に求まる。

function func7(x)
    a = [i for i in x if i != 0]
    append!(a, repeat([0], count(x .0)))
    return a
end

array1 = [0,1,0,3,12]
println(func7(array1))
array2 = [1,7,0,0,8,0,10,12,0,4]
println(func7(array2))

[1, 3, 12, 0, 0]
[1, 7, 8, 10, 12, 4, 0, 0, 0, 0]

8. Fill The Blanks

Given an array containing None values fill in the None values with most
recent non None value in the array.

Julia に None はないので,NaN に置き換えて考える。

function func8(x)
    for i in 2:length(x)
        if isnan(x[i])
            x[i] = x[i-1]
        end
    end
    x
end

array1 = [1,NaN,2,3,NaN,NaN,5,NaN];
println(func8(array1))

[1.0, 1.0, 2.0, 3.0, 3.0, 3.0, 5.0, 5.0]

9. Matched & Mismatched Words

Given two sentences, return an array that has the words that appear in
one sentence and not the other and an array with the words in common.

function func9(a, b)
    a = Set(split(a, " "))
    b = Set(split(b, " "))
    sort([i for i in union(a, b)]), sort([i for i in intersect(a, b)])
end

sentence1 = "We are really pleased to meet you in our city"
sentence2 = "The city was hit by a really heavy storm"
u, i = func9(sentence1, sentence2)
println(u)
println(i)

SubString{String}["The", "We", "a", "are", "by", "city", "heavy", "hit", "in", "meet", "our", "pleased", "really", "storm", "to", "was", "you"]
SubString{String}["city", "really"]

10. Prime Numbers Array

Given k numbers which are less than n, return the set of prime number
among them Note: The task is to write a program to print all Prime
numbers in an Interval. Definition: A prime number is a natural number
greater than 1 that has no positive divisors other than 1 and itself.

参照先の解答例は n 以下の素数リストを求めるだけのものだけど,ちょっと違うんじゃないか?

function func10(k)
    n = maximum(k)
    primes = [2]
    for i = 3:2:n
        isprime = true
        for j = 2:floor(Int, sqrt(i))
            if mod(i, j) 0
                isprime = false
                break
            end
        end
        if isprime
            append!(primes, i)
        end
    end
    sort([s for s in intersect(Set(k), Set(primes))])
end

n 以下の値の k 個の数のリストから,素数のみから成るリストを求めよ

k = [2, 1, 3, 4, 3, 7, 13, 18, 27, 35]
func10(k)

  2
  3
  7
 13

コメント    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« Julia で R の deparse() み... | トップ | みんな大好き,Julia の速度自慢 »
最新の画像もっと見る

コメントを投稿

ブログラミング」カテゴリの最新記事