Q Idioms assemembered

This is more of an expanding list of Q idioms I have had to either assemble or remember or some combination.

  1. Cross product of two lists is faster in table form

    q)show x:til 3

    0 1 2

    q)show y:2#7

    7 7

    q)x cross y

    0 7

    0 7

    1 7

    1 7

    2 7

    2 7

    q) ([] x) cross ([] y)

    x y

    0 7

    0 7

    1 7

    1 7

    2 7

    2 7

    \t til[1000] cross 1000#5

    85

    \t flip value flip ([] til 1000) cross ([] x1:1000#5)

    33

    /and if you are happy working with it in table form

    \t ([] til 1000) cross ([] x1:1000#5)

    5

  2. Take last N observations for a column in a tableBoth of these can be used to create a list of indexes and the columns can be simply   projected on to the list of indexes

    /a) Intuitive way take last n from c

    q) N:10; C:til 100000;

    q) {[n;c]c{y-x}[til n] each til count c}[N;C] /timing 31 milli

    0

    1 0

    2 1 0

    3 2 1 0

    4 3 2 1 0

    ….

    /b) Faster way using xprev and flip

    q) \t {[n;c] flip (1+til n) xprev \\: c}[10;c]  /timing 9 millesec

  3. Create a Polynomial Function from the coefficients

    poly:{[x] (‘)[wsum[x;];xexp/:[;til count x]]};

    f:poly 0 1 2 3;

    f til 5

    0 6 34 102 228

  4. Count Non Null entries

    All in K:

    fastest:{(#x)-+/^x}

    slower:{+/~^x}

    slowest:{#*=^x}

    Q translation:

    fastest:{count[x]-sum null x}

    slower:{sum not null x}

    slowest:{count first group null x}

  5. Camel case char separated symbols:

camelCase:{[r;c]`$ssr[;r;””] each @'[h;i;:;]upper h @’ i:1+ss'[;r] h:string x}
most common case
q)c:` sv/: `a`b cross `e`fff`ggk cross `r`f
`a.e.r`a.e.f`a.fff.r`a.fff.f`a.ggk.r`a.ggk.f`b.e.r`b.e.f`b.fff.r`b.fff.f`b.ggk.r`b.ggk.f
camelCase[“.”;c]
`aER`aEF`aFffR`aFffF`aGgkR`aGgkF`bER`bEF`bFffR`bFffF`bGgkR`bGgkF

6.  Progress style bars:

p:0;do[10; p+:1; system “sleep .1”;1 “\r “,p#”#”];-1 “”;

{[p]1 “\r “,(a#”#”),((75-a:7h$75*p%100)#” “),string[p],”%”;if[p=100;-1 “”;]}

7.  AutoCorr:

autocorr:{x%first x:x{(y#x)$neg[y]#x}/:c-til c:count x-:avg x}

8.  Index of distinct elements:

idistinct:{first each group x}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s