text:
Power-Ending Patterns
When you look at the last decimal digit of each power of a non-negative integer a repeating pattern forms. For example, 3:
3^1 =     3
3^2 =     9
3^3 =    27
3^4 =    81
3^5 =   243
3^6 =   729
3^7 =  2187
3^8 =  6561
3^9 = 19683

The last digits go 3971 which repeats indefinitely. In fact any number we choose that ends in 3 has that same pattern because none of the other digits can have an effect on the ones place during repeated multiplication.
What's curious is that some numbers have a much shorter cycle of power-ending digits. For example with 5 the powers all end in 5 so the pattern, written as short as possible, is simply 5.
Looking at the minimal power-ending digits patterns for 0 through 9 we get:
0 -> 0
1 -> 1
2 -> 2486
3 -> 3971
4 -> 46
5 -> 5
6 -> 6
7 -> 7931
8 -> 8426
9 -> 91

(The lengths of these being 11442 repeated is a curious tidbit itself.)
Remember, any numbers above 9 will have the same pattern as their last digit as was explained above with 3.
Challenge
Your challenge here is to write a program that takes in any non-negative integer and outputs its minimal power-ending digit pattern.
The exact output formatting, whether string or list, doesn't matter. For example, here are some potential inputs followed by valid potential outputs:
900 -> [0]
11 -> 1
2 -> 2486
303 -> 3, 9, 7, 1
44 -> 4 6
45 -> 5
666 -> "6"
3857 -> [7 9 3 1]
118 -> '8426'
129 -> [9, 1]

The shortest code in bytes wins.

I assume we can't indefinitely print the list?

@RGS No. The point is to just print the minimal sequence of 1, 2, or 4 digits.

"Your challenge here is to write a program that takes in any non-negative integer and outputs it's minimal power-ending digit pattern" but then "Pretty much reproduce the list above." & [tag:kolmogorov-complexity] - which is it?

...I guess the former since you give examples, I suggest removing the KC tag and "Pretty much reproduce the list above."

@JonathanAllan I figured there could be elements of KC in some solutions since the data is pretty small. And for the inputs 0 to 9 the list would be reproduced. Sorry if that's not clear - I'm open to better phrasing?

If we want to put this in the math jargon, this is the semigroup generated by $n$ on the monoid $\langle\mathbb{Z}_{10},\times\rangle$.

Are we allowed to produce incorrect results upon overflow?

@S.S.Anne Like if the input integer is too big? That's fine. As long as your program can accept integers up to your language's usual maximum, like 2^31-1.

No, if the calculations of the integers inside the functions are too big.

@S.S.Anne Ah. Good point. It's ok if things overflow if you're taking powers.

@Calvin'sHobbies: compactly encoding a lookup table can be part of a code-golf answer.  That doesn't mean the overall problem is one of Kolmogorov complexity.  It's nice that the question points out that the pattern for any number is the pattern for it's lowest decimal digit.  Maybe you want to replace some of the other phrasing with that?  But @ JonathanAllen already told you how to fix the biggest misleading part: simply remove the sentence "Pretty much reproduce the list above."  The test cases are clearer without that.

@640KB Nope, sorry.

Python 3, 44 43 40 bytes
Based off of mabel's answer but using dictionary comprehensions:
lambda n:[*{n**i%10:0for i in[1,2,3,4]}]

Saved 1 byte thanks to mabel.
Saved 3 bytes thanks to xnor.
You can try it online

ah of course! I forgot about these

you can replace :i for with :1for to save a byte

@mabel clever trick!

Python 3's list unpacking can save a few bytes: https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIc8qWqs6T0srU9XQwMogLb9IIVMhMy/aUMdIx1jHJLY29j9ILA8oplCUmJeeqmFoYqZpxaUABAVFmXklGmlK1Xm1Crp2CtVpGnmatUqa/wE

Ah I knew it was possible @xnor but I couldn't remember what it was called, thanks for sharing

Jelly, 6 bytes
*Ɱ4%⁵Q

A monadic link which accepts an integer and yield a list of integers.
Try it online!
How?
*Ɱ4%⁵Q - Link: integer, n
  4    - four
 Ɱ     - map across (implicit range of [1..4]) with:
*      -    exponentiate
    ⁵  - ten
   %   - (powers) mod (ten)
     Q - de-duplicate

JavaScript (ES6), 41 bytes
n=>[n%=10]+[[,,486,971,6,,,931,426,1][n]]

Try it online!

JavaScript (ES6), 42 bytes
A recursive version.
n=>(g=k=>(d=(k*n)%10)-n?[k]+g(d):k)(n%=10)

Try it online!

Python 3, 54 bytes
lambda n:list(dict.fromkeys(n**i%10for i in(1,2,3,4)))

Try it online!
Could have been 38 bytes if set() was ordered.

APL (Dyalog Unicode), 10 8 bytes
Jo King suggested a shorter function than what I originally had, ∪10⊤*∘⍳∘4 (a train at 9 bytes) vs my 10-byter dfn, and ngn pointed out a tradfn would be shorter than both altogether
∪10⊤⎕*⍳4

Try it online!
⍳4 the vector 1 2 3 4
⎕* the input raised to the power of, i.e. (⍵*1)(⍵*2)(⍵*3)(⍵*4) (using ⍵ to represent the value of the input)
10⊤ mod 10
∪ unique

9 bytes

@JoKing *∘⍳∘4 -> ⎕*⍳4 to make it a "full program"

Thanks, to both of you.

05AB1E, 7 6 bytes
-1 byte thanks to Kevin Cruijssen
4LmT%Ù

Try it online!
Just a port of Jonathan Allan's Jelly answer.

You can remove the €, since it's done implicitly.

Thank you! I didn't know that @KevinCruijssen

MATL, 7 bytes
4:^10\u

Try it online!
Explanation
4:    % Push [1 2 3 4]
^     % Implicit input, n. Element-wise power: gives [n n^2 n^3 n^4]
10\   % Modulo 10
u     % Unique (remove duplicates). Implicit display

Haskell, 48 46 bytes
import Data.List;f n=nub[n^i`mod`10|i<-[1..4]]
-2 bytes thanks to @Laikoni
Having to import nub is really annoying... Any suggestions to remove it?
You can Try it online!

Here's a version without nub, but it is also 48 bytes: n!i|x<-n^i`mod`10=x:[y|i<4,y<-n!(i+1),y/=x];(!1) Try it online!

However, your version can be shortened to 46 bytes: import Data.List;f n=nub[n^i`mod`10|i<-[1..4]] Try it online!

@Laikoni thanks for your suggestions!

x86-16 machine code, IBM PC DOS, 26 bytes
Binary:
00000000: b380 8a07 d72c 308a d850 0430 b40e cd10  .....,0..P.0....
00000010: 58f6 e3d4 0a3a c375 f0c3                 X....:.u..

Unassembled:
B3 80       MOV  BL, 80H            ; BX to command line input tail
8A 07       MOV  AL, BYTE PTR[BX]   ; input length into AL
D7          XLAT                    ; AL = [BX+AL] (get the last char of input)
2C 30       SUB  AL, '0'            ; convert from ASCII
8A D8       MOV  BL, AL             ; save N to BL for compare/multiply
        POW_LOOP:
50          PUSH AX                 ; save AX
04 30       ADD  AL, '0'            ; convert to ASCII
B4 0E       MOV  AH, 0EH            ; BIOS tty function
CD 10       INT  10H                ; call BIOS, write char to console
58          POP  AX                 ; restore AX
F6 E3       MUL  BL                 ; AX = AL * BL
D4 0A       AAM                     ; AL = AL % 10
3A C3       CMP  AL, BL             ; is sequence repeating?
75 F0       JNE  POW_LOOP           ; if not, keep looping
C3          RET                     ; return to DOS

A standalone PC DOS executable program.  Input via command line args.
I/O:

JavaScript (Node.js), 42 bytes
n=>new Set([1,2,3,4].map(v=>(n%10)**v%10))

Try it online!
JavaScript (Node.js), 37 bytes
This solution is suggested by @Expired Data, it is shorter, elegant but it will have problems when working with large number.
n=>new Set([1,2,3,4].map(v=>n**v%10))

Try it online!

do you need to take n modulo 10?

@Expired Data thank for your solution, I just updated my answer.

PHP, 54 50 bytes
for($n=$o=$argn%10;print$n;$n-$o||die)$n=$n*$o%10;

Try it online!

Alternate Solution:
PHP, 50 45 bytes
for(;$i<'11442'[$argn%5];)echo$argn**++$i%10;

Try it online!

x86_64 machine code, 63 61 bytes
B8 BF 84 7B 09 B9 0A 00 00 00 31 D2 C7 44 24 FC
A4 10 0A 00 48 C1 E0 22 48 89 44 24 EC 48 B8 3C
00 00 00 00 00 5E 24 48 89 44 24 F4 89 F8 66 F7
F1 48 89 D0 83 E0 0F 66 03 54 44 EC C3

Disassembly:
00000000  B8BF847B09        mov eax,0x97b84bf
00000005  B90A000000        mov ecx,0xa
0000000A  31D2              xor edx,edx
0000000C  C74424FCA4100A00  mov dword [rsp-0x4],0xa10a4
00000014  48C1E022          shl rax,byte 0x22
00000018  48894424EC        mov [rsp-0x14],rax
0000001D  48B83C0000000000  mov rax,0x245e00000000003c
         -5E24
00000027  48894424F4        mov [rsp-0xc],rax
0000002C  89F8              mov eax,edi
0000002E  66F7F1            div cx
00000031  4889D0            mov rax,rdx
00000034  83E00F            and eax,byte +0xf
00000037  66035444EC        add dx,[rsp+rax*2-0x14]
0000003C  C3                ret

Input: edi, Output: dx, requires rsp to be set to a correct value.
Example call:
main:
  mov edi, 1337
  call f
  movzx eax, dx
  ret

Retina 0.8.2, 58 50 bytes
.*(.)
$1$1$*_,,486,971,6,,,931,426,1
+`_\d*,

,.*

Try it online! Link includes test cases. Edit: Saved 8 bytes by not including the input digit in the digit patterns. Explanation:
.*(.)
$1$1$*_,,486,971,6,,,931,426,1

Create a unary copy of the last digit and append the list of power-ending digit pattern suffixes.
+`_\d+,

Delete the appropriate number of entries from the start of the list.
,.*

Delete unneeded entries from the end of the list.
Actually calculating the digits takes 69 bytes:
M!`.$
{`(.).*
$&;$1$*_,$&$*
_(?=.*,(1*))|,1*
$1
;(1{10})*(1*)
$.2
D`.

Try it online! Link includes test cases. Explanation:
M!`.$

Modulo the input by 10.
{`

Repeat while new digits can be added.
(.).*
$&;$1$*_,$&$*

Create unary copies of the first digit and power-ending digits so far.
_(?=.*,(1*))|,1*
$1

Multiply them together.
;(1{10})*(1*)
$.2

Take the remainder modulo 10 and convert it to decimal.
D`.

Deduplicate the digits.
Of course it only takes 34 bytes in Retina 1:
L`.$
{`(.).*
$&_$.(*$1*
_.*\B

D`.

Try it online! Link includes test cases. Explanation:
L`.$

Modulo the input by 10.
{`

Repeat while new digits can be added.
(.).*
$&_$.(*$1*

Multiply the power-ending pattern so far by its first digit. (* has higher precedence than $^, so multiplying by its reverse ends up costing a byte more than it saves.)
_.*\B

Modulo the result by 10.
D`.

Deduplicate the digits.

Perl 6, 23 bytes
((*X**1..4)X%10).unique

Try it online!
Returns the unique values of the input to the power of 1 through 4 modulo 10.

Excel, 53 bytes
=CHOOSE(RIGHT(A1)+1,,1,2486,3971,46,5,6,7931,8426,91)

RIGHT(A1) defaults to RIGHT(A1,1), making it more efficient than MOD(A1,10)

MathGolf, 6 bytes
4╒#♂%▀

port of @JonathanAllan's Jelly answer, so make sure to upvote him as well!
Try it online.
Explanation:
4╒      # Push the list [1,2,3,4]
  #     # Take the (implicit) input-integer to each of this power
   ♂%   # Take modulo-10 for each of these
     ▀  # Uniquify the list
        # (after which the entire stack is output implicitly)

C (gcc), 56 51 bytes
Saved 5 bytes thanks to S.S. Anne!!!
i;f(n){for(i=n%10;putchar(i+48),i=n*i%10,i-n%10;);}

Try it online!

Wow. I feel ashamed now...

51 bytes

@S.S.Anne Nice one, was thinking a for loop might golf some bytes but hadn't figured it out. Thanks!

https://codegolf.stackexchange.com/a/168932/89298

@S.S.Anne Interesting, makes sense. :-)

Ruby, 30 bytes
->n{(1..4).map{|g|n**g%10}|[]}

Try it online!

Pyth, 9 bytes
{m%^QdTS4

Try it online!

Burlesque, 12 bytes
ri4ro?^)[~NB

Try it online!
ri   # Read input to int
4ro  # Range [1,4]
?^   # Raise input to powers [1,4]
)[~  # Take last digit of each
NB   # Remove duplicates

Jelly, 7 bytes
4R*@%⁵Q

You can try it online. [It doesn't beat Jonathan's answer nor was it posted first. I just got to this answer by myself and I like posting Jelly answers while I'm learning]

Charcoal, 24 bytes
⭆⁺0§⪪”←‴Ki⦃k‽” Ｉθ﹪⁺ＩθＩιχ

Try it online! Link is to verbose version of code. Uses the repetition between the first and second halves of the table. Explanation:
     ”←‴Ki⦃k‽”              Compressed string `  264 648 2`
    ⪪                       Split on literal space
   §           Ｉθ           Cyclically index by the input as a number
 ⁺0                         Prefix a literal `0`
⭆                           Map over characters and join
                 ﹪⁺ＩθＩιχ    Add to the input and reduce modulo 10

C (gcc), 116 bytes
x,c,a[4];f(n){n%=10;for(c=0,x=n;c<4;x*=n)a[c++]=x%10;n=*a*10+a[1];n=a[2]*10+a[3]-n?n*100+a[2]*10+a[3]:*a-a[1]?n:*a;}

Can almost certainly be golfed more but I haven't figured it out yet.
Try it online!

Can you drop n%=10;?

@JonathanFrech No. For larger integers omitting that will cause overflow.

Most of the time such overflow deviations are acceptable; one may need to ask the OP for clarification.

Suggest x=n%=10;for(c=0; instead of n%=10;for(c=0,x=n;

J, 15 bytes
[:~.10|]^1+i.@4

Try it online!
K (Kona), 14 bytes
{?(x^1+!4)!10}

Try it online!

Pip, 12 bytes
UQ(a**\,4)%t

takes range from 1 to 4, takes powers, mod 10, uniquify.
Try it online!


text:
Number of palindrome splits
In this task you will take as input a non-negative integer \$n\$, and output the number of pairs of non-negative integers \$a,b\$ such that both are palindromes*, \$a \leq b\$, and \$a+b = n\$.  For example if \$n\$ is \$22\$ then the valid pairs are
\$
\begin{array}{c|c}
a & b  \\
\hline
0 & 22 \\
11 & 11 \\
\end{array}
\$
So the output is \$2\$.
As another example, if \$n\$ is \$145\$  then the valid pairs are
\$
\begin{array}{c|c}
a & b \\
\hline
4 & 141 \\
44 & 101 \\
\end{array}
\$
So the output is 2.
Your submission should be a program or function.  Answers will be scored in bytes with fewer bytes being the goal.
Test Cases
\$
\begin{array}{c|c c|c}
\mathrm{Input} & \mathrm{Output} & \mathrm{Input} & \mathrm{Output} \\
\hline
0 & 1  & 12 & 5\\
1 & 1  & 13 & 4\\
2 & 2  & 14 & 4\\
3 & 2  & 15 & 3\\
4 & 3  & 16 & 3\\
5 & 3  & 17 & 2\\
6 & 4  & 18 & 2\\
7 & 4  & 19 & 1\\
8 & 5  & 20 & 1\\
9 & 5  & 21 & 0\\
10 & 5 & 22 & 2\\
11 & 5 & 23 & 1\\
\end{array}
\$
OEIS A260254

* In base 10

Related

I like how this challenge was posted on a palindromic date, 02/02/2020

@DJMcMayhem Additionally the number of days since the beginning of the year (33) and the number of days to the end of the year (333) today are both palindromes.

@DJMcMayhem I think you mean 20200202 or 2020-02-02 (ISO 8601) -- today is special, it is palindromic in the UK, the US, and internationally.

Jelly, 9 bytes
ŻŒḂ€ḋṚ$HĊ

A monadic Link accepting a non-negative integer which yields a non-negative integer.
Try it online!
How?
Counts all pairs without the \$a\leq b\$ restriction, halves and rounds up. Note that the halved count is only a fraction if \$\frac n 2\$ is a palindrome and in such cases we want to count this \$a=b\$ pair.
ŻŒḂ€ḋṚ$HĊ - Link: integer, n    e.g. 22
Ż         - zero-range               [0,1,2,...,9,10,11,12,...,21,22]
   €      - for each:
 ŒḂ       -   is palindrome (digits) [1,1,1,...,1,0,1,0,...0,1]
      $   - last two links as a monad:
     Ṛ    -   reverse                [1,0,...,0,1,0,1,...,1,1,1]
    ḋ     -   dot-product           3  (=1×1+1×0+...+1×0+1×1+0×1+...+0×1+1×1)
       H  - halve                   1.5
        Ċ - ceil                    2

JavaScript (ES6),  74  73 bytes
n=>(g=a=>a>n-a?0:![a,n-a].some(n=>[...n+''].reverse().join``-n)+g(-~a))``

Try it online!

could you please tell me what is the last `` mean, thanks !

@chaugiang (g=a=>...)``  is equivalent to (g=a=>...)(['']) (TIO). So we have a=[''] for the first iteration, which happens to behave like a=0 would with our code and is turned into 1 for the 2nd iteration with -~a. All in all, this is one byte shorter than (g=a=>...)(0).

The tagged template plus the usage of -~ is actually super clever I definitely need to incorporate them more

Python 2,  73 70  63 bytes
lambda n:sum(`n-v`+`v`==(`v`+`n-v`)[::-1]for v in range(n/2+1))

Try it online!
Note that:
(string_a == reverse(string_a)) and (string_b == reverse(string_b))

is equivalent to
reverse(string_a + string_b) == (string_b + string_a)

(where + is concatenation)

Are the backtits converting the integers to strings?

Yes, in Python 2 it is a shorthand for repr(...)

very clever. Adapting it in Python 3 with f" " format strings I shaved 18 bytes ;) have a +1

Perl 6, 44 bytes
{+grep {.flip eq[R,] $_},(^$_ Z($_...$_/2))}

Try it online!
Finds the number of pairs of numbers such that the reverse of the string representation is equal to the string representation of the reversed pair.

Prolog (SWI), 99 bytes
N-C:-aggregate_all(count,(between(0,N,A),B is N-A,B=<A,+A,+B),C).
+N:-atom_codes(N,C),reverse(C,C).

Try it online!
Ungolfed Code
After adding white space, this solution reads very similarly to the challenge specification. It simply asks for the number of pairs palindrome integers within specified bounds that sum to N.
count_splits(N,C) :-
  aggregate_all(count,(
    between(0,N,A),
    B is N-A, B=<A,
    palindrome(A),
    palindrome(B)
  ),C).

palindrome(N) :-
  atom_codes(N,C),
  reverse(C,C).

05AB1E, 10 bytes
ÝεÂQ}Â*O;î

Port of @JonathanAllan's Jelly answer, so make sure to upvote him as well!
Try it online or verify all test cases.
Explanation:
Ý        # Push a list in the range [0, (implicit) input-integer]
 ε       # Map each value to:
  Â      #  Bifurcate the value; short for Duplicate & Reverse copy
   Q     #  And check if it's equal to the value itself (1 if a palindrome; 0 if not)
 }Â      # After the map: bifurcate the entire list as well
   *     # Multiply the values at the same indices in the lists
    O    # Take the sum of that
     ;î  # And then halve and ceil it
         # (after which the result is output implicitly)

C (gcc), 114 \$\cdots\$ 105 98 bytes
Saved 7 bytes thanks to rtpax!!!
i;m;p(n){for(i=0,m=n;i=i*10+n%10,n/=10;);n=i==m;}r;a;f(n){for(a=r=0;a<=n/2;)r+=p(a)*p(n-a++);n=r;}

Try it online!

@rtpax Very nice, adding the if condition to the result is especially sweet  - Thanks!:-)

Python 3.8, 89 87 68 66 bytes
Adapting Jonathan's clever answer to Python 3 (with f format strings) and removing [] for a generator expression instead of list comprehension, we shave 21 bytes with
lambda n:sum(f"{i}{n-i}"==f"{n-i}{i}"[::-1]for i in range(n//2+1))

Try it online
My old answer:
lambda n:len([i for i in range(n//2+1)if(s:=str(i))==s[::-1]and(t:=str(n-i))==t[::-1]])

You can try it online

@JonathanAllan damn generator expressions ;)

Charcoal, 18 bytes
ＩＬΦ⊕⊘θ⬤Ｉ⟦ι⁻θι⟧⁼λ⮌λ

Try it online! Link is to verbose version of code. The halved input has to be incremented because a needs to vary over the inclusive range from 0 to n/2. Explanation:
     θ              Input `n`
    ⊘               Halved
   ⊕                Incremented
  Φ                 Filter over implicit range
        ⟦           Begin list
         ι          Current index `a`
           θ        Input `n`
            ι       Current index `a`
          ⁻         Subtracted (i.e. `b`)
             ⟧      End list
       Ｉ            Vectorised cast to string
      ⬤             Both strings satisfy
                 λ  Current string
                ⮌   Reversed
               λ    Current string
              ⁼     Are equal
 Ｌ                  Length
Ｉ                   Cast to string for implicit print

PHP, 83 86 85 73 bytes
for(;$i<=$argn/2;$i++)$k+=strrev($j=$argn-$i)==$j&&strrev($i)==$i;echo$k;

Try it online!
-13 bytes and bug fix thanks to @640KB

JavaScript (Node.js),  70 69  67 bytes
-2 thanks to Arnauld (change each string cast from x+''+y to x+[y])
I don't really know much JavaScript, I based this around Arnauld's answer, any advice is very welcome!
n=>(g=a=>(v=n-a)<a?0:(v+[a]==[...a+[v]].reverse().join``)+g(-~a))``

Try it online!
Note that:
(string_a == reverse(string_a)) and (string_b == reverse(string_b))

is equivalent to
reverse(string_a + string_b) == (string_b + string_a)

(where + is concatenation)

67 bytes by coercing to strings in a slightly shorter way.

It also means that you can get rid of v like this, but that's the same byte count.

Thanks @Arnauld ...it seems that there are many, many ways to --skin-- golf a cat in JS.

Vyxal l, 63 bitsv2, 7.875 bytes
½ʀ2('Ḃ⁼;-

Try it Online!
Bitstring:
000100100000010110000001100101111001000100100001100010110111001

Explained
½ʀ2('Ḃ⁼;-
½ʀ         # Push the range [0, input / 2] for later
  2(       # Twice:
    'Ḃ⁼;   #   Filter the top of the stack by is palindromic
        -  #   And subtract that from the input.
        -  #   This acts as a check for pairs, by keeping numbers that are palindromes before and after subtraction
# The l flag outputs the length of the top of the stack

Created with the help of Luminespire.
Only took me around 3 and a half years to finally write this answer. Things sure have changed since then.

Perl 5 -p, 51 bytes
$\+=($,==reverse$,)&&$_==reverse;++$,<=--$_&&redo}{

Try it online!

MathGolf, 14 bytes
)rmÑ_x^mÅε*Σ)½

Try it online.
Explanation:
)               # Increase the (implicit) input-integer by 1
 r              # Pop and push a list in the range [0, input+1)
  mÑ            # Check for each value whether it's a palindrome (1 if truthy; 0 if falsey)
    _           # Duplicate this list
     x          # Reverse the copy
      ^         # Zip the two together to create pairs
       m        # Map over each pair,
        Å       # using the following two commands:
         ε      #  Reduce by:
          *     #   Multiplying
           Σ    # Then take the sum of this list
            )   # Increase this sum by 1
             ½  # And integer-divide it by 2
                # (after which the entire stack joined together is output implicitly)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
SKI calculus golf: Half of a Church numeral
Background
SKI combinator calculus, or simply SKI calculus, is a system similar to lambda calculus, except that SKI calculus uses a small set of combinators, namely S, K, and I instead of lambda abstraction. Unlike lambda calculus, beta reduction is possible only when a combinator is given enough arguments to reduce.
The three combinators in SKI calculus are defined as follows:
$$
\begin{aligned}
S\;x\;y\;z & \overset{S}{\implies} x\;z\;(y\;z) \\
K\;x\;y & \overset{K}{\implies} x \\
I\;x & \overset{I}{\implies} x
\end{aligned}
$$
For example, the SKI expression \$ e=S(K(S\;I))K \$ is equivalent to the lambda expression \$ λx.λy.y\;x \$, as applying two arguments to \$ e \$ reduces to the desired result:
$$
\begin{aligned}
S(K(S\;I))K\;x\;y & \overset{S}{\implies} (K(S\;I)x)(K\;x)y \\
& \overset{K}{\implies} S\;I(K\;x)y \\
& \overset{S}{\implies} (I\;y)(K\;x\;y) \\
& \overset{I,K}{\implies} y\;x
\end{aligned}
$$
It is known that any lambda expression can be converted to a SKI expression.
A Church numeral is an encoding of natural numbers (including zero) as a lambda expression. The Church encoding of a natural number \$ n \$ is \$ λf. λx. f^n\;x \$ - given a function \$ f \$ and an argument \$ x \$, \$ f \$ repeatedly applied to \$ x \$ \$ n \$ times.
It is possible to construct a lambda expression (and therefore a SKI expression) that performs various arithmetic (e.g. addition, multiplication) in Church encoding. Here are a few examples of Church numerals and Church arithmetic functions: (The given SKI expressions are possibly not minimal.)
$$
\begin{array}{r|r|r}
\text{Expr} & \text{Lambda}   & \text{SKI} \\ \hline
0           & λf. λx. x       & K\;I       \\
1           & λf. λx. f\;x    & I          \\
2           & λf. λx. f(f\;x) & S (S (K\;S) K) I \\
\text{Succ} \; n & λn. λf. λx. f(n\;f\;x) & S (S (K\;S) K) \\
m+n         & λm. λn. λf. λx. m\;f(n\;f\;x) & S (K S) (S (K (S (K\;S) K)))
\end{array}
$$
Challenge
Write an SKI expression that accepts a Church numeral of \$ n \$ and evaluates to the Church numeral of \$ \lfloor n/2 \rfloor \$.
Scoring and winning criterion
The score is the total number of S, K, and I combinators used. The submission with the lowest score wins.
Here is a Python script to check the correctness and score of your SKI expression. For the record, I have a (relatively naïve) solution of score 126.

Could you maybe explain how S(S(KS)K) is the successor? I'm finding the ...K) hard to comprehend to start with - does it get the input?

@JonathanAllan When you give three arguments to it, you get $$S(S(KS)K)nfx = S(KS)Kf(nf)x = KSf(Kf)(nf)x = S(Kf)(nf)x = Kfx(nfx) = f(nfx),$$ which is exactly what we want the successor function to do.

40 combinators
S(S(SI(K(S(S(KS)K)(K(S(S(KS)(S(KK)S))(K(S(KK)(S(S(KS)K)))))))))(K(S(SI(K(KI)))(K(KI)))))(KK)

Try it online!
Generated with a little help from a slightly modified version of my answer to Combinatory Conundrum:
$$\begin{align*}
\textit{zero} &= λf. λx. x = KI \\
\textit{succ} &= λn. λf. λx. f\,(n\,f\,x) = S(S(KS)K) \\
\textit{zero-pair} &= λf. f\,\textit{zero}\,\textit{zero} = S(SI(K\,\textit{zero}))(K\,\textit{zero}) \\
\textit{next-pair-helper} &= λf. λm. λn. f\,n\,(\textit{succ}\,m) \\ &= S(S(KS)(S(KK)S))(K(S(KK)\,\textit{succ})) \\
\textit{next-pair} &= λp. λf. p\,(\textit{next-pair-helper}\,f) \\ &= S(S(KS)K)(K\,\textit{next-pair-helper}) \\
\textit{half} &= λn. n\,\textit{next-pair}\,\textit{zero-pair}\,K \\ &= S(S(SI(K\,\textit{next-pair}))(K\,\textit{zero-pair}))(KK)
\end{align*}$$

How does (KK) work if K requires two parameters?

@JerryJeremiah All combinators in SKI calculus are curried higher-order functions; $K x y = x$ is an abbreviation for $K = λx. λy. x$, so $KK = λy. K$ is a perfectly fine value. (If that doesn’t make sense to you yet, that’s understandable, but you may need to do some more reading about lambda calculus and SKI calculus instead of asking me to explain it in 600 character coments. ☺)

31 combinators
S(S(S(SI(K(S(S(KS)(S(KK)S))(K(S(KK)(S(S(KS)K)))))))(KK))(K(KI)))(K(KI))

Try it online!
$$\begin{align*}
\textit{zero} &= λf. λx. x = KI \\
\textit{succ} &= λn. λf. λx. f\,(n\,\,f\,\,x) = S(S(KS)K) \\
\textit{fst} &= λm. λn. m = K \\
\textit{next} &= λg. λm. λn. g\,\,n\,(\textit{succ}\,\,m) = S(S(KS)(S(KK)S))(K(S(KK)\,\textit{succ})) \\
\textit{half} &= λn. n\,\,\textit{next}\,\,\textit{fst}\,\,\textit{zero}\,\,\textit{zero} = S(S(S(SI(K\,\textit{next}))(K\,\textit{fst}))(K\,\textit{zero}))(K\,\textit{zero})
\end{align*}$$

56 combinators
S(K(SI(KK)))(S(SI(K(S(S(K(S(K(S(S(K(S(KS)K))S)(KK)))(S(K(SI))K)))(SI(K(KI))))(S(K(S(S(KS)K)))(SI(KK))))))(K(S(SI(K(KI)))(K(KI)))))

Try it online!
This is the hand-optimized version of my own solution (originally of score 126). I also used the "pair" construct, but in rather basic way.
$$
\begin{align*}
\textit{zero} &= λf. λx. x = KI \\
\textit{succ} &= λn. λf. λx. f\,(n\,f\,x) = S(S(KS)K) \\
\textit{pair} &= λx. λy. λf. f\,x\,y \\
\textit{zero-pair} &= \textit{pair}\,\textit{zero}\,\textit{zero} \\
\textit{fst} &= λp. p\,(λx. λy. x) \\
\textit{snd} &= λp. p\,(λx. λy. y) \\
\textit{next-pair} &= λp. \textit{pair}\,(\textit{snd}\,p)\,(\textit{succ}\,(\textit{fst}\,p))\\
\textit{half} &= λn. \textit{fst}\,(n\,\textit{next-pair}\,\textit{zero-pair})
\end{align*}
$$
Then I used \$SKIBC\$-conversion. Those reverse-applications generated lots of \$C\$s (\$C = (S (S (K (S (K S) K)) S) (K K))\$), which turned out to be very heavy even after reduction.

45 combinators
S(K(SI(KK)))(S(SI(K(SI(K(S(K(S(S(KS)(S(K(SI))K))))(S(KK)(S(KK)(S(S(KS)K)))))))))(K(S(SI(K(KI)))(K(KI)))))

From \n.(\p.p(\xy.x))(n(\p.p(\xyf.fy(\fz.f(xfz))))(\f.f00)).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Find the Inverse Neighbor Pairs

Definition
We say a pair of integers \$(a,b)\$, where \$0<a<b<N\$ and \$N\$ is an integer larger than 4, is an inverse neighbor pair respect to \$N\$ if \$ab\equiv1\text{ }(\text{mod }N)\$ and \$1\le b-a\le\log_2{N}\$. There may be no such pairs respect to some integers \$N\$.
To illustrate the definition, consider \$N=14\$. \$(3,5)\$ is an inverse neighbor pair respect to \$N\$ because \$3\times 5=15\equiv1\text{ }(\text{mod }14)\$ and \$1\le 5-3=2\le\log_2{14}\approx 3.807\$. Another pair is \$(9,11)\$.
On the other hand, consider \$N=50\$. \$(13,27)\$ is not an inverse neighbor pair because although \$13\times 27=351\equiv1\text{ }(\text{mod }50)\$, their distance \$27-13=14\$ is too large to be "neighbors". In fact, there are no inverse neighbor pairs respect to this \$N\$, since there are no such pairs that both \$ab\equiv1\text{ }(\text{mod }50)\$ and \$1\le b-a\le\log_2{50}\approx 5.643\$ can be fulfilled.
Challenge
Write a program or function, that given an integer input \$N>4\$, outputs or returns all inverse neighbor pairs respect to \$N\$ without duplicate. You may output them in any reasonable format that can be clearly interpreted as distinct pairs by a human, e.g. two numbers per line, or a list of lists, etc.
The algorithm you use must in theory vaild for all integers \$N>4\$, although practically your program/function may fail or timeout for too large values.
Sample I/O
For inputs without any inverse neighbor pairs, the word empty in the output column means empty output, not the word "empty" literally.
Input  -> Output
5      -> (2,3)
14     -> (3,5), (9,11)
50     -> empty
341    -> (18,19), (35,39), (80,81), (159,163), (178,182), (260,261), (302,306), (322,323)
999    -> (97,103), (118,127), (280,289), (356,362), (637,643), (710,719), (872,881), (896,902)
1729   -> empty
65536  -> (9957,9965), (15897,15913), (16855,16871), (22803,22811), (42725,42733), (48665,48681), (49623,49639), (55571,55579)
65537  -> (2880,2890), (4079,4081), (10398,10406), (11541,11556), (11974,11981), (13237,13249), (20393,20407), (26302,26305), (39232,39235), (45130,45144), (52288,52300), (53556,53563), (53981,53996), (55131,55139), (61456,61458), (62647,62657)
524287 -> (1023,1025), (5113,5127), (59702,59707), (82895,82898), (96951,96961), (105451,105458), (150800,150809), (187411,187423), (192609,192627), (331660,331678), (336864,336876), (373478,373487), (418829,418836), (427326,427336), (441389,441392), (464580,464585), (519160,519174), (523262,523264)

Winning Condition
This is a code-golf challenge, so shortest valid submission of each language wins. Standard loopholes are forbidden by default.

Nice challenge! Do the neighbor pairs have a practical use somewhere?

05AB1E, 17 14 13 bytes
Thanks to @KevinCruijssen and @Grimmy for the fix and inspiration from Kevin's now deleted answer
-1 byte further thanks to @Grimmy
L.ÆʒRÆo@}ʒPI%

Try it online!

Explanation
L.Æ                    - Combinations of [1..N] with 2 elements
    ʒ     }            - Filter this when ...
     RÆo               - 2^(The difference of each pair) is...
        @              - <= the input
           ʒPI%        - Then filter this list further where the product modulo input is 1

Shouldn't the í be R? You want to swap the pair [a,b] to [b,a] before using the reduce-by-subtraction, not a pair like [10,12] to [01,21]. ;)

Btw, our answers are the same now, so I'll delete it. I tbh hadn't seen your answer when I posted mine, otherwise I would have suggested it as a golf.

Yeah you're right.. I'll change í to R thanks @Grimmy and @KevinCruijssen

.Æ defaults to 2 (similar to other list operators: ι, ã, ...), so you can drop the 2 for a 13: TIO

Interesting, thanks @Grimmy didn't know that will definitely come in handy :)

Jelly, 17 bytes
ŒcðIḢ2*>¬ȧ⁸P%⁼1ðƇ

A monadic Link accepting an integer which yields a list of pairs.
Try it online!
How?
not updated for less-than-or-equal...
ŒcðIḢ2*<ȧ⁸P%⁼1ðƇ - Link: integer, n
Œc               - unordered pairs (of implicit range [1..n])
               Ƈ - filter keep those for which:
  ð           ð  - ...this dyadic chain, f(pair,n), is non-zero:
   I             -   deltas       [a,b] -> [b-a]
    Ḣ            -   head                   b-a
     2*          -   2 raised to         2^(b-a)
       <         -   is less than (n)    2^(b-a)<n  == b-a<log(n,2)
         ⁸       -   chain's left argument, the pair
        ȧ        -   logical AND           [a,b]    or  0
          P      -   product                a×b         0
           %     -   modulo (n)            (a×b)%n      0
            ⁼1   -   equals one?           (a×b)%n==1   0

@ShieruAsakoto the OP does have <= !

@RGS Yes it does, but I have little knowledge in Jelly and I don't know whether there are <= operators in Jelly

@ShieruAsakoto there aren’t. One option would be to do >¬ (greater than, not), but there may be a golfier option.

@ShieruAsakoto thanks fixed code

JavaScript (V8), 56 bytes
x=>{for(y=x;i=--y;)for(z=x;z>>=1;)y*++i%x-1||print(y,i)}

Try it online!
This \$O(n\log{n})\$ algorithm works practically up to \$N\approx2^{26.5}\approx9.49\times10^7\$.
This was 67 bytes and was originally for my test case verifications only, and then I saw Arnauld's 57 bytes. Inspired by his solution, I checked whether I can golf the loops while keeping \$O(n\log{n})\$ complexity, and here it is.

MATL, 20 bytes
:2XN!tpG\1=yd|WG>>Z)

The output is a 2-row matrix where each column is a pair.
Try it online!
How it works
Consider input 5 as an example.
:     % Implicit input: N. Range [1 2 ... N]
      % STACK: [1 2 ... N]
2XN   % Combinations of 2 elements, as rows in a 2-column matrix
      % STACK: [1 2;
                1 3;
                ···;
                4 5]
!     % Transpose. Each combination is now a column in a 2-row matrix
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
tp    % Duplicate. Product of each column
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [2  3  4  5  6  8 10 12 15 20]
G\    % Modulo N
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [2 3 4 0 1 3 0 2 0 0]
1=    % Equal to 1?
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
y     % Push another copy of the 2-row matrix
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
d|    % Absolute difference between the two rows
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [1 2 3 4 1 2 3 1 2 1]
W     % 2 raised to that
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [2  4  8 16  2  4  8  2  4  2]
G>    % Greater than N? (**)
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
               [0 0 1 1 0 0 1 0 0 0]
>     % Greater than. This gives true for entries that are true in (*)
      % and false in (**)
      % STACK: [1 1 1 1 2 2 2 3 3 4;
                2 3 4 5 3 4 5 4 5 5]
               [0 0 0 0 1 0 0 0 0 0]
Z)    % Use as a logical index into the columns of the 2-row matrix
      % STACK: [2;
                3]
      % Implicit display

Fortran (GFortran), 86 79 bytes
read*,n
print*,((pack([i,j],mod(i*j,n)==1.and.2.**(j-i)<=n),j=i+1,n),i=1,n)
end

-7 bytes thanks to @DeathIncarnate
Yes, I still write Fortran in 2020. Here I'm reading an implicit integer n and looping over i and j (a and b would be implicitly reals). An array (i, j) is masked using the intrinsic pack().
Try it online!

You don't need to use the old array syntax and real(j-i,8) is equivalent to dble in Gfortran. 82 Bytes Try it online!

In fact, you don't need to make it a real at all, you can just make the 2 real with a decimal point. 79 bytes. Try it online!

@DeathIncarnate Thanks, didn't think of that!

JavaScript (V8),  61 59  57 bytes
n=>{for(a=b=n;a=a||--b;)--a*b%n-1|2**(b-a)>n||print(a,b)}

Try it online!
The way the for loop is written, we have \$b=N\$ during the first \$N\$ iterations and we have \$a=0\$ before \$b\$ is decremented. But in both cases, it implies \$ab\equiv 0\pmod N\$, so the corresponding pairs are rejected anyway.

C (gcc) -lm, 76 bytes
A port of my JS answer.
a,b;f(n){for(a=b=n;a=a?a:--b;)--a*b%n-1|pow(2,b-a)>n||printf("%d,%d ",a,b);}

Try it online!

Hmm... There's got to be some way to use 1 << b-a rather than pow(2, b-a).

@S.S.Anne That would limit the maximum difference between $a$ and $b$ to $31$, which IMO is not acceptable.

bc, 140 94 90 bytes
define f(n){for(a=2;a<n;a=a+1){for(d=1;2^d<=n;d++){if(a*(a+d)%n==1){print" ",a,",",a+d}}}}

Try it online!
Function f() takes the number as input, writes its output to stdout, and returns 0, which should be ignored.  The test wrapeper in the TIO needs a special marker for end-of-file, as it otherwise keeps trying to read
Having looked at another answer, I saw I could do \$2^{d}\le{n}\$ instead of \$d\le\log_2{n}\$  -46, including the +2 for -l.
I was amazed to find it turned into a one-liner.
I then realized I had two unneeded pairs of parentheses.  -4.
I have also realized that I allow b>n, but it apparently doesn't hit in the test cases.
Edit: it turns out with \$0<a<N<b\$, there can't be a hit unless \${{b-a}\over2}\ge\sqrt{N-1}\$  Combining with the neighbor requirement of \$b-a\le\log_2{N}\$ we get \$2\sqrt{N-1} \le \log_2{N} \$  This only happens at \$N=1\$, so I'm safe.
ungolfed:
define f(n) {
    for (a=2; a<n; a=a+1) {
        for (d=1; 2^d<=n; d++) {
            if (a*(a+d)%n==1) {
                print " ", a, ",", a+d
            }
        }
    }
}

originally: bc -l, 138 + 2 = 140 bytes
define f(n){
scale=9
m=l(n)/l(2)
scale=0
for(a=2;a<n;a=a+1){c=a+m
if(c>=n)c=n
for(b=a+1;b<c;b=b+1){if(((a*b)%n)==1){print " ",a,",",b
}}}}

Try it online!

Burlesque, 46 bytes
riJs1ro2CBf{Jp^.-ab2j**g1.<jpdg1.%1==&&}:U_:so

Try it online!
ri     # Read as int
Js1    # Store a copy
ro     # Range [1,N]
2CB    # Combinations of length 2
f{     # Filter for
 J     # Duplicate
 p^.-  # i-j
 ab    # |i-j|
 2j**  # 2^|i-j|
 g1.<  # < N
 jpd   # i*j
 g1.%  # (i*j)%N
 1==   # Equal to 1
 &&    # Bitwise and
}
:U_    # Filter out i=j
:so    # Filter for sorted (removing duplicates)

Python 3, 76 71 bytes
lambda N:[(a,b)for a in range(N)for b in range(a)if(1<<a-b)-N<a*b%N==1]

Thanks, Jitse, for saving me 5 bytes after some discussion.
You can try it online, where I'm not running the larger test cases because it times out

@Jitse why does your //N work? Because //N divides by N and rounds down, isn't that too permissive?

@Jitse what I mean is that if x = N+1 then x//N<=1 passes the test but x<=N doesn't. Do you get what I am saying?

@Jitse imagine N = 11, a = 10, b = 6. Then 2^(10-6) // 11 = 16//11 = 1 but it is not true that 2^4 <= 11. Thus the inequality seems too loose.

Ruby, 64 bytes
->n{(r=*1...n).product(r).select{|a,b|b>a&&a*b%n==1&&n>=1<<b-a}}

Try it online!

Charcoal, 27 bytes
ＮθＦθＦιＦ‹›Ｘ²⁻ικθ⁼¹﹪×ικθＩ⟦⟦κι

Try it online! Link is to verbose version of code. Explanation:
Ｎθ

Input N.
ＦθＦι

Loop 0 <= a < b < N. (a=0 can never be a solution, so it doesn't hurt to include it.)
Ｆ‹›Ｘ²⁻ικθ⁼¹﹪×ικθ

Check whether 2**(b-a)<=N and a*b%N==1.
Ｉ⟦⟦κι

If so then output a and b, on separate lines, with each pair double-spaced.

Perl 6, 55 bytes
{grep {[*](@^a)%$_==1&&$_>=2**[R-](@a)>=2},(^$_ X ^$_)}

Try it online!

R, 77 64 bytes
function(N)which((o=outer(x<-1:N,x,'-'))>0&2^o<=N&x%o%x%%N==1,T)

Try it online!
Returns a matrix with columns b,a of all inverse neighbor pairs. Since it creates several NxN matrices, this will run out of memory in a hurry.

Haskell, 57 bytes
A port of my Python answer
f n=[(a,b)|a<-[0..n],b<-[0..a-1],2^(a-b)<=n,1==mod(a*b)n]

You can try it online

Husk, 24 bytes
fȯ≤¹`^2F-fȯ=1%¹F*fF>´×,ḣ

Try it online! Nothing too complicated, just the three filters applied to the list of ordered pairs.

Japt, 18 bytes
õ à2 fÈrÍ§U«1nX×uU

Try it

Wolfram Language (Mathematica), 73 71 69 bytes
n_:>Select[Range@n~Subsets~2,Mod[1##&@@#,n]==1&&2^#[[2]]<=2^#[[1]]n&]

Try it online!
Defined as a delayed rule that can be applied to any integer.


text:
Intersection of circles – How can I reduce this golf code to 127 bytes?
I started a CodeWars kata in Python, just two days ago, related to code golf.
Task: Given two congruent circles a and b of radius r, return the area of their intersection rounded down to the nearest integer, in less than 128 chars.

Has to be a one-liner.
Version: Python 3.6
External libraries: You may import NumPy as an external library.
Function name: circleIntersection
Input example: circleIntersection([0,0],[0,10], 10)

This is the closest I could come (129):
from math import*;circleIntersection=lambda a,b,r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(b[0]-a[0],b[1]-a[1])/r/2)//.5

You mention that 3.6 is the latest version provided -- is Python 2 an option? If so, I have a way to save bytes with that. It could also help to link the site's problem page if we can view that without login.

Yes, Python 2 is an option. You need to login in order to view the problem :(

Direct translation to NumPy: 127 bytes
from numpy import*
circleIntersection=lambda a,b,r:r*r*(lambda h:h<1and arccos(h)-h*(1-h*h)**.5)(hypot(*subtract(b,a))/r/2)//.5

Try it online!
Converting your code to numpy seems to save the required bytes. While using hypot is still ugly, being able to splat the result of subtract is still enough shorter that the loss of converting to arccos doesn't matter.
It is possible this can save more since it doesn't error on h<1 and will return nan in the case that the circles do not intersect. I don't know if that is permissible though since nan is not equal to zero.
I'm not convinced this is optimal, in particular I didn't look at improving the algorithm at all.

I can't thank you enough! I tried NaN in one of my desperate tries and it was not acceptable. However, your piece of code did the job and it is successfully passing all tests! It is amazing how 2 bytes kept me awake all night haha!

Subtract did the magic and I will be honest with you, this is the first time I see it. Need to dig into it and see how it works... once again, thanks for your effort and your time!

@LeooeL No problem! I found subtract in this list of numpy functions, for reference.

Use Python 2's arg unpacking: 124 bytes
from math import*;circleIntersection=lambda(v,w),(x,y),r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(v-x,w-y)/r/2)//.5

Try it online!
Python 2 has parameter unpacking, allowing the input point arguments to be taken directly as pairs (v,w) and (x,y), where the input lists like [0,0] and [0,10] will be unpacked into the respective variables. This feature was removed in Python 3 -- a pity, in my opinion, since the old syntax seems more readable. But, the site has a Python 2 option, and nothing in your solution relies on Python 3.

Works like a charm for now as sooner or later they plan to remove Python 2 from their platform. Thank you once again ^_^

This was actually the first thing I tried, but I assumed when I got a syntax error that I had just misremembered where you were allowed to do that. Thanks for finding it and explaining what had happened!

Use def: 125 bytes
You have a classic dilemma of wanting to assign to a variable without losing the brevity of a lambda function. Your method of using an inner lambda for assignment is one solution. The problem site not having Python 3.8 means the walrus operator is unfortunately off limits.
But, it's shorter here to just use def and suck up the bytes of writing out return. This is generically a 7-byte cost according to this reference. Within the def, we can just write the statement h= to do the assignment. We put everything on one line separated with ; to avoid needing to indent.
125 bytes
from math import*
def circleIntersection(a,b,r):h=hypot(b[0]-a[0],b[1]-a[1])/r/2;return(h<1and acos(h)-h*(1-h*h)**.5)*r*r//.5

Try it online! (vs original)
I've changed the multiplication order from return r*r*(...)//.5 to return(...)*r*r//.5 to cut the space after return.
There are likely other byte saves, including FryAmTheEggman's switch to numpy, but refactoring from lambda to def is already enough to get below 128 bytes.

Hello, @xnor and thank you for your time. Your idea is brilliant and so well thought, however, I do apologise as I didn't mention that another requirement is that it has to be a one-liner. Will update the description asap.

@LeooeL Ah, too bad. When you say one line, do you mean literally that the code needs to not contain any newlines? Like, if there weren't an import, would a def like here work?


text:
Shortest POSIX command line that eagerly removes dual newline sequences
Remove every pair of newline characters, that means every two newline characters appearing together are elided, whereas unaccompanied newline characters remain present.
Example:
echo -ne 'a\n\nb\nc\n\n\n\nd\n\n\n' | your-command

should output the same as
echo -ne 'ab\ncd\n'

Watch out, some POSIX tools have implementations that diverge from the standard.
Please consult https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html before submitting your solution.

Sed, 22
sed ':l;s/\n\n//;N;bl'

Try it online!
Initially I had hoped to do sed -z 's/\n\n//g' for a score of 18, but I think -z is a GNU extension and not Posix.

Sorry, it doesn't work on MacOS. -z option is not present either. (This version of sed was written by Diomidis Spinellis for FreeBSD. It's expected to be a superset of the IEEE Std 1003.2 (``POSIX.2'') specification.)

Figured it out: sed -E ':l;s/\n\n//;N;bl' on MacOS. A known bug.

Bash, 32 bytes
awk 'BEGIN{RS="\n\n";ORS="";} 1'

Try it online!

I'm not talking about practical use though. I'm saying your answer is invalid, since nothing in the challenge's spec says you can assume there's a character that's not in the input string.

See this standard loophole.

Your answer is invalid regardless of tags. Most standard loopholes (including this one) aren’t tag-specific.

@Grimmy Ah, didn't know that - thanks for bring me up to speed. :-)

@Grimmy Fixed that.

Hi @Noodle9, unfortunately this is still not a valid POSIX solution, because the b command can't be followed by a semicolon according to the spec.
"Editing commands other than {...}, a, b, c, i, r, t, w, :, and # can be followed by a ."

@ggPeti Fixed that.

I admire your perseverance.

AWK, 26 22 bytes
awk -vRS='

' -vORS= 1

Tested with gawk and mawk on MacOS.
Edit: saved 4 bytes thanks to @AndersKaseorg.

You can remove the second "" pair (−2 bytes), and you can replace the \n\n with two literal newlines (−2 bytes).


text:
Print this maximally long URL
Task
This one is simple.  We want to compress a URL, but don't trust URL shorteners.
Write a program that prints to stdout (or a 0-argument function that returns) the following, working URL:
http://a.b.c.d.e.f.g.h.i.j.k.l.m.n.oo.pp.qqq.rrrr.ssssss.tttttttt.uuuuuuuuuuu.vvvvvvvvvvvvvvv.wwwwwwwwwwwwwwwwwwwwww.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.me
Code golf, standard rules.
You may output uppercase or lowercase.
Leading or trailing whitespace is ok.
Context
Explanation taken from the website:

The domain is created to reach the maximum number of allowed characters (255 (really 253)) with an exponential curve in the length of the letters as you proceed through the alphabet. The formula used is "1 + 62 * (10/7)^(x-26)". To help illustrate this curve, reference the distribution on this spreadsheet. It's colorful because I like colors and wanted to do a progressive "rainbow" animation in CSS3.

Jesus, that sh*t crashed my browser...

05AB1E, 25 24 23 21 bytes
žXAS.7Ƶ-t∞-m>×….me¬ýJ

-1 byte thanks to @Neil's analysis that *(10/7)** is the same as /.7**.
-3 bytes thanks to @Grimmy using a different formula and ingenious use of ý!
Try it online.
Explanation:
The formula used to get the correct amount of characters of the alphabet, where \$n\$ is the 1-based index of the alphabetic letter:
\$a(n) = \left\lfloor0.7^{(\sqrt{208}-n)}+1\right\rfloor\$
žX                     # Push builtin "http://"
      Ƶ-               # Push compressed 208
        t              # Take the square-root of that: 14.422...
         ∞             # Push an infinite list of positive integers: [1,2,3,...]
          -            # Subtract each from the 14.422...: [13.442...,12.442...,...]
    .7     m           # Take 0.7 to the power of each of these: [0.008...,0.011...,...]
            >          # Increase each by 1: [1.008...,1.011...,...]
  AS                   # Push the lowercase alphabet as list of characters,
             ×         # and repeat each the calculated values amount of times as string
                       # (which implicitly truncates the floats to integers, and ignores
                       #  the floats beyond the length of the alphabet)
              ….me     # Push ".me"
                  ¬    # Push its head (the "."), without popping the ".me" itself
                   ý   # Join with delimiter. Normally it will use the top value as
                       # delimiter and joins the top-1'th list. In this case however, the
                       # top-1'th item is a string, so instead it will join the entire stack
                       # together. BUT, because the stack contains a list, it will instead
                       # only join all lists on the stacks by the "." delimiter
                    J  # And finally join the three strings on the stack together
                       # (after which this result is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ƶ- is 208.

05AB1E even has a builtin for "http://". I'm impressed

@EmbodimentofIgnorance Yep. žX is "http://"; žY is "https://" and žZ is "http://www." :)

22

21 (: Also, here's a 20 that almost works (1 extra v, 1 missing z).

@Grimmy Very nice! Both the new formula with sqrt(208) and how you've used the ý to join the list somewhere on the stack is ingenious! :D

Python 3, 86 \$\cdots\$ 81 77 bytes
Saved 3 bytes thanks to mypetlion!!!
Saved 4 bytes thanks to Shieru Asakoto!!!

print(f"http://{'.'.join(chr(i+97)*int(1+.7**-i/120)for i in range(26))}.me")

Try it online!
Uses Shieru Asakoto's 0-based formula.

81 bytes: print(f"http://{'.'.join(chr(i+122)*int(1+62*1.43**i)for i in range(-25,1))}.me")

@mypetlion Clever reshuffle of braced expressions - thanks! :-)

77 bytes when using an alternative formula.

@ShieruAsakoto Was just adding that - thanks! :-)

APL (Dyalog), 41 38 bytes
-3 bytes thanks to Bubbler
2⌽'mehttp://',∊'.',¨⍨⎕A⍴¨⍨⌊1+62×.7*⍒⎕A

Try it online!
Outputs the URL with the letters capitalised. Uses the 0 indexed formula \$ \lfloor 1 + 62 \times 0.7^{25-x} \rfloor \$, since \$ (\frac{10}{7})^{x-25} = ((\frac{7}{10})^{-1})^{x-25} = (\frac{7}{10})^{25-x}\$
Explanation:
2⌽                         ⍝ Rotate by two places (moving the 'me' to the end)
  'mehttp://'              ⍝ The start string
             ,             ⍝ Followed by
              ∊               ⍝ The flattened string of
               '.'            ⍝ A period
                  ,⍨¨         ⍝ Appended to the end of each of
                     ⎕A            ⍝ The uppercase alphabet
                       ⍴¨⍨         ⍝ Where each letter is repeated by
                          ⌊               ⍝ The floor of
                           1+             ⍝ 1 plus
                             62×          ⍝ 62 times
                                .7*       ⍝ 0.7 to the power of
                                   ⍒⎕A  ⍝ The range 26 to 1

are the final two dots in ,⍨¨ the equivalent of J's rank 0 adverb "0?  Does APL have the ability to specify other specific ranks?

@Jonah Yes, ¨ is the each function, which applies an operator to each element of the vector. I don't think you can specify rank with that specific function, though I'm not an expert with APL. Try asking Adam in chat

@Jonah f¨ is like J's stdlib's each, or f&.:>"0. The "0 part is ⍤0 in APL. Unfortunately, we don't have J's (new) L: (though I'm arguing for adding it as ⍥).

Perl 5, 61 57 55 bytes
-4 bytes thanks to @Neil
say"http://",(map{$_ x(1+62/.7**(++$p-26))."."}a..z),me

Try it online!

I think *(10/7)** is the same as /(7/10)** or /.7**.

JavaScript (Node.js), 77 bytes
Based on @ShieruAsakoto's formula. Builds the URL recursively.
f=n=>n>25?".me":(n?".".padEnd(2+.7**-n/120,Buffer([97+n])):"http://a")+f(-~n)

Try it online!

Java (JDK), 108 bytes
v->{var s="HTTP://";for(char c=64,t;++c<91;s+=(""+c).repeat(t/=Math.pow(.7,c-90))+c+".")t=62;return s+"ME";}

Try it online!
Credits

-4 bytes thanks to Kevin Cruijssen

Very likely golfable using math.

-3 byte using 62/Math.pow(.7,c-122) (credit goes to @Neil).

And an additional -1 with for(char c=96,t;++c<123;s+=(""+c).repeat(t/=Math.pow(.7,c-122))+c+".")t=62;

Charcoal, 27 bytes
http://⭆β⁺×ι⊕×⁶²Ｘ·⁷⁻²⁵κ.¦me

Try it online! Link is to verbose version of code. Explanation:
http://                     Implicitly print literal string `http://`
        β                   Lowercase alphabet
       ⭆                    Map over letters and join
                      κ     Current index
                   ⁻²⁵      Subtract from 25
                Ｘ·⁷         Raise 0.7 to that power
             ×⁶²            Multiply by 62
            ⊕               Increment
          ×ι                Repeat letter that many times
         ⁺             .    Concatenate literal string `.`
                        ¦   Implicitly print
                         me Implicitly print literal string `me`

Jelly, 49 48 46 31 bytes (send help)
A niladic link printing the URL
26RU.7*×89ĊØa×⁾meṭj”.“http://”;

-2 bytes thanks to Kevin
-15 bytes thanks to Nick!
I never wrote anything this complex in Jelly and the tacicity isn't obvious to me yet... So this is very golfable (see 49 byte link). I would appreciate feedback and golfing tips in small chunks so that I can digest it!
You can try this online.

Your https:// can be http:// ;)

@KevinCruijssen gosh, I missed this entirely :D ty

Np. Unfortunately I can't really help you with the rest, since I don't know a lot about Jelly. Only thing that comes to mind is removing the trailing ”, since it's closed implicitly to save a byte. But since my 05AB1E answer is 23 bytes, I'm sure <30 should be easily possible for Jelly as well. ;)

@KevinCruijssen I don't doubt that. It's just that Jelly is still so weird for me :p thanks for your input

Here’s a 31 byte answer for comparison. In general, it’s helpful to try to have a single link that proceeds from left to right whenever possible. Other useful hints include use of j (join) for your last line (though I’ve changed it to add the me earlier), use of the Ø nilads, reversing the order of the list rather than subtracting from 26. Happy for you to use my answer (and improve it if possible). Note it was derived from @KevinCruijsen’s answer. It’s longer because of the “http://”

@NickKennedy this was an unbelievable byte discount. I'll have to digest your submission calmly. Thanks a lot!

Wolfram Language (Mathematica), 71 bytes
"http://"<>Array[Table[Alphabet[][[#]],1+1.43^(#-26)62]<>"."&,26]<>"me"

Try it online!

C (gcc), 99 bytes
n;f(i){for(i=printf("http://");i<33;)for(n=62/pow(.7,i++-32)+2;n--;)putchar(n?89+i:46);puts("me");}

-3 or so bytes thanks to Noodle9!
-8 bytes thanks to gastropner!
Try it online!

JavaScript (Node.js), 93 bytes
_=>`http://${[...Array(26)].map((x,i)=>Buffer(Array(1+.7**-i/120|0).fill(97+i))).join`.`}.me`

Try it online!
When turning the formula into 0-indexed, the formula becomes \$1+62\times(\frac{10}{7})^{x-25}=1+0.0083146\times0.7^{-x}\$, and then 0.0083146 is approximated by 1/120.

Same length variant: _=>`http://${"abcdefghijklmnopqrstuvwxuz".replace(/./g,(x,i)=>x.repeat(1+.7**-i/120)+`.`)}me`

77 bytes

@Arnauld I suggest you post it as a separate answer because the approach is quite different on this. I've rolled back your golf to let you post it.

Japt, 29 bytes
;`http://{C®p.7**T´/#xÄ +'.}´

Saved 2 bytes thanks to @Shaggy
Test it

29 bytes?

@Shaggy Thanks, I forgot that ** exists

R, 124 115 63 bytes
This is way better than my original approach. Thanks to @Giuseppe and @Grimmy
cat("http://");cat(strrep(letters,1+62*.7^(25:0)),"me",sep=".")

Try it online!

69 bytes; feel free to come to the R golfing chat if you wanna discuss ideas there :-)

@Giuseppe 65 based on your 69.

@Giuseppe and Grimmy, thanks! Very impressive trimming.

Haskell, 86 bytes
g(c,x)=replicate(floor$1+62*1.43**x)c++"."
f="http://"++(zip['a'..][-25..0]>>=g)++"me"

Try it online!

C++ (gcc), 126 123 bytes
-3 bytes thanks to S.S. Anne
Some acrobatics needed to avoid having to include cmath.
#import<map>
using s=std::string;s f(){s r="http://";for(float i=26,p=7456;i--;p*=.7)r+=s(1+62/p,122-i)+'.';return r+"me";}

Try it online!

You could use bits/stdc++.h and use cmath's functions.

@S.S.Anne I might misunderstand you, but that would take even more bytes to include than cmath.

But not string and cmath combined. Instead of #import<string> #import<cmath> (in this hypothetical solution) you could do #import<bits/stdc++.h>.

@S.S.Anne Oh, I see what you mean! Had no idea about that one. Sadly it came out longer, doing that.

Well, then string can be replaced with map for -3 bytes.

ahem 123 bytes

@S.S.Anne Ah, nice one! Thought you were talking about the data type so had no idea where it was going :-P

Keg, 46 40 bytes
`3);://`0&(‡26   |⑻a+ⁿ⅍7
/⑻±Ëx/ℤ1+⑹*\.)`me

Try it online!
A port of the Python 3 answer by Noodle9.
-6 bytes due to using string compression and some other things

PHP, 94 bytes
for($c='a',$s='http://',$i=-26;$i++;$c++,$s.='.')for($l=62/.7**$i;$l-->=0;$s.=$c);echo$s.'me';

Try it online!
Probably still golfable, uses the formula from the question and PHP's char incrementing
EDIT: saved 3 bytes with code reorganization
EDIT2: another byte less starting from -26 and removing ($i-26)

Ruby, 64 bytes
Conveniently, when multiplying a string with a non-whole positive number, Ruby truncates the number to determine how many times to repeat the string.
puts"http://#{(?a..?z).map{|c|c*(1+62/0.7**(c.ord-122))}*?.}.me"

Try it online!

MATLAB 92 bytes
b="";for i=1:26;b=b+repelem(char(96+i),floor(1+62*(10/7).^(i-26)))+".";end;"http://"+b+"me"

Deadfish~, 809 bytes
{i}cc{{i}d}iiiic{i}iiccddddc{{d}iiiii}ddddc{d}dcc{{i}ddddd}c{{d}iiiii}dc{{i}ddddd}iic{{d}iiiii}ddc{{i}ddddd}iiic{{d}iiiii}dddc{{i}ddddd}iiiic{{d}iiiii}ddddc{{i}ddddd}iiiiic{{d}iiiii}dddddc{{i}ddddd}iiiiiic{{d}iiiii}ddddddc{{i}dddd}dddc{{d}iiii}iiic{{i}dddd}ddc{{d}iiii}iic{{i}dddd}dc{{d}iiii}ic{{i}dddd}c{{d}iiii}c{{i}dddd}ic{{d}iiii}dc{{i}dddd}iic{{d}iiii}ddc{{i}dddd}iiic{{d}iiii}dddc{{i}dddd}iiiic{{d}iiii}ddddc{{i}dddd}iiiiicc{{d}iiii}dddddc{{i}dddd}iiiiiicc{{d}iiii}ddddddc{{i}ddd}dddccc{{d}iii}iiic{{i}ddd}ddcccc{{d}iii}iic{{i}ddd}dcccccc{{d}iii}ic{{i}ddd}cccccccc{{d}iii}c{{i}ddd}i{c}c{{d}iii}dc{{i}ddd}ii{c}ccccc{{d}iii}ddc{{i}ddd}iii{c}{c}cc{{d}iii}dddc{{i}ddd}iiii{c}{c}{c}c{{d}iii}ddddc{{i}ddd}iiiii{c}{c}{c}{c}cccc{{d}iii}dddddc{{i}ddd}iiiiii{c}{c}{c}{c}{c}{c}ccc{{d}iii}ddddddc{{i}dddd}iiic{d}iic

Try it online!
E.


text:
The Magical Piper
An old test for programmers, taken from here (Note: in italian).
Along a road (denoted by '_'), there is a Magical Piper (denoted by 'P') and several mice (represented by the two characters 'o' and '~', that denote respectively the head and the tail of the small rodents).
Write a program that prints how many mice are going towards the Piper and how many mice are going away from him.
The input is a string, the output are two numbers, the first the number of mice that go towards the Piper, the second the number of mice that go away from the Piper.
The input can be also a list or vector of characters, and the output
a vector or list of two numbers. You can assume that the input is always correct.
Both programs as well as functions are allowed.
Examples:
input: __o~P_o~~o
output: 1 2
input: __P~oo~o~_o~~o__
output: 3 2
input: ~oPo~
output: 2 0
input: o~P~o
output: 0 2

This is code golf, so the shortest program in any language wins.
Note: In the question, I've removed the requirement of an error message, given the majority prefer it this way. Sorry for people that already coded the error test!

I'd prefer if there weren't error checking, but the input was guaranteed to be well formed

@Noodle9 yes to both.

@xnor, I maintaned the error to be true to the original text, but if you think that it is more interesting for this site to assume always correct input, I will change the question.

How do you check if a mouse is going towards or away from the Piper? Do you mean whether the mouse is facing away from the Piper?

Yes, if the mouse has the head is nearer than the tail to the Piper.

As for me, it would be indeed more interesting with error-checking.

Bella sfida davvero!

@LuisMendo, thanks!

@KevinCruijssen, added to the question, thanks!

Can you change the wording to either be referring to which way they're facing rather than moving? It took me a couple of reads to figure this out, because the only Piper I know of would have all the rats going towards him.

@xnor, I see. Several people asked for removing them. I agree with you, however. Don’t know what to do now.

Sorry, that was a bad typo by me, the community tends to support not requiring validation.  The linked post was under "things to avoid".

Ah, ok. In any case I think the best thing to do is to left everything as it is now.

Ruby, 128 .. 51 49 bytes
->w{%w(o ~).map{|c|w.scan(/_*._*(.)/).count [c]}}

Try it online!
No error checking.
How:

Ignore all underscores
All mice going towards the piper have the head in an odd-numbered (0-based) position.
All mice heading away from the piper have the tail in an odd-numbered position.
Take every 2nd character (skipping underscores), count heads and tails.

Ruby (with error checking), 109 99 97 bytes
->w{w.chars+w.scan(/[o~]./)-%w(o ~ _ ~o o~)==[?P]?%w(o ~).map{|c|w.scan(/_*._*(.)/).count [c]}:q}

Try it online!
Thanks Value Ink for -2 bytes on both.

[?o,?~].map [...] .count [c] saves 2 bytes.

05AB1E, 13 11 10 bytes
'_KāÈÏaTS¢

Port of @GB's Ruby answer, so make sure to upvote him!!
-1 byte thanks to @Grimmy by taking the input as character-list.
Try it online or verify all test cases.
Explanation:
'_K        '# Remove all "_" from the (implicit) input-list
   ā        # Push a list in the range [1, length] (without popping the list)
    È       # Check for each whether it's even
     Ï      # Only keep the characters at these even 1-based indices
      a     # Check for each remaining character whether it's a letter or not
            # (1 if 'o'; 0 if '~')
       TS   # Push 10 as digit-list: [1,0]
         ¢  # And count each in the list of 0s and 1s
            # (after which this pair of counts is output implicitly as result)

-1 by taking input as a character list

@Grimmy Ah, smart use of the aTS, thanks!

JavaScript (Node.js),  80 66 65 58  57 bytes
Returns [towards, away].
s=>Buffer(s).map(c=>c%3?i^=~c:a[c&1]+=++i&1,a=[i=0,0])&&a

Try it online!
How?
An efficient way to determine whether the character is a mouse body part is to take the ASCII code modulo \$3\$.
Quite conveniently, we can also distinguish between P and _ or between o and ~ by simply testing the parity of the corresponding ASCII codes.
 character  | 'P' | '_' | 'o' | '~'
------------+-----+-----+-----+-----
 ASCII code |  80 |  95 | 111 | 126
 modulo 3   |   2 |   2 |   0 |   0
 modulo 2   |   0 |   1 |   1 |   0

Commented
s =>                       // s = input string
  Buffer(s)                // turn s into a buffer
  .map(c =>                // for each ASCII code c:
    c % 3 ?                //   if c modulo 3 is not equal to 0:
      i ^= ~c              //     invert the least significant bit of i if c is even
                           //     (must be 80, for 'P')
    :                      //   else:
      a[c & 1] += ++i & 1, //     update a[0] if c is even (126 -> '~')
                           //     or a[1] if c is odd (111 -> 'o')
                           //     increment i and add its parity
    a = [i = 0, 0]         //   start with a = [0, 0] and i = 0
  ) && a                   // end of map(); return a[]

JavaScript (Node.js),  112  102 bytes
A version with error checking, as per the original rules of the challenge.
s=>Buffer(s).some(c=>n?n-=c:c-111&&c-126?c-95?c-80|p++:0:!++a[n=c^17,p^c&1],a=[n=0,p=0])|p-1?'error':a

Try it online!

@KevinCruijssen Thanks! But I was already editing to another 57.

Then I'll post it as a separated answer. :)

Python 2, 47 bytes
Port of G B's Ruby answer.
lambda s:map(s.replace('_','')[::2].count,'~o')

Try it online!

Python 2, 252 \$\cdots\$ 71 72 bytes
Saved 29 bytes thanks to JoKing!!!
Saved 2 bytes thanks to ovs!!!
Saved a byte thanks to ReinstateMonica!!!
Saved 21 bytes thanks to KevinCruijssen!!!
Added a byte to fix a bug kindly pointed out by JoKing.
def f(s):
 r=[0,0];i=0
 for c in s:
	if'_'!=c:r[c>'o']+=i;i^=1
 return r

Try it online!
Inputs a string and outputs a list.

@JoKing Very clever stuff - thanks! :-)

93 bytes with '~'==c -> c>'o' and i=1-i -> i^=1.

def f(s,i=1,r=[0,0]): also saves a byte over assigning i and r in the function

@ovs Nice golfs - thanks! :-)

@Noodle9 bet

@ReinstateMonica I stand happily corrected! :-)

'P'==c can be 'Q'>c to save a byte.

And an additional -19 bytes by removing the if'P'==c:r=r[::-1] line completely and modifying the other line a bit. Since P is guaranteed to be at an even index if we ignore all _, the character P will always result in an i=0 increase, so it won't matter for the r[c>'o']+=i;. Now it's basically a port of my Java 8 answer. :)

Oh, and you could save a 21st byte by using Python 2 instead of Python 3, in which case you can change the indentation of 2 spaces into an indentation of a single tab.

@KevinCruijssen Wow! That's truly diabolical - thanks! :-)

@JoKing Ah, missed that - thanks ! :-)

J, 27 19 bytes
[:+/_2=&'~'\'_'-.~]

Try it online!
This took inspiration from both Kevin's answer and GB's answer.
how
We'll work through an example: __o~P_o~~o

'_'-.~] Remove the underscores:
o~Po~~o

_2=&'~'\ For every two characters, create a boolean mask where 1 indicates that the character in that position is ~:
0 1  o~
0 0  Po
1 1  ~~
0 0  o

[:+/ Sum the colums:
1 2

Retina, 31 bytes
+`o~(?!o)
1
T`1~`~1`.*P
*\C`1
~

Try it online!
Explanation
+`o~(?!o)
1

Recursively replace all mice walking to the left with a 1. Mice walking to right stay as they are.
T`1~`~1`.*P

Swap 1 and ~ at all positions up to the P.
*\C`1

Every 1 stands for a mouse walking towards the Magical Piper. Count the 1's and output the result without changing the current string.
~

Count ~'s (implicit output). every ~ stands for a mouse walking away from the Magical Piper.

Retina, 23 18 bytes
port of G B's Ruby answer. 5 bytes shorter thanks to Neil.
_

(.).
$1
*\C`~
o

Try it online!

It's golfier to delete even-numbered characters: Try it online!

@Neil This looks much better. thanks a lot.

C (gcc),  87  85 bytes
Saved 2 bytes thanks to @xibu
Prints the results as towards away.
a,b,p;f(char*s){for(a=b=p=0;*s;s++)*s%3?p|=~*s:p+*s++&1?b++:a++;printf("%d %d",a,b);}

Try it online!
Commented
a,                       // a = 'towards' counter
b,                       // b = 'away' counter
p;                       // p = piper flag
f(char *s) {             // f is function taking a pointer to a string s
  for(                   // main loop:
    a = b = p = 0;       //   start with a = b = p = 0
    *s;                  //   go on while the end of the string is not reached
    s++                  //   advance the pointer after each iteration
  )                      //
    *s % 3 ?             //   if the current character is not a mouse body part:
      p |= ~*s           //     set the piper flag if the ASCII code is even (80 -> 'P')
    :                    //   else:
      p + *s++ & 1 ?     //     test the parity of (p + current ASCII code) and advance
                         //     the string pointer to skip the next body part
                         //     if odd:
        b++              //       increment b
      :                  //     else:
        a++;             //       increment a
  printf("%d %d", a, b); // print the results
}                        //

C (gcc),  72  70 bytes
Saved 2 bytes thanks to @mypronounismonicareinstate
This version saves the results in an array passed as a 2nd argument. I don't know for sure if it's acceptable.
p;f(char*s,int*r){for(*r=r[1]=p=0;*s;s++)*s%3?p|=~*s&1:r[p^*s++&1]++;}

Try it online!

per I/O rules, the second variant is acceptable, but I think you should keep the original entry somewhere in the answer.

I think r[0] -> *r in the second program.

suggestion for -2 Bytes TIO

The typeless variables are certainly not C++, is that a C feature? Also could you please explain what your code is doing?

@VaradMahashabde There's no such thing as a typeless variable in C, but the default type is int when it's not specified. (Of course, you should not do that in any serious piece of code.) I've added a commented version. You may also see my JS answer for more details about the ASCII code logic.

Nice! I didn't understand what you were doing, but I have implemented the same. Well, your C code would win both C and C++ categories!

JavaScript (Node.js), 57 54 bytes
s=>Buffer(s).map(c=>a[~c&1]+=c%19&&i++%2,a=[i=0,0])&&a

Alternative JavaScript answer for the existing JavaScript answer (of equal byte-count at time of writing), which I figured was worth posting as separated answer. Loosely based on my Java 8 answer and inspired by @GB's Ruby answer.
-3 bytes thanks to @Arnauld.
Try it online.
Explanation:
s=>                 // Method with string as parameter and integer-array as result
  Buffer(s).map(c=> //  Loop over the characters in the String as codepoint integers:
    a[~c&1]+=       //   Increase the count at index (c+1)%2 by:
      c%19&&        //    If c modulo-19 is NOT 0:
            i++%2,  //     Add i%2 to the count, and increase i by 1 afterwards
    a=[i=0,0]       //  Start the counts at [0,0] and i at 0
  )&&a              //  After the loop, return this resulting pair of counts

The codepoints of the four used characters are 'P'=80, '_'=95, 'o'=111, '~'=126, which I'm using to my advantage:

The ~c&1 will result in index 0 for the character 'o' and index 1 for character '~'. (It will also result in index 1 for character 'P' and index 0 for character '_', but this won't cause any issues.)
The modulo-19 is to ignore '_' characters. Using the modulo-19 on the four codepoints results in 4,0,16,12 for P_o~ respectively, for which the '_' is falsey and the other three are truthy.

The i++%2 will only add 1 to the count for odd-indexed characters. All even-indexed characters won't affect the counts. Since the 'P' is guaranteed to be at an even-indexed position (when ignoring the '_' with c%19&&), the count for character 'P' will always increase by 0, and thus stay the same.

54 bytes

@Arnauld Thanks! I had the feeling a=[i=0,0] might have been possible somehow like in your answer, but couldn't figure it out. Now that I see the i++%2 I can't believe I hadn't thought of it just yet. And nice ~c&1 trick!

JavaScript (ES6)
Port of G B's Ruby answer.
a=>a.filter(v=>v!='_').map((v,i)=>i%2||v=='P'?0:a[+(v=='o')]++,a=[0,0])&&a

Burlesque, 11 bytes
'_;;\[2enf:

Try it online!
Using the algorithm of G B's answer
Burlesque, 24 bytes
'P;;^p<-_+'_;;m{2co}FLf:

Try it online!
Without error checking.
'P;;   # Split at P
^p<-   # Reverse those following the piper
_+     # Rejoin
'_;;   # Remove all road
m{2co} # Split each into pairs (i.e. mice)
FL     # Flatten array
f:     # Count mice

Burlesque, 44 bytes
'P;;sa2!=qpPif^p<-_+'_;;m{2co}FLf:sa2!=qpPif

Try it online!
With error checking. As above but with checks to see if lists are correct lengths and throw impossible action if not, halting execution.

05AB1E, 17 bytes
'P¡`RJ'_K2ô„~oÂ‚¢

Try it online!

MATL, 25 bytes
80&Yb"@g'o~'&mXz2eq!Xs]P+

Try it online!

@Arnauld is indeed correct. I.e. o~P~o should result in 0 2 and ~oPo~ should result in 2 0, but they both result in 1 1 in your answer.

Thanks for noticing! My bad

Solved now, with a few more bytes

PHP, 108 bytes
for(;$b=$argn[$j++];){$b!='P'?:$p++;$b=='~'?($p&++$j?$m++:$n++):($b!='o'?:($p&++$j?$n++:$m++));}echo"$n $m";

Try it online!
Back to more serious golfing, ends like a port of Noodle9's original answer (but much more readable)
ORIGINAL VERSION:
PHP, 156 bytes
$a=explode('P',$argn);for($i=2;$i--;$j=0)for($b=$a[$i];$b[$j];){$t=$b[$j].$b[++$j];if($t=='~o')$i&++$j?$n++:$m++;if($t=='o~')$i&++$j?$m++:$n++;}echo"$n $m";

Try it online!
Ok, this is really horrible and far from optimal, but I had real fun writing this unreadable atrocity. Forgive me :D (the reason behind the explode was to check validity for original post rule of only one P in the string)
EDIT: ORIGINAL VERSION WITH ERROR CHECKING (displays 0 on error)
PHP, 213 bytes
$a=explode('P',$argn);for($i=0;isset($a[$i]);$j=0,++$i<3?:die(0.))for($b=$a[$i];$b[$j];){strpos(" _~o",$b[$j])?:die(0.);$t=$b[$j].$b[++$j];$t=='~o'?($i&$j++?$m++:$n++):($t!='o~'?:($i&$j++?$n++:$m++));}echo"$n $m";

Try it online!
Caveat: won't display the zero results, but ,$n=0,$m=0 can be added after $i=0 to make it so.

GolfScript, 46 bytes 36 bytes
1/{"_"=!},'P'%~-1%+2/.{"~o"=},,.@,\-

Significant improvement from my previous algorithm. Enough so that I'm willing to actually explain it.
1/                                     #Split the string into an array of chars
  {"_"=!},                             #Replace the prev array with one without underscores
          'P'%~                        #Split the array at the piper
               -1%                     #Reverse the second array (right side)
                                       #This has the function of making all correct mice
                                       #face the same way, which makes for easier matching
                  +                    #Concatenate
                   2/                  #Split the array into groups of two
                                       #so we only an array of mouse-strings!
                     .                 #Duplicate our array, since we have to count twice
                      {"~o"=},,        #First count all valid mice
                               .       #Duplicate that count
                                @,     #Bring back that second array and count the mice
                                  \-   #Subtract (correct mice) from (all mice)
                                       #which only leaves (correct mice) then (wrong mice)

Python 3.8, 62 bytes
lambda s:((v:=s.replace("_","")[::2]).count("o"),v.count("~"))

You can try it online. Link has two extra bytes to give a name to the function.
Port of this Ruby answer, so be sure to upvote it as well!

Your TIO link shows an error.

@xnor thanks for catching that! corrected.

Pyth, 14 bytes
/J%2-z\_\~/J\o

Try it online!
A port of @GB's wonderful Ruby answer, go give him your upvotes!
Terrible explanation:
/       \~      // Count the occurrences of "~" in:
 J              // J=
  %2            // Every second character of
    -z\_        // every character of the input not in "_"
                // Implicit print
          /J\o  // Count the occurrences of "o" in J
                // Implicit print

Jelly, 14 13 10 bytes
A monadic link taking the string as input.
ḟ”_m2ċⱮ⁾~o

You can try it online.
Port of this Ruby answer so check it as well!
ḟ”_         remove all the underscores from the string

   m2       Then take a slice modulo 2 and
                for what remains
      Ɱ“~o  go over the characters ~ and o
     ċ      counting how many times they show up.

Output is [towards, away].
-3 bytes thanks to @Jonathan and @Nick.

You have the wrong quoting instruction on the right (“ should be ⁾). Save two bytes using modulo-indexing by two after dequeuing TIO

@JonathanAllan thanks! I looked for something like m2 but couldn't find it and so went for my lengthier version :p thanks!

PowerShell, 46 42 bytes
Inspired by G B
$a=,0*7
$args|%{$a[$i++%2+$_%6]++}
$a[4,1]

Try it online!
    | ascii | %6 | even | odd
 -----------------------------
  P |   80  |  2 |   2  |  3
  _ |   95  |  5 |   5  |  6
  o |  111  |  3 |   3  |  4
  ~ |  126  |  0 |   0  |  1

The 4 and 1 are odd-numbered positions from the G B answer. No error checking.

PowerShell, 46 bytes
switch($args|?{$i++%2}){o{$t++}~{$a++}}+$t;+$a

Try it online!

Sorry for casting a down vote; it was an accident! Could you please edit it slightly so that downvote is unlocked?

K (ngn/k), 18 bytes
{+/2!0N 2#0,x^"_"}

Try it online!
{ } function with argument x
x^"_" remove all _s
0, prepend a 0
0N 2# split in pairs
2! mod 2 as ascii codes: P→80→0, o→111→1, ~→126→0
+/ sum

Unix TMG, 115 bytes
p:ignore(<<_>>)r<P>[a=^t][t=^a][a=^t]r parse(d);r:<o~>[t++]r|<~o>[a++]r|();a:0;t:0;d:decimal(t)decimal(a)={2< >1};

Expanded:
p:ignore(<<_>>)r<P>[a=^t][t=^a][a=^t]r parse(d);
r:<o~>[t++]r|<~o>[a++]r|();
a:0;
t:0;
d:decimal(t)decimal(a)={2< >1};

Python 3, 86 bytes
m=input()
n=m.index('P')
c=count
t=m[:n].c('~o')+m[n:].c('o~')
a=m.c('~')-t
print(t,a)

Try it online!
Takes in the string, and finds the location of the Piper. Then just counts the number of mice behind him facing forwards, plus the number of mice ahead of him facing backwards - this is the total number of mice facing towards him. The number of mice facing away is just the total number of mice (the total number of '~'s) minus the number facing him.
Uses c to replace the count function, for byte saving.

Your TIO link gives an error when input is provided. To alias count, you'd need to refer to str.count.

Java 8, 72 71 bytes
s->{int i=1,r[]=new int[2];for(int c:s)r[~c&1]+=c!=95?i^=1:0;return r;}

Port of @GB's Ruby answer, so make sure to upvote him!!
-1 byte thanks to @Arnauld.
Try it online.
Explanation:
s->{               // Method with char-array parameter and int-array return-type
  int i=1,         //  Toggle integer, starting at 1
   r[]=new int[2]; //  Result int-array of size 2, filled with 0s by default
  for(int c:s)     //  Loop over the input char-array:
    r[~c&1]+=      //   Increase the count at index (c+1)%2 by:
      c!=95?       //    If the character is NOT '_':
            i^=1   //     Toggle the integer (1→0 or 0→1), and add that to the current count
                   //     this will only add 1 for every odd-indexed character, ignoring '_'
           :       //    Else:
            0;     //     Keep the count the same by increasing with 0
  return r;}       //  And finally return this resulting pair of counts

C++ (gcc), 189 184 170 bytes
#include <string>
struct a{int t;int f;};a f(std::string s){a r={0,0};for(int i=0,d=1;i<s.length();++i)s[i]%3?s[i]%2?1:d=0:s[i++]%2?d?r.f++:r.t++:d?r.t++:r.f++;return r;}

Try it online!
Expanded Version (Full Program) :
// Example program
#include <iostream>
#include <string.h>
using namespace std;

struct pseudo_arr {int to_piper; int from_piper;};
pseudo_arr countRats(string s) {
  pseudo_arr rats = {0,0};
  int direction = 1;
  for(auto i = s.cbegin();i!=s.cend();++i) {
    // Exploitable properties of the 4 characters
    // 'P' == 80  - %3 == 2, %3 == 0
    // '_' == 95  - %3 == 2, %2 == 1
    // '~' == 126 - %3 == 0, %2 == 0
    // 'o' == 111 - %3 == 0, %2 == 1
    switch(*i) {
      case 'P' : // char(80) == 'P'
        direction = 0; // Crossed piper, change direction
        break;
      case 'o' :
        // If see head, skip tail
        ++i;
        // if before piper then away, else towards
        direction ? rats.from_piper++ : rats.to_piper++;
        break;
      case '~' :
      // if see tail, skip head
        ++i;
        // if before piper then towards, else away
        direction ? rats.to_piper++ : rats.from_piper++;
        break;
    }
  }
  return rats;
}

int main() {
  string input;
  getline(cin, input);
  pseudo_arr rat_count = countRats(input);
  cout << rat_count.to_piper << " " << rat_count.from_piper;
}

166 bytes

@ceilingcat Nice char-int conversion! I should have realised the curly braces on my own . But how come it works with #include <string.h> removed?

I don’t think you’re using anything in string.h

@ceilingcat I am using std::string, but for some implementations <string> is included inside <iostream>. But not all. I could save a couple by removing the .h

Z80Golf, 28 bytes
00000000: 1680 cd03 8030 0578 ff79 ff76 fe5f 28f0  .....0.x.y.v._(.
00000010: 1930 ed0c fe7e 28e8 0d04 18e4            .0...~(.....

Try it online!
start:
  ld d, $80
  call $8003
  jr nc, ok
results:
  ld a, b
  rst $38
  ld a, c
  rst $38
  halt
ok:
  cp '_'
  jr z, start
  add hl, de
  jr nc, start
  inc c
  cp '~'
  jr z, start
  dec c
  inc b
  jr start

Prints two bytes: towards and away.
One maybe-clever trick here is using add hl, de as a sort of flip-flop mechanism. Since de is fixed to $8000, it will overflow and set the carry flag every other time.