LoginSignup
12
4

More than 5 years have passed since last update.

100 numpy exercises in Julia v0.6.2

Posted at

まだ全部終わってないんですが、疲れてしまったので途中で公開してしまいます。
100 julialang exercisesを見て面白そうだったので、自分もやってみました。編集リクエストも考えたのですが、上記の記事の頃に比べて元ネタ(100 numpy exercises)に問題が追加されているのと、上記の記事がJulia v0.4時代のものでいろいろと変更が必要な部分があったので、新たに記事を起こしました。@chezouさんの回答そのままのものもたくさんあります。
Julia v0.6.2で確認しています。

軽い気持ちで始めたのですが、かなり疲れました。。(上記の記事のころから新たな問題がたくさん追加されています。)
途中ですが、ギブアップして公開してしまいます。
問題文に(未)とあるのは、まだできていない問題です。

気が向いたら、今後、残った問題を少しずつやろうと思っています。
変なところを見つけた方や、残っている問題をやってみたという方は、コメントなり編集リクエストなりしてください。よろしくお願いします。

1. Import the numpy package under the name np (★☆☆)

1. numpyパッケージを名前npでインポートする (★☆☆)

# nothing to do

2. Print the numpy version and the configuration (★☆☆)

2. バージョンと詳細な環境を表示する (★☆☆)

println(VERSION)
versioninfo(true)

3. Create a null vector of size 10 (★☆☆)

3. サイズが10のゼロベクトルを作成 (★☆☆)

Z = zeros(10)

# without initialization
# ゼロ初期化が必要ない場合
Z = Vector{Float64}(10)

4. How to find the memory size of any array (★☆☆)

4. 配列のメモリ上のサイズを得る (★☆☆)

Z = zeros(10, 10)
@printf("%d bytes\n", sizeof(Z))

5. How to get the documentation of the numpy add function from the command line? (★☆☆)

5. コマンドラインから加算演算子のドキュメントを表示する (★☆☆)

%run `julia -e "print(@doc +)"`

6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)

6. サイズ10のゼロベクトル(ただし、5番目の要素のみ1)を作成 (★☆☆)

Z = zeros(10)
Z[5] = 1

# another solution
Z = @. ifelse(1:10 == 5, 1, 0)

7. Create a vector with values ranging from 10 to 49 (★☆☆)

7. 10から49までの連続値のベクトルを作成 (★☆☆)

Z = collect(10:49)

# another solition
Z = range(10, 40)

# obtains Float64 vector
# 浮動小数点数のベクトルが欲しい場合
Z = collect(10.0:49)
# or
Z = range(10.0, 40)

8. Reverse a vector (first element becomes last) (★☆☆)

8. ベクトルを反転する (最初の要素が最後になるように) (★☆☆)

Z = collect(0:49)
reverse!(Z)

# straightforward method
# 直接的な方法
Z = collect(0:49)
Z = Z[end:-1:1]

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

9. 0から8までの連続値を格納する 3x3 行列を作成 (★☆☆)

Z = reshape(0:8, 3, 3)

10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

10. [1,2,0,0,4,0] の非ゼロ要素の番号を取得 (★☆☆)

nz = find([1, 2, 0, 0, 4, 0])

11. Create a 3x3 identity matrix (★☆☆)

11. 3x3 の単位行列を作成 (★☆☆)

Z = eye(3)

# using UniformScaling
Z = zeros(3, 3) + I

12. 3x3x3 次元のランダム配列を作成 (★☆☆)

Z = rand(3, 3, 3)

13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

13. 10x10 のランダム配列を作成し、最大値と最小値を得る (★☆☆)

Z = rand(10, 10)
Zmin, Zmax = extrema(Z)
@show (Zmin, Zmax)

14. Create a random vector of size 30 and find the mean value (★☆☆)

14. 30要素のランダムベクトルを作成し、平均値を計算する (★☆☆)

Z = rand(30)
m = mean(Z)
@show m

15. Create a 2d array with 1 on the border and 0 inside (★☆☆)

15. 外周では値1、内部では値0をとる2次元配列を作成する (★☆☆)

Z = ones(10, 10)
Z[2:end-1, 2:end-1] .= 0

# using comprehension
# 内包表記の利用
Z = [ifelse(all(1 .< (i,j) .< 10), 0, 1) for i in 1:10, j in 1:10]

16. How to add a border (filled with 0's) around an existing array? (★☆☆)

16. 既存の行列の周囲を1列ずつ拡張する (0で埋める) (★☆☆)

Z = ones(5, 5)

Z2 = zeros(eltype(Z), size(Z) .+ 2)
Z2[2:end-1, 2:end-1] = Z
@show Z2

# another solution
Z2 = [checkbounds(Bool, Z, i, j) ? Z[i, j] : zero(eltype(Z)) for i in 0:size(Z, 1)+1, j in 0:size(Z, 2)+1]
@show Z2

17. What is the result of the following expression? (★☆☆)

17. 以下を実行した結果は? (★☆☆)

println(0 * NaN)         # => NaN
println(NaN == NaN)      # => false
println(Inf > NaN)       # => false
println(NaN - NaN)       # => NaN
println(0.3 == 3 * 0.1)  # => false

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)

18. 対角要素の1つ下に1,2,3,4が並ぶ5x5行列を作成する (★☆☆)

Z = diagm(1:4, -1)

19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)

19. 市松模様に初期化された8x8行列を作成 (★☆☆)

Z = [(i + j) % 2 for i in 1:8, j in 1:8]

20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?

20. サイズが(6,7,8)の配列を考える。100番目の要素のインデックス(x,y,z)は?

println(ind2sub((6, 7, 8), 100))

21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)

21. tile関数を利用して市松模様の8x8行列を作成 (★☆☆)

# numpy's tile equal to repmat
Z = repmat([0 1; 1 0], 4, 4)

22. Normalize a 5x5 random matrix (★☆☆)

22. 5x5のランダム行列を正規化する (★☆☆)

Z = rand(5, 5)
Zmax, Zmin = extrema(Z)
@. Z = (Z - Zmin) / (Zmax - Zmin)
@show Z

23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)

23. 4個の符号なしバイト(RGBA) で構成されるカスタムdtypeを作成する (★☆☆)

# composite type
mutable struct Color
    R::UInt8
    G::UInt8
    B::UInt8
    A::UInt8
end

# immutable composite type
# 変更不可能な型
struct Color
    R::UInt8
    G::UInt8
    B::UInt8
    A::UInt8
end

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)

24. 5x3行列と3x2行列の乗算する (行列の乗算) (★☆☆)

Z = ones(5, 3) * ones(3, 2)

25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)

25. 与えられた1次元配列の3より大きく8以下の要素の符号を反転させる(★☆☆)

Z = collect(1:10)
@. Z = flipsign(Z, ifelse(3 .< Z .≤ 8, -1, 1))
@show Z

26. What is the output of the following script? (★☆☆)

# skip

27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)

27. Zが整数であるとき下のうち正当(エラーにならない)な文は? (★☆☆)

# all of these expression are legal.
# 全て正当(エラーにならない)文です。
Z^Z
2 << Z >> 2
Z <- Z
1im*Z
Z/1/1
Z<Z>Z

28. What are the result of the following expressions?

0.0 / 0.0 # => NaN
0 / 0 #     => NaN

29. How to round away from zero a float array ? (★☆☆)

29. 実数値の配列を絶対値が大きくなる方向に丸めて整数にする (★☆☆)

# using Distributions package in order to create uniformly distributed random number
# 一様分布の乱数を生成するためにDistributionsパッケージを使っています。
using Distributions
Z = rand(Uniform(-10, 10), 10)
@. Z = copysign(ceil(abs(Z)), Z)
@show Z

# another solution
using Distributions
Z = rand(Uniform(-10, 10), 10)
@. Z = ifelse(Z > 0, ceil(Z), floor(Z))
@show Z

30. How to find common values between two arrays? (★☆☆)

30. 2つの配列の共通要素を取得する (★☆☆)

Z1 = rand(1:10, 10)
Z2 = rand(1:10, 10)
@show unique(Z1  Z2)

# using Set
@show collect(Set(Z1)  Set(Z2))

(未)31. How to ignore all numpy warnings (not recommended)? (★☆☆)

# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

# Back to sanity
_ = np.seterr(**defaults)

An equivalent way, with a context manager:

with np.errstate(divide='ignore'):
    Z = np.ones(1) / 0

32. Is the following expressions true? (★☆☆)

32. 以下の式はtrueか? (★☆☆)

sqrt(-1) == sqrt(complex(-1))  ## in Julia, sqrt(-1) raises DomainError

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)

33. 昨日、今日、明日の日付を取得する (★☆☆)

yesterday = Date(now()) - Dates.Day(1)
today     = Date(now())
tomorrow  = Date(now()) + Dates.Day(1)

34. How to get all the dates corresponding to the month of July 2016? (★★☆)

34. 2016年7月の日付を全て取得する (★★☆)

Z = collect(Date("2016-07"):Dates.Day(1):Date("2016-08"))[1:end-1]

35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)

35. ((A+B)*(-A/2)) をその場で (コピーしないで) 計算する? (★★☆)

A = ones(3)
B = fill(2.0, 3)
@. A = (A + B) * (-A / 2)

36. Extract the integer part of a random array using 5 different methods (★★☆)

36. ランダム実数値配列の、整数部分を5つの異なる方法で取得する (★★☆)

using Distributions
Z = rand(Uniform(0, 10), 10)
@show floor.(Z)
@show floor.(Int, Z)
@show @. Z - mod1(Z, 1)
@show @. ceil(Z) - 1
@show trunc.(Z)

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

37. 各行が0から4までの連続値である5x5行列を作成する (★★☆)

Z = zeros(5, 5)
Z .= (0:4)'
@show Z

# another solution
Z = repmat((0:4)', 4)
@show Z

# another solution using broadcast syntax
# broadcast構文を用いた方法
Z = zeros(5) .+ (0:4)'
@show Z

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

38. 10個の整数を生成する生成関数を作成し、それを用いて配列を得る (★☆☆)

function generate()
    Channel(ctype=Int) do ch
        for i in 1:10
            put!(ch, i)
        end
    end
end

Z = collect(generate())
@show Z

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

39. 0から1の範囲を等分するサイズ10のベクトルを作成する。ただし、両端(0と1)を除く (★★☆)

Z = linspace(0, 1, 12)[2:end-1]
@show Z

40. Create a random vector of size 10 and sort it (★★☆)

40. サイズ10のランダムベクトルを整列する (★★☆)

Z = rand(10)
sort!(Z)
@show Z

41. How to sum a small array faster than np.sum? (★★☆)

# skip

42. Consider two random array A and B, check if they are equal (★★☆)

42. 2つの乱数配列A, Bが等しいか判定する (★★☆)

A = rand(0.0:1, 5)  # Float64 array
B = rand(0.0:1, 5)  # Float64 array

# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = A  B
@show equal

# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = A == B
@show equal

43. Make an array immutable (read-only) (★★☆)

43. 配列を不変(書き換え不可)にする (★★☆)

# tuple acts (almost) like immutable vector

# Slow
Z = zeros(10)
Z = (Z...)
Z[1] = 1 # error

# Fast
Z = zeros(10)
Z = ntuple(i->Z[i], length(Z))
Z[1] = 1 # error

44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)

44. 直交座標の点を表す10x2の乱数行列を、極座標に変換する (★★☆)

Z = rand(10,2)
@views X, Y = Z[:, 1], Z[:,2]  # use view to avoid copy
R = hypot.(X, Y)
T = atan2.(Y, X)
@show R
@show T

45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)

45. サイズ10の乱数ベクトルを生成し、最大値を0に置換する(★★☆)

Z = rand(100)
Z[indmax(Z)] = 0
@show Z

46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)

46. [0,1]x[0,1]の範囲で、x and y 座標を表す構造化された配列のグリッドを作成する(★★☆)

struct Point
  x::Float64
  y::Float64
end
Z = [Point(x, y) for x in linspace(0,1,10), y in linspace(0,1,10)]
@show Z

47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))

47. 2つの配列X, Yからコーシー行列 Cを作成する (ただし、Cij =1/(xi - yj))

X = collect(0:7)
Y = X + 0.5
C = @. 1 / (X - Y')
@show det(C)

48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)

48. それぞれのnumpyのスカラー型が表現可能な最大の値と最小の値を表示する (★★☆)

for dtype in (Int8, Int16, Int32, Int64)
    println(typemin(dtype))
    println(typemax(dtype))
end
for dtype in (Float32, Float64)
    println(typemin(dtype))
    println(typemax(dtype))
    println(eps(dtype))
end

49. How to print all the values of an array? (★★☆)

49. 配列のすべての値を表示する (★★☆)

Z = zeros(16, 16)
showall(Z)

50. How to find the closest value (to a given scalar) in a vector? (★★☆)

50. ベクトルから与えられた値に最も近い値を取り出す (★★☆)

using Distributions
Z = 1:100
V = rand(Uniform(1, 100))
println(Z[indmin(abs.(Z .- V))])

51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)

51. 位置(x,y)と色(r,g,b)を表す構造化配列を作成する (★★☆)

struct Position
    x::Float64
    y::Float64
end
struct Color
    r::Float64
    g::Float64
    b::Float64
end
struct Point
    position::Position
    color::Color
end
Z = map(_->Point(Position(0,0), Color(0,0,0)), 1:10)
@show Z

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)

52. 座標を表す(100,2)の乱数配列から、全ての点の間の距離を計算する (★★☆)

Z = rand(10, 2)
X, Y = @views Z[:, 1], Z[:, 2]
D = @. hypot(X - X', Y - Y')
@show D

53. How to convert a float (32 bits) array into an integer (32 bits) in place?

53. 浮動小数点(32ビット)の配列を、その場で整数(32ビット)の配列に変換する

Z = convert(Vector{Float32}, 0:9)

Z2 = reinterpret(Int32, Z)
Z2 .= Z
@assert pointer(Z) == pointer(Z2)
@show Z2

(未)54. How to read the following file? (★★☆)

from io import StringIO

# Fake file 
s = StringIO("""1, 2, 3, 4, 5\n
                6,  ,  , 7, 8\n
                 ,  , 9,10,11\n""")
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
@show Z

55. What is the equivalent of enumerate for numpy arrays? (★★☆)

55. numpy配列のenumerateアクセス (★★☆)

Z = reshape(1:9, 3, 3)
for (index, value) in enumerate(Z)
    println("$index $value $(Z[index])")
end
for (index, value) in enumerate(IndexCartesian(), Z)
    println("$index $value")
end

56. Generate a generic 2D Gaussian-like array (★★☆)

56. 2次元のガウス分布(係数をのぞく)の配列を作成する (★★☆)

X, Y = linspace(-1, 1, 10), linspace(-1, 1, 10)
σ, μ = 1.0, 0.0

# using broadcast
G = @. exp(-(abs2(X - μ) + abs2(Y' - μ)) / 2σ^2)
@show G

# using comprehension
G = [ exp(-sum(abs2, (x, y) .- μ) / 2σ^2) for x in X, y in Y]
@show G

57. How to randomly place p elements in a 2D array? (★★☆)

57. 2次元配列にp個の要素をランダムに配置する (★★☆)

n = 10
p = 3

using StatsBase
Z = zeros(n, n)
Z[sample(eachindex(Z), p, replace=false)] .= 1
@show Z

58. Subtract the mean of each row of a matrix (★★☆)

58. 配列から各行の平均値を差し引く (★★☆)

X = rand(5, 10)
Y = X .- mean(X, 1)
@show Y

59. How to I sort an array by the nth column? (★★☆)

59. 行列の各行をn番目の列をキーとして整列する (★★☆)

Z = rand(0:9, 3, 3)
n = 2
@show Z
@show sortrows(Z, by=row->row[n])

60. How to tell if a given 2D array has null columns? (★★☆)

60. 与えられた2次元配列に、値がすべてゼロの列があるか判定する (★★☆)

Z = rand(0:2, 3, 10)
println(any(all(iszero, Z, 1)))

61. Find the nearest value from a given value in an array (★★☆)

61. 配列から与えられた値に最も近い値を取り出す (★★☆)

Z = rand(10, 10)
z = 0.5
m = Z[indmin(abs.(Z - z))]
@show m

(未)62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)

A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])

63. Create an array class that has a name attribute (★★☆)

class NamedArray(np.ndarray):
    def __new__(cls, array, name="no name"):
        obj = np.asarray(array).view(cls)
        obj.name = name
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
        self.info = getattr(obj, 'name', "no name")

Z = NamedArray(np.arange(10), "range_10")
print (Z.name)

(未)64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)

# Author: Brett Olsen

Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
print(Z)

# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z, I, 1)
print(Z)

65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)

65. インデックスリストIのもとでベクトルXの要素を加算する(★★★)

X = [1, 2, 3, 4, 5, 6]
I = [1, 3, 9, 3, 4, 1]
F = zeros(Int, maximum(I))
foreach((i,x) -> F[i] += x, I, X)
@show F

# another solution (using StatsBase)
using StatsBase
X = [1, 2, 3, 4, 5, 6]
I = [1, 3, 9, 3, 4, 1]
F = counts(I, maximum(I), Weights(X))
@show F

(未)66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)

# Author: Nadav Horesh

w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print(np.unique(I))

67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)

67. 4次元配列の後ろの2つの次元についての和を計算する (★★★)

A = rand(1:10, 3, 4, 3, 4)
last2dims = ndims(A)-1, ndims(A)
sum2 = squeeze(sum(A, last2dims), last2dims)

(未)68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)

# Author: Jaime Fernández del Río

D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)

# Pandas solution as a reference due to more intuitive code
import pandas as pd
print(pd.Series(D).groupby(S).mean())

69. How to get the diagonal of a dot product? (★★★)

69. 行列の積の対角要素を取得する (★★★)

A = rand(5, 5)
B = rand(5, 5)

# Slow (Straightforward)
diag(A * B)

# Fast version
sum(A .* B', 2)

# using Einsum
using Einsum
@einsum C[i] := A[i, j] * B[j, i]

70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros q1 interleaved between each value? (★★★)

70. ベクトル [1, 2, 3, 4, 5]から、各要素の間に3個のゼロを挿入した新しいベクトルを作成する (★★★)

Z = [1, 2, 3, 4, 5]
nz = 3
Z0 = zeros(eltype(Z), length(Z) + (length(Z)-1)*nz)
Z0[1:nz+1:end] = Z
@show Z0

# another solution
Z0 = reshape([Z repmat(zero(Z), 1, nz)]', :)

71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)

71. 次元が(5,5,3)の配列に、次元が(5,5)の配列を(要素毎に)乗算する (★★★)

A = ones(5, 5, 3)
B = 2*ones(5,5)
@show A .* B

(未)72. How to swap two rows of an array? (★★★)

# Author: Eelco Hoogendoorn

A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print(A)

73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)

73. それぞれ3点で構成される10個の三角形を考える。全ての三角形を構成する線分を重複をのぞいて得る (★★★)

faces = rand(1:100, 10, 3)
F = circshift(repeat(faces, inner=(1,2)), (0,-1))
F = reshape(F', 2, :)
G = unique(extrema(F, 1))
@show G

(未)74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)

# Author: Jaime Fernández del Río

C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
print(A)

75. How to compute averages using a sliding window over an array? (★★★)

75. 配列の移動平均を計算する (★★★)

moving_average(a, n) = @views cumsum(vcat(sum(a[1:n]), a[n+1:end] - a[1:end-n]))/n
Z = collect(0:19)
@show moving_average(Z, 3)

76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)

rolling(a, window) = a[(1:window)' .+ (0:length(a)-window)]
Z = rolling(1:9, 3)
@show Z

77. How to negate a boolean, or to change the sign of a float inplace? (★★★)

77. その場で(コピーなしで)、真偽値ベクトルを論理否定する、浮動小数点ベクトルの符号を反転する (★★★)

Z = bitrand(100)
@. Z = !Z

Z = rand(0:1, 100)
@. Z = 1 - Z

using Distributions
Z = rand(Uniform(-1, 1), 10)
@. Z = -Z

78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)

78. 2次元平面上の2組の点の配列P0, P1と点pを与えられたとき、点pから(P0[i],P1[i])を通る直線iへの距離を求める (★★★)

function distance(P0, P1, p)
    T = @. P1 - P0
    a, b, c = @. T[:, 2], -T[:, 1], P0[:, 2]*T[:, 1] - P0[:, 1]*T[:, 2]
    return @. abs(a*p[:, 1]' + b*p[:, 2]' + c) / hypot(a, b)
end

using Distributions
P0 = rand(Uniform(-10, 10), 10, 2)
P1 = rand(Uniform(-10, 10), 10, 2)
p  = rand(Uniform(-10, 10), 1, 2)
@show distance(P0, P1, p)

79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)

79. 2次元平面上の2組の点の配列P0, P1と点pを与えられたとき、各点j (P[j]) から(P0[i],P1[i])を通る直線iへの距離を求める (★★★)

# based on distance function from previous question
using Distributions
P0 = rand(Uniform(-10, 10), 10, 2)
P1 = rand(Uniform(-10, 10), 10, 2)
p  = rand(Uniform(-10, 10), 10, 2)
@show distance(P1, P2, p)

80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)

80. 行列を与えられて、指定された位置を中心とした小行列を取り出す (必要な場合は、fillで埋める) (★★★)

Z = rand(0:9, 10, 10)
shape = (5, 5)
fillval  = 0
cposition = (2, 2)

Zinds = @. range(cposition - shape÷2, shape)
R = [checkbounds(Bool, Z, i, j) ? Z[i,j] : fillval for i in Zinds[1], j in Zinds[2]]
@show Z
@show R

81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)

81. 配列 Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14] から、新たな配列 R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]] を作成する (★★★)

Z = collect(1:14)
n = 4

R = Z[(1:n)' .+ (0:length(Z)-n)]

82. Compute a matrix rank (★★★)

82. 行列のランクを計算する (★★★)

Z = rand(10, 10)
println(rank(Z))

83. How to find the most frequent value in an array?

83. 配列に最も多く出現する値を得る

Z = rand(1:10, 50)

# Slow
print(indmax(count(Z .== v) for v in 1:maximum(Z)))

# Fast
F = zero(1:maximum(Z))
foreach(v -> F[v] += 1, Z)
print(indmax(F))

# using StatsBase
using StatsBase
println(indmax(counts(Z)))

# for arbitrary array
Z = rand(["the", "be", "and", "of", "a", "in", "to", "have"], 50)
F = Dict{eltype(Z), Int}()
for z in Z
    F[z] = get(F, z, 0) + 1
end
kv = reduce(F) do kv1, kv2
    ifelse(kv1[2] > kv2[2], kv1, kv2)
end
print(kv[1])

# using PriorityQueue
using DataStructures
Z = rand(["the", "be", "and", "of", "a", "in", "to", "have"], 50)
F = PriorityQueue{eltype(Z), Int}(Base.Order.Reverse)
for z in Z
    F[z] = get(F, z, 0) + 1
end
print(peek(F)[1])

84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)

84. 10x10行列から、全ての3x3の小行列を取り出す (★★★)

Z = rand(1:5, 10, 10)
n = 3

C = [Z[i+k, j+l] for i in 1:size(Z, 1)-n+1, j in 1:size(Z, 2)-n+1, k in range(0, n), l in range(0, n)]

# another solution (using broadcast)
C = broadcast((i,j,k,l) -> Z[i+k, j+l],
              1:size(Z, 1)-n+1,
              reshape(1:size(Z, 2)-n+1, (1,:)),
              reshape(range(0, n), (1,1,:)),
              reshape(range(0, n), (1,1,1,:)))

(未)85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)

# Author: Eric O. Lebigot
# Note: only works for 2d array and value setting using indices

class Symetric(np.ndarray):
    def __setitem__(self, index, value):
        i,j = index
        super(Symetric, self).__setitem__((i,j), value)
        super(Symetric, self).__setitem__((j,i), value)

def symetric(Z):
    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)

S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print(S)

(未)86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)

# Author: Stefan van der Walt

p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)

# It works, because:
# M is (p,n,n)
# V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
# and 2 and 1, to remain with a (n,1) vector.

87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)

87. 16x16の行列の、4x4の小行列毎の和を計算する (★★★)

using Base.Iterators
Z = ones(16,16)
k = 4
S = [sum(Z[i,j]) for i in partition(indices(Z,1), k), j in partition(indices(Z,1), k)]
display(S)

88. How to implement the Game of Life using numpy arrays? (★★★)

88. numpyの配列を用いてライフゲームを実装する (★★★)

function iterate!(Z)
    # Count neighbours
    N = @views (Z[1:end-2, 1:end-2] + Z[1:end-2, 2:end-1] + Z[1:end-2, 3:end] +
                Z[2:end-1, 1:end-2]                       + Z[2:end-1, 3:end] +
                Z[3:end  , 1:end-2] + Z[3:end  , 2:end-1] + Z[3:end  , 3:end])

    # Apply rules
    birth = @. @views (N==3) & !Z[2:end-1, 2:end-1]
    survive =  @views @. ((N==2) | (N==3)) & Z[2:end-1, 2:end-1]
    fill!(Z, false)
    @views fill!(Z[2:end-1, 2:end-1][birth .| survive], true)
end

Z = bitrand(50, 50)
for _ in 1:100
    iterate!(Z)
end
@show Z

(未)89. How to get the n largest values of an array (★★★)

Z = np.arange(10000)
np.random.shuffle(Z)
n = 5

# Slow
print (Z[np.argsort(Z)[-n:]])

# Fast
print (Z[np.argpartition(-Z,n)[:n]])

90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)

90. 複数のベクトルを与えられたとき、その直積(各要素の全ての組み合わせ)を得る (★★★)

using IterTools
collect(product([1, 2, 3], [4, 5], [6, 7])) |> display

(未)91. How to create a record array from a regular array? (★★★)

Z = np.array([("Hello", 2.5, 3),
              ("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T, 
                               names='col1, col2, col3',
                               formats = 'S8, f8, i8')
print(R)

(未)92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)

# Author: Ryan G.

x = np.random.rand(5e7)

%timeit np.power(x,3)
%timeit x*x*x
%timeit np.einsum('i,i,i->i',x,x,x)

93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)

93. (8,3)次元の配列Aと、(2,2)次元の配列Bを考える。Aの行のうち、Bの行の要素を全て含むもの(順序は問わない)を取り出す (★★★)

A = rand(0:4, 8, 3)
B = rand(0:4, 2, 2)
rows = filter(indices(A, 1)) do i
    all(any(map(b->contains(==, A[i,:], b), B), 2))
end
@show rows

94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)

94. 10x3行列から、全ての値が同じでない行を取り出す ([2,2,3]など) (★★★)

Z = rand(0:4, 10, 3)
E = squeeze(all(Z .== Z[:,1], 2), 2)
U = Z[.!E, :]
@show Z
@show U

95. Convert a vector of ints into a matrix binary representation (★★★)

95. 整数ベクトルから、各整数に対応する2進数表現の行列を得る (★★★)

I0 = [0, 1, 2, 3, 15, 16, 32, 64, 128]
B = @. Int(!iszero(I0 & 2^(7:-1:0)'))
@show B

96. Given a two dimensional array, how to extract unique rows? (★★★)

96. 2次元配列から、重複のない行を取り出す。(★★★)

Z = rand(0:1, 6, 3)
Z[unique(i->Z[i,:], indices(Z,1)), :]

(未)97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)

# Author: Alex Riley
# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/

A = np.random.uniform(0,1,10)
B = np.random.uniform(0,1,10)

np.einsum('i->', A)       # np.sum(A)
np.einsum('i,i->i', A, B) # A * B
np.einsum('i,i', A, B)    # np.inner(A, B)
np.einsum('i,j->ij', A, B)    # np.outer(A, B)

98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?

98. (X,Y)の2つのベクトルで表現されるパス(折れ線)があるとき、そのパスから等間隔で点を得る(補間する) (★★★)?

function interp1(x, v, xq)
    i = map(xq1->clamp(searchsortedfirst(x, xq1), 2, length(x)), xq)
    return @. (v[i] - v[i-1])/(x[i] - x[i-1]) * (xq - x[i]) + v[i]
end

ϕ = 0:0.1:10π
a = 1
X = @. a*ϕ*cos(ϕ)
Y = @. a*ϕ*sin(ϕ)

dr = hypot.(diff(X), diff(Y)) # segment lengths
r = vcat(0, cumsum(dr))
r_int = linspace(0, last(r), 200) # regular spaced path
X_int = interp1(r, X, r_int)  # integrate path
Y_int = interp1(r, Y, r_int)

99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)

99. 整数nと2次元配列Xを与えられたとき、Xから母数nの多項分布と解釈可能な行 (つまり、要素がすべて整数でかつ合計がnとなっている行) を抽出する。 (★★★)

X = [1.0 0.0 3.0 8.0
     2.0 0.0 1.0 1.0
     1.5 2.5 1.0 0.0]
n = 4

M = @. $squeeze($all(iszero(first(modf(X))), 2) & ($sum(X, 2) == n), 2)
display(X[M, :])

100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★)

100. 1次元配列Xの期待値の95%信頼区間をブートストラップ法により求める (N回リサンプリングして平均値を計算し、分位数を求める) (★★★)

X = randn(100) # random 1D array
N = 1000 # number of bootstrap samples
means = squeeze(mean(rand(X, (length(X), N)), 1), 1)
confint = quantile(means, [0.025, 0.975])
display(confint)
12
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
4