text:
Tips for golfing in Keg
What general tips do you have for golfing in Keg? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Keg (e.g. "remove comments" is not an answer).
Please post one tip per answer.

It's not a great idea to accept an answer for a tips question

Brackets autocomplete
This is my biggest tip for anyone golfing in Keg: when writing programs, brackets used in loops or if-statements are automatically balanced if there are unclosed brackets.
For example:
(9|0.)

Can be shortened to:
(9|0.

And:
{:1=[1.]}

Can be shortened to:
{:1=[1.

Use Unicode characters when possible
In Keg, you can represent large constants using simply Unicode characters. Sometimes this is really hard to do, sometimes it is easy and can lead to creative solutions. And there is almost nothing to say about this; this is a canonical feature for golfed Keg programs.

With the SBCS this no longer applies

Just make sure you clarify that you are using an old version of Keg if you are using this tip.

Using the ; operator
The ; operator in Keg can be very powerful. For example for building NOT gates for if statements;
11$-[Blah|Blah2]

Can be golfed into:
1;[Blah|Blah2]

There's A Dictionary!
Like other golfing languages, Keg has a built-in ~60.5k word (~6.05 times better than 05AB1E's) dictionary that is available to be used. There are 6 ways to access the goodness that is words.txt:

Standard Spaceless Strings (Done with backticks)
Standard Spaceful Strings (Done with ¶)
SCC-Only Spaceless Strings (Done with ‘)
SCC-Only Spaceful Strings (Done with “)
Special Spaceless Strings (Done with „)
Special Spaceful Strings (Done with «)

Note that when the terms spaceful and spaceless are used, they refer to whether or not the string will place spaces between string compression codes when expanding.
I feel like I should take the time to explain what String Compression Codes are:
Every word within the Keg dictionary has a two byte code associated with it. These range from 00 through to ↫↫. When the uncompressor sees a string, it will go through and expand each SCC with it's corresponding word from the dictionary (for example, H% is Hello, c¡ is World and 5Ƴ is Good). Even though all of the examples had uppercase letters, there are words starting with lower case letters.
Obtaining SCCs
The best and easiest way to find out what the required SCCs for programs is to navigate to uncompress.py and run the program (preferably in some sort of terminal/something that isn't IDLE). "But that's a library, not a user-friendly program!", I hear you say. Well, when run by a user as a program, it will branch into if __name__ == "__main__" and run a helpful session for golfing. If a word is in the dictionary, the corresponding SCC will be printed (single character SCCs start with 0), otherwise, -1 will be printed. Here's an example session:
Enter a search term: Hello
H% [43, 66]

Enter a search term: world
⬥ [188]

Enter a search term: Keg
-1

Enter a search term: keg
←z [130, 35]

Enter a search term: Um
-1

Enter a search term: Keg
-1

Enter a search term: isn't
4 [4, 239]

Enter a search term: in
-1

Enter a search term: the
0 [0]

Enter a search term: dictionary
V¿ [57, 88]

Don't mind the fact that Keg isn't in the dictionary.

I feel like the amount of words in the dictionary does not mean it is a good dictionary. The extra words occur in strings less frequently and will be used less (they will be too space-consuming too).

Use Functions where possible
Functions are defined using @ and store code that would potentially be repeated many times.


text:
Duck, duck, gone!
Here is the (quite scary) Five little ducks song(it is not long):
Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.

Four little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only three little ducks came back.

Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.

Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.

One little duck went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but none of the little ducks came back.

Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.

Your task is not to output this song. You should take a verse and output the next verse, cyclically (the next verse of the last verse is the first verse).
Rules

No standard loopholes, please.
Input/output will be taken via our standard input/output methods.
The exact verse must be outputted, and there should be no differences when compared to the song lyrics. The input will not be different when it is compared to the song lyrics too.

Examples
Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.

Expected:
Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.

Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.

Expected:
Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.

The Catalogue
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](https://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 193467; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

I remember the words to this being slightly different when I was young, many moons ago. But I also remember being traumatised by it! Where were those missing ducklings for all those days?! Why was nobody out looking for them?! And what sort of irresponsible mother manages to lose so many children and keeps letting the rest of them out to play?! The horror!

Possible duplicate. Just kidding :)

That song lyrics sure made me go through a roller coaster of emotions.

I listened to the YouTube video I posted here yesterday, twice, just twice. Now that song is embedded into my brain, anywhere I go, anything I do, I keep hearing it! Help...

@Shaggy This one is just as bad...  Lots of negligent parenting in childrens' poetry...

Nice challenge! Outputting the next verse is a really novel and creative twist on text-printing.

Any reason the capitalization on "Mother duck" and "Mother Duck" is different in the 2 places it is used in the last verse?

Stax, 115 111 bytes
τ*^&k─Zè0µ9┬$█◘çl╟☼:Drσ59ò╠▄┴╢Q♂╔¡ô╜Oa╣▀yèA÷╨%^♀█Ö+╡◄ì=∙%╧o▌Θ<▲Çα¿╗√;1°┼╤V◘ú┐♥▒ÇM☼b╩░o]YaL4░ƒ%(Æ♫Q0æÆä⌂¡╘○Eâó╪¡

Run and debug it
All the verses as test cases

When you run it with "One little duck", it responds "little ducknd little duckll of the little ducks came back." in the last line.

The bug has been fixed at no cost in size.  It was actually about a 2-byte cost, and and offsetting 2-byte savings elsewhere, although bytes are kind of hard to measure here, since the changes aren't exactly byte aligned inside compressed string literals, or even in the final program.

JavaScript (ES9), 227 bytes
This is similar to the Node version below but uses a formula based on parseInt() instead of Buffer() to identify the input verse.
This is ES2018 (aka ES9) because we're using a regular expression with the /s flag (dotAll).
s=>'Mother duck herself1and all23,,Three4two3,Five4four3,Four4three3,One01but none23,Two4one0'.split`,`[parseInt(s,30)&7].replace(/\d/g,n=>[x=' little duck',y=/ w.*\n/s.exec(s),' of the',x+='s',x+y+'but only '][n])+s.slice(-11)

Try it online!
How?
In this version, we parse the entire input verse as base 30 (0 to t) and perform a bitwise AND with 7. The parsing stops on the first invalid character, leading to:
 verse | valid part | base 30 -> decimal | AND 7
-------+------------+--------------------+-------
   0   |  'fi'      |            468     |   4
   1   |  'fo'      |            474     |   2
   2   |  'three'   |       23973734     |   6
   3   |  't'       |             29     |   5
   4   |  'one'     |          22304     |   0
   5   |  'mother'  |      554838747     |   3

JavaScript (Node.js),  233 231  227 bytes
Saved 2 bytes thanks to @Shaggy
s=>'Three4two3,Four4three3,Mother duck herself1and all23,One01but none23,,,Two4one0,,Five4four3'.split`,`[Buffer(s)[2]%9].replace(/\d/g,n=>[x=' little duck',y=/ w.*\n/s.exec(s),' of the',x+='s',x+y+'but only '][n])+s.slice(-11)

Try it online!
How?
The third character of each input verse can be used as a unique identifier. By taking its ASCII code modulo 9, we get:
 verse | 3rd char. | ASCII code | MOD 9
-------+-----------+------------+-------
   0   |    'v'    |     118    |   1
   1   |    'u'    |     117    |   0
   2   |    'r'    |     114    |   6
   3   |    'o'    |     111    |   3
   4   |    'e'    |     101    |   2
   5   |    't'    |     116    |   8

The output verses are encoded with the following templates:
 verse | template
-------+---------------------------------
   0   | 'Five4four3'
   1   | 'Four4three3'
   2   | 'Three4two3'
   3   | 'Two4one0'
   4   | 'One01but none23'
   5   | 'Mother duck herself1and all23'

Where each digit is replaced with a string according to the following table:
 digit | replaced with
-------+---------------------------------------------------
   0   | ' little duck'
   1   | / w.*\n/s.exec(s)
   2   | ' of the'
   3   | ' little ducks'
   4   | ' little ducks' + / w.*\n/s.exec(s) + 'but only '

Where the regular expression / w.*\n/s extracts this common part from the input:
  went out one day,[LF]
 over the hills and up away.[LF]
 Mother Duck said, "Quack Quack Quack Quack",[LF]

We finally add the last 11 characters of the input, which is " came back.".

231

@Shaggy Nicely done. Thanks!

Was just posting another comment to suggest exec when the page reloaded. Great minds ... !

Python 3, 267 263 254 bytes
4 bytes saved thanks to @ovs
def f(s):
 for a in zip(T[2:]+T,T):s=s.replace(*a)
 return s
T="8:9:and allHO1BnoneHT2No1T3Nt2F4Nt3FiveINf4MotherD herself"
for r in "H of theI,4ourI,3hreeI,2woI,1neL:,ILs:,L littleD,D duck,NBonly ,Bbut ".split(','):T=T.replace(r[0],r[1:])
T=T.split(':')

Try it online!
Works by replacing the relevant parts by the respective parts of the next verse.
After the preinitialisation, T is ['8', '9', 'and all of the little ducks', 'One little duck', 'but none of the little ducks', 'Two little ducks', 'but only one little duck', 'Three little ducks', 'but only two little ducks', 'Four little ducks', 'but only three little ducks', 'Five little ducks', 'but only four little ducks', 'Mother duck herself'].
Alternative Python 2, 252 bytes
by @ovs
lambda s:reduce(lambda s,a:s.replace(*a),zip(T[2:]+T,T),s)
T="8:9:and allHO1BnoneHT2No1T3Nt2F4Nt3FiveINf4MotherD herself"
for r in "H of theI,4ourI,3hreeI,2woI,1neL:,ILs:,L littleD,D duck,NBonly ,Bbut ".split(','):T=T.replace(r[0],r[1:])
T=T.split(':')

Try it online!

for a in zip(T,T[-2:]+T):s=s.replace(*a) for 264 bytes.

Or lambda s:reduce(lambda s,a:s.replace(*a),zip(T,T[-2:]+T),s) for 262 bytes in Python 2.

@ovs Thanks, I got it to 263 with reodering some things and using T[2:] instead of T[-2:]

QuadR, 257 242 bytes
-14 thanks to Black Owl Kai, -1 thanks to Kevin Cruijssen
ive
Four
hree
Two( little duck)s
One little( duck)
Mother( duck) herself
four
two( little duck)s
only on(e little duck)
but none
and all of the
our
Three
wo
One\1
Mother\1 herself
Five little\1s
three
one\1
none of th\1s
and all
but only four

Try it online!

243 bytes

242 bytes

T-SQL, 407 390 388 382 bytes
DECLARE @ CHAR(999)=REPLACE(REPLACE('SELECT CASE LEFT(v,2)WHEN''Fi74,''Four''),122,4,''three'')WHEN''Fo74,''Three''),123,5,''two'')WHEN''Th75,''Two''),121,16,''on#'')WHEN''Tw716,''On#''),115,20,''none of th#s'')WHEN''On715,''Mother duck herself''),115,8,''and all'')WHEN''Mo719,''Fiv#s''),113,14,''but only four'')END FROM i',7,'''THEN STUFF(STUFF(v,1,'),'#','e little duck')EXEC(@)

Input is via a pre-existing table \$i\$ with VARCHAR(MAX) field \$v\$, per our IO rules.
After a couple of byte-saving REPLACEs, executes the following as dynamic SQL:
SELECT CASE LEFT(v,2)
       WHEN'Fi'THEN STUFF(STUFF(v,1,4,'Four'),122,4,'three')
       WHEN'Fo'THEN STUFF(STUFF(v,1,4,'Three'),123,5,'two')
       WHEN'Th'THEN STUFF(STUFF(v,1,5,'Two'),121,16,'one little duck')
       WHEN'Tw'THEN STUFF(STUFF(v,1,16,'One little duck'),115,20,'none of the little ducks')
       WHEN'On'THEN STUFF(STUFF(v,1,15,'Mother duck herself'),115,8,'and all')
       WHEN'Mo'THEN STUFF(STUFF(v,1,19,'Five little ducks'),113,14,'but only four')END
FROM i

Uses a CASE statement and STUFF commands to insert/overwrite characters at the listed positions.
EDITS:

Replace original (below) with an entirely different strategy
Saved two bytes by switching to LEFT instead of SUBSTRING and eliminating a space
Saved 6 bytes by changing variable to CHAR and moving an extra letter into the second REPLACE (thanks, @CDC!)

Here's my first version, using a different method (post-replacement, formatted):
DECLARE @ VARCHAR(MAX)
SELECT @=v FROM i
SELECT @=REPLACE(@,PARSENAME(value,2),PARSENAME(value,1))
FROM string_split('e.but none.and all
                  -e.One little duck.Mother duck herself
                  -o.only one little duck.none of the little ducks
                  -o.Two little ducks.One little duck
                  -r.two little ducks.one little duck
                  -r.Three.Two
                  -u.three.two
                  -u.Four.Three
                  -v.four.three
                  -v.Five.Four
                  -t.and all of the.but only four
                  -t.Mother duck herself.Five little ducks','-')
WHERE LEFT(value,1)=SUBSTRING(@,3,1)
PRINT @

STRING_SPLIT and PARSENAME are used to break a string into rows and columns via - and . separators.
The first column is a key character that is matched against the 3rd letter of the input verse (thanks for the idea, @Night2). The second and third are the replacements being performed for that verse.

First solution, if you use "CHAR(700)" instead of "VARCHAR(MAX)" you can save 3 bytes.  Also in your " little duck", you can instead do "e little duck" and remove the e before # on each replacement to get another 3.

BTW, really fun solution.  I used formatmessage to get very close to you, but not quite.

Good suggestions, @CDC, thanks!

Java 10, 347 bytes
s->{String L=" little duck",M="Mother duck herself";int i=9;for(var t:("ive;Four;hree;Two"+L+"s;One"+L+";four;two"+L+"s;only one"+L+";but none;and all of the;"+M).split(";"))s=s.replace(t,++i+"");for(var t:("Five"+L+"s;but only four;and all;none of the"+L+"s;one"+L+";three;"+M+";One"+L+";wo;Three;our").split(";"))s=s.replace(i--+"",t);return s;}

Try it online.
Explanation:
We first replace all parts one by one with integers in the range \$[10,21]\$, and then these integers back to their replacements. The reason this is done in two steps, is because we would otherwise replace replacements.
s->{                     // Method with String as both parameter and return-type
  String L=" little duck",M="Mother duck herself";
                         //  Two temp strings to save bytes
  int i=9;               //  Temp replacement integer, starting at 9
  for(var t:("ive;Four;hree;Two"+L+"s;One"+L+";four;two"+L+"s;only one"+L+";but none;and all of the;"+M).split(";"))
                         //  Loop over the parts to replace:
    s=s.replace(t,       //   Replace the part,
                ++i+""); //   with the integer pre-incremented by 1
  for(var t:("Five"+L+"s;but only four;and all;none of the"+L+"s;one"+L+";three;"+M+";One"+L+";wo;Three;our").split(";"))
                         //  Then loop over the parts to replace with in reverse:
    s=s.replace(i--+"",  //   Replace the (post-decrementing) integer,
    t);                  //   with the replacement-part
  return s;}             //  And then return the modified String as result

PHP (7.4), 253 247 bytes
-6 bytes by improving how the replacements array is built with more help from "Unpacking inside arrays".
<?=strtr($argv[1],array_combine([0,1,...$a=[Five.$l=($o=" little duck").s,($b="but only ").four.$l,Four.$l,$b.three.$l,Three.$l,$b.two.$l,Two.$l,$b.one.$o,One.$o,"but none of the$l","Mother duck herself","and all of the$l"]],[...$a,$a[0],$a[1]]));

Try it online!
This creates an array of every possible replacement (12 used + 2 unused) in a key=>value format. Example: ['Mother duck herself' => 'Five little ducks', etc...] and then just replaces those using strtr.
The only interesting thing is my first ever usage of "Unpacking inside arrays" which is a new feature in PHP 7.4.

PHP, 264 bytes
<?=str_replace(($a=[[Five.$l=($o=" little duck").s,($b="but only ").four.$l],[Four.$l,$b.three.$l],[Three.$l,$b.two.$l],[Two.$l,$b.one.$o],[One.$o,"but none of the$l"],["Mother duck herself","and all of the$l"]])[$i=strpos(vuroet,($v=$argv[1])[2])],$a[++$i%6],$v);

Try it online!
I have stored different words of each verse in an array. I find which verse the input is using third character of the input as it is unique (vuroet). Then I simply replace different words of that verse with different words of the next verse.

Python 2, 1034 bytes
This is my code! It employs a simple dictionary. After running this code, you can enter any verse and it will output the next verse.
PS: I am new to this channel and this is my first post. I really liked this challenge so decided to give it a try. Please feel free to correct me.
import sys
i=sys.stdin.readlines()
s={"Mother":"""Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.""",
"Five":"""Four little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only three little ducks came back.""",
"Four":"""Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.""",
"Three":"""Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.""",
"Two":"""One little duck went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but none of the little ducks came back.""",
"One":"""Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back."""}
print s[i[0].split(" ")[0]]

Welcome to the site!  Usually we would count the dictionary as part of the source.  Part of the challenge would be to try and make this as small as possible.  There are also a few ways you could shorten this.  1) Since you don't get any points for being readable you can use single character variable names (e.g. x or a) 2)  Python is pretty permissive with whitespace so I would try removing some of your whitespace also.  For example you don't need spaces around =. Lastly We have a page for golfing in python you can visit to up your game.

wow @SriotchilismO'Zaic! that's helpful..thank you! :)

You can easily golf this by removing unnecessary whitespace and variables, avoiding importing sys by using e.g. raw_input(), shortening the key of the dictionary, etc. You should most definitely take out the repeated sections of the song and add them seperately

@JoKing as I mentioned this is my very first post and I didn't put much thought into this. Just wanted to give it a try, but I now get the idea. My next post is going to be much much better and shorter than this--all thanks to you guys..helping me out! :)

Clean, 352 bytes
import StdEnv,Text
$n={#"Five"+e+"four"+d,"Four"+e+"three"+d,"Three"+e+"two"+d,"Two"+e+"one"+a,"One"+a+b+"but none"+f,"Mother duck herself"+b+"and all"+f}.[indexOf{n.[2]}"tvuroe"]+" came back."
a=" little duck"
b=" went out one day,\nover the hills and up away.\nMother Duck said, \"Quack Quack Quack Quack\",\n"
d=a+"s"
e=d+b+"but only "
f=" of the"+d

Try it online!

C# (Visual C# Interactive Compiler), 262 bytes
x=>$@"{l[g=x[2]*37%724%7]}{g-5:; little} duck{g-4: herself;s;\} went out one day,
{(x=x.Split('\n'))[1]}
{x[2]}
{g-5:and;but} {g-4:all;only;none} {(g>3?"of the":l[g+1].ToLower())} little duc{g%3:ks;;k} came back.";var l=" Four Three Two One Mother".Split();int g

Try it online!

PowerShell, 356 343 340 336 bytes
param($p)$l,$M=' little duck','Mother duck herself'
("ive!our;four!three;hree!wo;Four!Three;two!one;s c! c;Two!One;s w! w;only one!none of the;k c!ks c;One$l!$M;but none!and all;$M!Five$l`s;and all of the!but only four"-split';')[$(switch -r($p){^Fi{0,1}^Fo{2,3}^Th{2,4,5}^Tw{6..9}^O{10,11}^M{12,13}})]|%{$p=$p-creplace($_-split'!')}
$p

Try it online.
More readable version:
param($p)
$l, $M = ' little duck', 'Mother duck herself'
$replacements = @"
ive!our
four!three
hree!wo
Four!Three
two!one
s c! c
Two!One
s w! w
only one!none of the
k c!ks c
One$l!$M
but none!and all
$M!Five$l`s
and all of the!but only four
"@ -split '\n'
$i = switch -regex ($p) { ^Fi { 0, 1 }
                          ^Fo { 2, 3 }
                          ^Th { 2, 4, 5 }
                          ^Tw { 6..9 }
                          ^O  { 10, 11 }
                          ^M  { 12, 13 } }
$replacements[$i] | % { $p = $p -creplace ( $_ -split '!' ) }
$p

PowerShell, 265 263 255 251 246 bytes
$d='Five1four2s,Four1three2s,Three1two2s,Two1one2,One23but none52s,Mother duck herself3and all52s'-split','
'2s34',' little duck',-join($args-split'(\s)')[5..39],'but only ',' of the'|%{$d=$d-replace++$i,$_}
$d[+"$args"[2]*37%724%7]+' came back.'

Try it online!
I used the brute force to find the expression +"$args"[2]*37%724%7.
 verse | 3rd char. | ASCII code | *37%724%7
-------+-----------+------------+-----------
   0   |    'v'    |     118    |   1
   1   |    'u'    |     117    |   2
   2   |    'r'    |     114    |   3
   3   |    'o'    |     111    |   4
   4   |    'e'    |     101    |   5
   5   |    't'    |     116    |   0

Thanks @Arnauld for the 3rd char.

05AB1E, 134 bytes
“€µ‚•„í†ìˆÈ“#’ „ê Ðœs’δJć¨…î¥Ðœº¶s‚ìðδJD…€³€É δì¨¦“€ƒ€Ÿ€‚€€““€³Šª€‚€€“‚’ „ê Ðœs ’δJì…‹é‚ƒ.δJU.•4Ôāl•|н2èk©è.ª?I„
ý#3.$17£ðý„
¶:,X®è?

Try it online!
Since i'm relatively new to 05AB1E, this can maybe be golfed a lot
                ### Preparation of the output strings ###
“€µ‚•„í†ìˆÈ“        push "one two three four five"
#                   split that by spaces
’ „ê Ðœs’           push " little ducks"
δJ                  join each number with " little ducks"
ć¨                  separate "one little ducks" and drop the "s"
…î¥Ðœº¶             push "mother duck herself"
s                   swap it with "one little duck"
‚ì                  prepend both strings to the list ["mother duck herself", "one little duck", "two little ducks" ... ]
ðδJ                 append a space to each list entry
D                   duplicate it
…€³€É               push "but only "
δì                  prepend "but only " to each list entry
¨¦                  drop the first and last list entry
“€ƒ€Ÿ€‚€€“          push "and all of the"
“€³Šª€‚€€“          push "but none of the"
‚                   push the two strings into a list
’ „ê Ðœs ’δJ        append " little ducks " to each
ì                   prepend it to the sentence list ["and all of the little ducks ", "but none of the little ducks ", "but only one little duck " ...]
…‹é‚ƒ.              push "came back."
δJ                  append that to each list entry
U                   save that list in X for later use

                ### Determine which verse has to be answered ###
.•4Ôāl•             push "eoruvt"
|н2è                get the third letter of the input
k                   get the index of that letter in "eoruvt". Now we know which verse we must return
©                   save that index in ® for later use

                ### Print the answer strings ###
è.ª?                print that index of the first sentence list (first three words of answer)
I„                  join the four input strings by <space><newline>
ý
#                   split that by spaces
3.$                 cut off the first three words
17£                 keep only the next 17 words
ðý                  join remaining words by spaces
„
¶:                  replace <space><newline> by only <newline>
,                   print that ("went out ... Quack\",")
X®è?                print the last line of answer

Japt v2.0a0, 143 bytes
Tried encoding a single verse with replacements but, in the end, adapting Arnauld's solution ended up being shorter. Have another idea that might, hopefully, work out shorter again but don't know when I'll get to try it.
tBn)i`Fr4È(e3
Two4e0
MÇ@r Ýõ Êelf1d a¥23
O01¿t Í
23
TËG4two3
Five4fr3`·g`v`b¢Î)r\dÈ°g[V=` Ò¤ Ýõ`W=Uf/ w.*\n/s `  e`V±'sV+W+`¿t § `]

Try it - includes all verses

Charcoal, 156 bytes
≔⌕tvuroe§θ²δ§⪪”↶0∨↘»≔xj➙⌈´βＸPＮLA‽⟦O⧴＆▷V'¦³≧ψZρ⊞t”¶δＦ‹δ⁵”↶↧V4ⅉＨ‴G%”Ｆ‹δ⁴s⮌…⮌θ¹⁸⸿η⸿ζ⸿§⪪”}∧h⁴ＮＱ≕Q^⪫ΦＧ✂q'ⅉＭG./_⸿s⁵6P⁴″⊟±ＮNpOfBz↷Ｆι‖ＴM→⁻γ？k⁴ς!d⁵º'E,θ}x§-υ”¶δ✂ε±¹¹

Try it online! Link is to verbose version of code. Explanation:
≔⌕tvuroe§θ²δ

Look at the third character of the first line to work out which verse we want.
§⪪”↶0∨↘»≔xj➙⌈´βＸPＮLA‽⟦O⧴＆▷V'¦³≧ψZρ⊞t”¶δＦ‹δ⁵”↶↧V4ⅉＨ‴G%”Ｆ‹δ⁴s⮌…⮌θ¹⁸

Output the first part of the first line by indexing into the list of strings Five, Four, Three, Two, One, Mother duck herself. Then print little duck and s as appropriate, followed by the last 18 characters of the input line (which are always the same on each verse).
⸿η⸿ζ⸿

The middle two lines are always the same on each verse.
§⪪”}∧h⁴ＮＱ≕Q^⪫ΦＧ✂q'ⅉＭG./_⸿s⁵6P⁴″⊟±ＮNpOfBz↷Ｆι‖ＴM→⁻γ？k⁴ς!d⁵º'E,θ}x§-υ”¶δ✂ε±¹¹

For the last line it turns out to be golfier to include little ducks in the list of alternatives for some reason, but the last 11 characters are still copied from the input.

Bash, 373 355 bytes
Nothing too crazy here. An easy few byte reduction would be to replace the two-character variables (a1,a2,a3,e1..e6) with single character ones.
read a{1..3} b
read c
read d
read e{1..6}
W="$e1 $e2"
X="${e3^} $a2 $a3"
Y="$e5 $e6"
Z="$e4 $Y"
p=$X
case $a1 in M*)p="Five ${Y::12}";s="but only four $Y";;O*)p="${d::11} herself";s="and all of $Z";;Tw*)p=${X/s};s="$e1 none of the $a2 ducks $e6";;Th*)s="$W one $e4 duck $e6";;Fo*)s="$W two $Z";;Fi*)s="$W three $Z";;esac
echo $p $b;echo $c;echo $d;echo $s

Try it online!
Try it online!

Perl 6, 247 bytes
{S:i/ne\sl.*?<(s//}o{m/..(.)(\S*)**3%\s(.**92).*(.**11)/;[(my$l=" little ducks")~$3 XR~"Mother duck herself$2and all of the","One{$l~=$2}but none of the","Five{$l~="but only "}four","Four{$l}three","Three{$l}two","Two{$l}one"]["eotvur".index($0)]}

Try it online!
Definitely golfable, especially the last 5 elements in the list in the form "num $l num-1", or the starting regex that matches the right parts of the old input.

ink, 353 bytes
=d(v)
~temp n=(v?"Fi")+(v?"F")*4+(v?"Th")+(v?"T")*2+(v?"O")
{n-1:{n:{n-5:{n-4:{n-3:One|Two}|Three}|Four}|Five} little duck{n-2:s}|Mother duck herself} went out one day,
over the hills and up away,
Mother Duck said "Quack Quack Quack Quack",
{n-1:but {n-2:only {n:{n-5:{n-4:one|two}|three}|four}|none of the}|and all of the} little duck{n-3:s} came back.

Try it online!
First, uses substring checks to figure out what verse we're in - that's easy enough thanks to the capitalisation of the numbers at the start - F, T and O don't occur in any other places, and you can distinguish the second and fourth verse from the first and third by also checking for Fi and Th respectively.
Then we just do what ink does best and print plain text specked with conditionals. I tried using switch statements at first, but while that looked nicer, it actually ended up longer.
You'd think the Quacks would be a good place to use variables, what with a string being repeated a bunch, but variables come with enough overhead that every way I tried to do that made the code longer. Maybe that's a sign I'm not supposed to golf in ink.

Zsh, 270 bytes
read {a..d}
read e
read f
set `cat`
case $a in
M*)a=Five
b=$5
c=$6
set but only four ${@:5};;O*)a=Mother
b=$c
c=herself
1=and
2=all;;*o)a=One
c=duck
set but none of the ${@:4}
6+=s;;T*)a=Two
3=one
5=duck;;*r)a=Three
3=two;;*)a=Four
3=three;;esac
<<Q
$a $b $c $d
$e
$f
$@

Try it online!
Explanation:
# {a..d} expands to a b c d
# so, read four words and assign them to a, b, c, and d
# (d also gets all the extra words beyond the 4th)
read {a..d}

# read two lines and store them in e and f
read e
read f

# assign the words in the remainder of the input
# to the numbered variables 1...
set `cat`

# if the first word...
case $a in
    # starts with M (i.e. Mother)
    M*)
        a=Five
        b=$5  # "little"
        c=$6  # "ducks"
        # set the numbered variables
        # ${@:5} is the existing numbered vars from 5 onwards
        set but only four ${@:5}
    ;;
    # One
    O*)
        a=Mother
        b=$c       # "duck"
        c=herself
        1=and
        2=all
    ;;
    # ends with o (Two)
    *o)
        a=One
        c=duck
        set but none of the ${@:4}
        # "duck" -> "ducks"
        6+=s
    ;;
    # Three
    T*)
        a=Two
        3=one
        5=duck
    ;;
    # Four
    *r)
        a=Three
        3=two
    ;;
    # anything else (Five)
    *)
        a=Four
        3=three
    ;;
esac

# now print:
<<Q
$a $b $c $d
$e
$f
$@
```

source: Stack Exchange

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

sort: votes


text:
Duct Tape a Regex Decider
Your task is to create a program that determines whether a given string is a valid regular expression or not using code snippets sourced from sites on the StackExchange network.
For the purposes of this challenge, the regular expression dialect will be a stripped down and mostly minimal set of meta-characters: ()*?|\. As such, you will not be able to use built-in regex parsers.

\ is used to escape meta-characters. It must be followed by a meta-character.
Unescaped parentheses must be balanced
* and ? must be preceded by either a non-meta-character, a parenthesized group, or an escaped meta-character.
All other printable ASCII characters plus newline, tab, and space must be supported as non-meta characters. What happens with a string containing other characters is undefined.
The actual meaning of the regex is not important for this challenge.

Examples
Truthy:
  abc
  a?
  (a|)*
  ()
  a|b*
  \*
  \\
  \\*
  a*b?(cd|e)
  +
  [
  }
  (123\))*
  \|
  (a(b(c|d)*e)*f)*
  (|\)*)
  (abc)+*
  (abc)+
  +abc

^ last test case is an actual newline

Falsy:
  ?abc
  *
  **
  \
  (
  a*?
  a?*
  ?
  a)
  (\)
  (|\)*
  \()
  |*
  (?:abc)
  \\**
  \n

Scoring
Your overall score is the number of snippets taken from questions and answers around StackExchange.

Repeated snippets count for as many times as they are used.
Whitespace can be added and removed freely (because of Python, Haskell, and other whitespace-sensitive languages) and does not count toward your snippet count.

The exception would be if your code is actually written in Whitespace.

Snippets are allowed from any StackExchange site as long as they come from questions, answers, and comments that are older (Including by edit time - use older revisions if necessary) than this challenge. (Sep 24, 2019 @ 3:30 PM UTC)
Snippets can come from anywhere in a question, answer, or comment body, whether it's in a preformatted code block or not.
Splicing a snippet into the middle of another causes the outer snippet to count as two snippets

Lowest score wins!

@RobinRyder yes, changed

Can the post be older than or equal to this challenge, i.e. can we use snippets from the body of this challenge?

"As such, you will not be able to use built-in regex parsers" Is that to say that its designed to thwart using that for a simple ya/nay, or that we are forbidden from using regex at all in our answers?

@guifa it's designed so that you can't just take your language's regex engine and see if it compiles the given regex. Every language I know of supports a larger set of meta-characters and specialized capture groups, so they wouldn't match this set of characters correctly in all cases.

@JoKing, I'm going to say no on that.

Does it have to be more than one snippet? Is the program allowed to have output?

What if we cut out a part from the middle?

@JL2210 That would make it two snippets: one for the beginning and one for the end. You can use a single snippet as long as it passes all the test cases and  comes from an answer/question/post that's older than this challenge

Unused, empty input?

Must the snippet be in the same language as the submission?

@boboquack very yes. It doesn't even need to be a programming language.

There should probably also be an exception for Unispace (https://esolangs.org/wiki/Unispace) (although there's no interpreter for it that I know of it)

Perl 6, 20 snippets
{$_ eq m/[[<-[()*?|\\]>|\\<[()*?|\\]>|'(' <~~>* ')']<[*?]>?|\|]+/}

Try it online!
The snippets are taken from:
{$_ eq, m/[, <-[, ()*?, |\\, ]>, |\\, <[, ()*?, |\\, ]>, |, '(' <~~>* ')', <[, *?, ]>, ?|, \|, ]+/, }.
This is mostly the greedy approach (made obvious by all the one or two character snippets). I used SymbolHound to search for the individual characters, and the only real optimisation was the '(' <~~>* ')' snippet, which is taken from my own answer on recursive Perl 6 regexes.
Explanation:
This basically checks if the input is equal to a greedy match of a valid regex. The reason we can't just use the regex itself and add ^$ to mark the ends is because we are using a recursive regex, which wouldn't work if there were ^$ markers. The regex itself is:
m/[                             ]+/   # Match one or more times
   [              ]  # Any of
    <-[()*?|\\]> |     # Not a metacharacter
    \\<[()*?|\\]>      # A metacharacter preceded by a \
    '(' <~~>* ')'      # Brackets surrounding a valid regex
                   <[*?]>?  # Optionally followed by a ? or *
                           | \|    # Or just the | metacharacter

@guifa Yes, I learnt that through the P6 specification, which has a lot of things that haven't been properly documented yet. I suspect ~~ doesn't appear because it is not yet fully implemented (for example <~~0>), though there are other hidden gems in there.

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


text:
Approximate the perfect fifth
Starting at 1-TET, give equal temperaments that have better and better approximation of the perfect fifth(just ratio 3/2). (OEIS sequence A060528)
The formal description of the sequence, copied from the OEIS:

A list of equal temperaments (equal divisions of the octave) whose nearest scale steps are closer and closer approximations to the ratios of two tones of musical harmony: the perfect 4th, 4/3 and its complement the perfect 5th, 3/2.

Note that by symmetry, the perfect fourth doesn't matter.
Let's say we know that 3 is in the sequence. The frequencies in 3-TET are:
2^0, 2^⅓, 2^⅔

Where 2^⅔ is the closest logarithmic approximation of 3/2.
Is 4 in the sequence? The frequencies in 4-TET are:
2^0, 2^¼, 2^½, 2^¾

Where 2^½ is the closest approximation of 3/2. This is not better than 2^⅔, so 4 is not in the sequence.
By similar method, we confirm that 5 is in the sequence, and so on.
When given an integer n as input, the output must be the first N numbers of the sequence in order. For example, when n = 7, the output should be:
1 2 3 5 7 12 29

Sequence description by xnor
The irrational constant \$ \log_2(3) \approx 1.5849625007211563\dots\$ can be approximated by a sequence of rational fractions
$$ \frac{2}{1}, \frac{3}{2}, \frac{5}{3}, \frac{8}{5}, \frac{11}{7}, \frac{19}{12}, \frac{46}{29}, \dots$$
A fraction is included in the sequence if it's the new closest one by absolute distance \$ \left| \frac{p}{q} - \log_2(3)\ \right|\$, that is, closer than any  other fraction with a smaller or equal denominator.
Your goal is to output the first \$n\$ denominators in order. These are sequence A060528 (table). The numerators (not required) are given by A254351 (table)
Rules:

Do not import the sequence A060528 directly.
The format doesn't matter as long as the numbers are distinguishable. In the example above, the output can also be:
[1,2,3,5,7,12,29]
As this is a code-golf, the shortest code in bytes wins.

Hi and welcome to Code Golf SE! We require that all challenges be self-contained, so a description here of the sequence would be a great help.

I'm confused by the description from OEIS. It mentions perfect 4th as well (ratio 4/3), but the challenge is about perfect 5ths (ratio 3/2). I think it also needs explanation that the sequence values are the denominators of the rational approximations.

I improved the question. Now vote for reopen, please?

I like the challenge, but I find the stuff added to the description still confusing, not knowing much about music. For instance, I don't know what 1-TET or  4-TET are, and nothing seems to show up on Google. I'll try writing an explanation of how I'd describe this sequence.

@xnor For example, 12-TET means 12-tone equal temperament.

As a small technical point, I'd suggest setting some upper bound on what input n can be given. Due to float precision issues, coded solutions might eventually become inaccurate for large n, making it hard to judge which answers are valid. I think something like n=40, the max of the OEIS table, would be reasonable.

@DannyuNDos Ah yes, the 12-tone equal temperament. That's my favourite instrument

Temparement is a way to define the notes that an instrument can produce; it's not an instrument

@DannyuNDos Thanks. So the comparison is between 1/2 and log2(1.5), not between 2^(1/2) and 1.5. That should be made clearer in the text

05AB1E, 19 18 bytes
µ¯ßNLN/3.²<αßDˆ›D–

Try it online!
µ                      # repeat until counter == input
 ¯                     #  push the global array
  ß                    #  get the minimum (let's call it M)
   N                   #  1-based iteration count
    L                  #  range 1..N
     N/                #  divide each by N
       3.²             #  log2(3)
          <            #  -1
           α           #  absolute difference with each element of the range
            ß          #  get the minimum
             Dˆ        #  add a copy to the global array
               ›       #  is M strictly greater than this new minimum?
                D–     #  if true, print N
                       #  implicit: if true, add 1 to the counter

Nice answer, but all I'm wondering right now is why the while-loop has 1-based indices.. :S

Wolfram Language (Mathematica), 62 60 bytes
Denominator@NestList[Rationalize[r=Log2@3,Abs[#-r]]&,2,#-1]&

Try it online!

How many precision?

@DannyuNDos This function uses exact values, so computations can be done to arbitrary precision.

You win the challenge.

@DannyuNDos why accept an answer this quickly? It's also arguably better not to accept an answer at all..

Regarding the floating-point errors other languages are suffering, I'd like to present an alternative method of alloting score. So hold on.

JavaScript (V8), 81 80 78 bytes
-2 bytes thanks Arnauld!
n=>{for(d=g=1;w=Math.log2(3),w+=~(w*g-.5)/g,n--;g++)w*w<d?d=print(g)||w*w:n++}

Try it online!

Python 2, 92 bytes
E=k=input()
n=0
while k:
 n+=1;e=abs((3.169925001442312*n-1)%2-1)/n
 if e<E:print n;E=e;k-=1

Try it online!
Uses the constant 3.169925001442312 for \$2 \log_2(3)\$. I wasn't sure how many digits of accuracy are required, since the inaccuracy will break the sequence eventually, so I used the full float precision of 2 * numpy.log2(3).

This gives two extra terms after 665: ..., 665, (1995), (4655), 8286, ... Try it online!

@Οurous Yeah, that's pretty much inevitable sooner or later for any language without infinite precision, though I'm surprised it popped up so early with 32-bit floats as Python uses. I'll wait for the challenge writer to clarify on how far answers need to work.

wouldn't it be fewer characters to use 2 * numpy.log2(3) rather than the fully spelled out number? (Or even better, numpy.log2(9))

@JDL that would require this code: from numpy import* and log2(9).

ah, that is what I get for assuming python works like R and you can write package::function without loading package first!

Clean, 128 111 108 bytes
import StdEnv
c=ln 3.0/ln 2.0
?d=abs(toReal(toInt(c*d))/d-c)
$i=take i(iterate(\d=until((>)(?d)o?)inc d)1.0)

Try it online!
Should work up to the limits of Real's 64-bit double precision type.

Perl 5 (-MPOSIX=log2 -M5.01 -n), 73, 78, 71 bytes
Fixed following comment, may be improved...
-7 bytes thanks to Grimy

$o=abs$d-(0|.5+($d=log2 3)*++$;)/$;;$@=$o,$_-=say$;if!$@|$o<$@;$_&&redo

Try it online!

here's 71

MATL, 27 25 bytes
1`@:@/Q3Zl-|X<hY<tdzG-}df

Try it online!
Explanation
1       % Push 1. This initiallizes the vector of distances
  `     % Do...while
  @:    %   Range [1, 2, ..., k], where k is the iteration index, staring at 1
  @/    %   Divide by k, element-wise. Gives [1/k, 2/k, ..., 1]
  Q     %   Add 1, element-wise. Gives [(k+1/k, (k+2)/k, ..., 2]
  3Zl   %   Push log2(3)
  -|    %   Absolute difference, element-wise
  X<    %   Minimum
  h     %   Concatenate with vector of previous distances
  Y<    %   Cumulative minimum
  t     %   Duplicate
  dz    %   Consecutive differences, number of nonzeros. This tells how many
        %   times the cumulative minimum has decreased
  G-    %   Subtract input n. This is the loop condition. 0 means we are done
}       % Finally (execute on loop exit)
  d     %   Consecutive differences (of the vector of cumulative differences)
  f     %   Indices of nonzeros. This is the final result
        % End. A new iteration is executed if the top of the stack is nonzero
        % Implicit display


text:
Is this a valid Tichu play?
Tichu is a card game in which players take turn playing sets of cards from a deck consisting of a standard 52-card deck, plus 4 additional cards:

the dragon, which has a greater value than any other card
the phoenix, which can act as a wildcard
the dog, which passes the turn to your partner
the Mah Jong, which has value 1 (and the person holding it plays first)

The first player (who is said to have "lead") can choose to play one of the following types of card combinations:

a single (e.g. 6)
a pair (JJ)
a triple (555)
a full house (QQQ33) - a triple and a pair
a straight (56789) - 5 or more consecutive cards
a tractor (223344) - any consecutive sequence of pairs

Subsequent players are then only allowed to play a set of cards of the same type, but strictly higher. For example, QQ can be played on top of JJ, but QQKK cannot (it is a tractor, not a pair). Full houses are ordered by the triple (e.g. 77722 > 44499), and straights and tractors must be the same length (456789 cannot be played on top of 23456). Aces are high.
There is one exception: any 4 of the same card is a bomb, and can be played on top of anything except a higher bomb.1
The dragon can be played by itself on top of any single or with lead (but nowhere else). The phoenix, aside from being a wildcard, can also be played on top of any single except the dragon.2 The dog can only be played by itself with lead and immediately ends the turn.3

Your challenge is to determine whether a given Tichu play is valid, given the previous play.
You may accept both plays in any order as either lists of integers or strings -- in either case, you may choose any mapping of cards to integers/characters.
If there was a previous play, it will always be valid, and if not (i.e. the player has lead), the first input will be the empty array/string (matching the type of the other input). The cards are not guaranteed to be given in any particular order.
Your output must be selected from a set of exactly two distinct values, one of which indicates the play is legal and one that indicates it is not.
There is no need to test for whether the set of cards actually exists in the deck (e.g. 77766 followed by 88877 is impossible because there are only four 7's) -- such cases will never be given.
In the following test cases, 234567890JQKA represent 2 through ace, and RPD1 represent the dragon, phoenix, dog, and Mah Jong respectively. The empty string is shown here as -. These plays are legal:
6 J
JJ QQ
555 KKK
44499 77722
23456 56789
223344 QQKKAA
49494 72727
A R
A P
P R
66 7P
P6 77
58304967 6P0594J7
5P304967 680594J7
57446765 788657P5
- D
- 1
- 12345
3344556677889900 JJJJ
5555 7777

And these are not:
9 3
66 55
888 444
44 888
77722 44499
44499 777
44499 777JJJ
45678 34567
34567 456789
556677 334455
5566 778899
72727 49494
A A
R A
R P
77 RP
77 6P
P7 66
680594J7 5P304967
6P0594J7 58304967
57446765 3645P536
1 D
2 D
2 1
- 1234
7777 5555
- 223355

1: actually, a straight flush is also a bomb, but since this is the only place in the game that the suit of the cards matter, I have chosen to leave it out for simplicity's sake
2: the value of the phoenix played on top of a card with value n is actually n+0.5 (a phoenix on a 9 is a 9 and a half); since this requires knowledge of additional history to adjudicate, no test cases involve a single played on top of a single phoenix
3: so the first input will never be dog

@Arnauld Not all are valid combinations (e.g. 777JJJ, 1234, 223355). However, RP is not valid: "The dragon can be played by itself on top of any single or with lead (but nowhere else)."

Indeed, I was just about to edit my comment to say that all first hands seem to be always valid.

@Arnauld Ah - yes, you may assume all first hands are valid.

It may be worth mentioning that a Phenix may not be used as a wildcard in a bomb. 5555 777P should be an invalid play, but both current answers mark it as valid.

JavaScript (ES6),  274  273 bytes
Takes input as (a)(b), where \$a\$ and \$b\$ are arrays of integers with:

\$1\$ = dog
\$3\$ = Mah Jong
\$4..16\$ = 2 ... Ace
\$18\$ = dragon
\$19\$ = phoenix

Returns false for valid or true for invalid.
a=>b=>!(L='length',[A,B]=(g=a=>(h=n=>--n?[i=1,2,3,'(20*)3|30*2','1{5,}','22+',4].some(p=>m=o.join``.match(`9(0*)(${p})0*$`,i++),a.map(x=>o[x-19?x:x=n]=-~o[x],o=[...9e16+'']))?[i,m[1][L]+(m[3]||[])[L]]:h(n):[])(18))(a),[C,D]=g(b),a+a?A-C?C>7|+b>a:a[L]==b[L]&D>B|A<3&b==18:C)

Try it online!
How?
To evaluate a hand, we build an array o[] made of a leading \$9\$, initially followed by 16 zeros:
//       D  -  1  2  3  4  5  6  7  8  9  T  J  Q  K  A
o = [ 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];

For each card rank in the hand, the corresponding slot in o[] is incremented. Once joined back to a string, we can apply the following regular expressions to detect each type of hand:
 hand        | pattern     | full regex              | example
-------------+-------------+-------------------------+-------------------
 single      | 1           | /9(0*)(1)0*$/           | 90000100000000000
 pair        | 2           | /9(0*)(2)0*$/           | 90000002000000000
 3-of-a-kind | 3           | /9(0*)(3)0*$/           | 90003000000000000
 full house  | (20*)3|30*2 | /9(0*)((20*)3|30*2)0*$/ | 90020000030000000
 straight 5+ | 1{5,}       | /9(0*)(1{5,})0*$/       | 90000111110000000
 tractor     | 22+         | /9(0*)(22+)0*$/         | 90000000000022200
 bomb        | 4           | /9(0*)(4)0*$/           | 90000000000000004

If the hand does not trigger any of these regular expressions, it's invalid.
The value of the hand is given by the number of zeros just after the leading \$9\$ (the higher, the better). A special case is a full house where the rank of the triple is higher than that of the pair, in which case we need to add the length of the (20*) pattern.
The phoenix (i.e. the wildcard) is simply replaced with each possible card rank, starting with the highest one, until a match is detected.

Python 3, 466 455 403 401 399 bytes
R=lambda H,n=3:n==len(H)*(len({*H})<2)and[15]!=H[1:]
s=lambda H:[H[2:],H[:1]][R(H[:3])]
def n(J,K):j,k=[[16in H,R(H,4),len(H)>4and all(15!=t>T-2for t,T in zip(H,H[1:])),[R(H[2:])*R(H[:2],2),R(H[3:],2)][R(H[:3])],R(H),R(H,2),R(H,1),1].index(1)for H in[J,K]];return k!=7and[17]==J or[j==k*[J<K,s(J)<s(K)][2<j<5],J<K][k==1]
f=lambda P:any(n(*[sorted([L,i][i>0]for i in H)for H in P])for L in range(16))

Try it online!
Input is list of hands where hand is list of integers1 with the following value mapping:

0: Phoenix
1: Mah Jong
2-13: 2 to Ace
14: Dragon
15: Dog
16: Empty string

1: Although in the linked TIO tests are expressed with list of strings due to convenience which are translated according to value mapping before calling f


text:
What is the score of my Scopa hand?
I like card game challenges so I made this one for the Italian card game Scopa. My family has been playing this game since time immemorial. It has a very interesting scoring system that should be fun to golf. I will post an answer in R to get the fun started, that I am sure people will improve upon.
The challenge: figure out the number of points scored in a round of Scopa, given the cards the player captured during the round as input.
There are 40 cards in a Scopa deck. If you are using an international deck you remove the 8s, 9s, and 10s, leaving A,2,3,4,5,6,7,Q,J,K in each suit.1 There are two players or partnerships, and after every round, all cards end up captured by one or the other of the two players. The score is counted as follows (more information here):

The player with the most cards scores 1 point.
The player with the most diamonds (or coins if using the Italian deck) scores 1 point.
The player with the 7 of diamonds (or coins), known as the sette bello or beautiful seven, scores 1 point.
The player with the highest primiera scores 1 point. A player's primiera score is the sum of the scores of the highest-value card that the player captured in each suit (see table below). If you do not have at least one card in every suit, you lose by default even if your score would exceed your opponent's score. In the exceedingly rare case that neither player has at least one card in every suit, the player with the higher primiera total scores the point.2

Table of primiera scores
| Rank  | Value |
| ----- | ----- |
| 7     | 21    |
| 6     | 18    |
| A     | 16    |
| 5     | 15    |
| 4     | 14    |
| 3     | 13    |
| 2     | 12    |
| Q,J,K | 10    |

So a player can score at most 4 points in a round.3 If there is a tie, which is possible for cards, diamonds, or primiera, no one scores the point.
It's important to realize that since each card must be captured by one of the two players, you can infer what cards the other player must have taken even if you only know what cards one player took. You will need to do this to correctly score primiera.
Challenge rules
Input
Your code should take as input the cards captured by a single player during a round of Scopa.
Input must be in string format, in which one character represents the rank of each card and one character its suit. This removes the potential loophole of passing the primiera scores in directly as input. Conversion of card ranks to primiera scores must be done in the program. However you may choose to use a single string separated by spaces or commas, an array of strings, or any other format. For example if you choose to encode ranks as 76A5432QJK and suits as DCHS you could use inputs such as ['7D', '6H', 'QD', 'JS'] or '7D,6H,QD,JS'.
Output
An integer from 0 to 4 representing the player's score.
Winning
Shortest answer in bytes wins!
Test cases
["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "7C", "6C", "4C", "3C", "2C", "7H", "4H", "2H", "5S", "3S", "QS", "JS", "KS"]
Scores 4: 1 point for >20 cards, 1 point for >5 diamonds, 1 point for the 7 of diamonds, and 1 point for scoring 78 in primiera (7,7,7,5 where opponent has 7,6,5,K for 64)
["3D", "7C", "6C", "AC", "5C", "4C", "3C", "2C", "QC", "4H", "7S"]
Scores 0: <=20 cards, <=5 diamonds, no 7 of diamonds, and only scores 69 in primiera (7,7,4,3 where opponent has 7,7,6,K for 70)
[7D", "6D", "AD", "5D", "4D", "3D", "2D", "7C", "6C", "AC", "5C", "4C", "3C", "2C", "7H", "6H", "AH", "5H", "4H", "3H", "2H"]
Scores 3: 1 point for >20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. The primiera would be 63 (7,7,7) and the opponent can only score 51 (7,Q,Q,Q) but since this hand has no spades it loses the point by default.
["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "QC", "QH", "QS"]
Scores 3: <=20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. The primiera only scores 51 (7,Q,Q,Q) and the opponent can score 63 (7,7,7) but since the opponent's hand has no diamonds this hand wins the primiera point by default.
["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "7C", "7H"]
Scores 3: <=20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. Even though this hand has no spades, it still wins primiera by a score of 63 to 57 (7,7,7 versus 7,6,6) because the opponent's hand has no diamonds.
["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "QC", "QH"]
Scores 2: <=20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. This hand has no spades, and opponent's hand has no diamonds. Opponent wins primiera by a score of 63 to 41 (7,7,7 versus 7,Q,Q).
[] (empty array)
Scores 0

1: At least in our family, Jack outranks Queen in Scopa but this is irrelevant for scoring purposes.
2: I've been playing this game since childhood and have never seen that happen but your code had better be able to handle that case!
3: There are bonus points for "sweeps" scored during the round which I am ignoring for the purpose of this challenge.

Does each rank have to be represented by a distinct character?

@Doorknob No not necessarily, but at least in the solution I am working on I found it necessary to have a unique character for each rank to get all the test cases right.

@Grimy good catch. thanks

Ruby, 156 153 bytes
->a{b='';([a[40],a.scan(/.d/)[5],a=~/;d/,'dchs'.gsub(/./){l=a.scan /.(?=#$&)/;l.size<10&&b+=(';865432'.tr(l*'','')+?0)[0];l.max}.sum>b.sum||p]-[p]).size}

Try it online!
->a{
b='';                # stores primiera of other player
([                   # this array stores all checks
a[40],               # check if >20 cards (>40 characters)
a.scan(/.d/)[5],     # check if >5 diamonds
a=~/;d/,             # check if 7 of diamonds
'dchs'.gsub(/./){    # for each suit, build a string with...
l=a.scan /.(?=#$&)/; # find all cards with this suit
l.size<10&&          # if there are less than 10, the other person has some, so
b+=                  # append to their score string the following:
(';865432'           #   start with all the cards
.tr(l*'','')         #   remove the ones we have
+?0)                 #   add back the JQK at the end
[0];                 #   take the highest
l.max}               # return the highest card that we have
.sum                 # take the sum of the codepoints
>b.sum               # check if it's greater than the other player's sum
||p                  # if not, evaluate to nil
]-[p])               # remove all nils
.size}               # count how many are left

This uses ;865432000 to represent 76A5432QJK respectively, and suits are in lowercase. (The choice of characters is because subtracting 38 from each gives their primiera value, but we never actually do so because only the relative difference matters.)
We don't check whether either player is missing a suit because it is unnecessary -- since all cards are counted as 38 plus their actual value, if someone is missing a suit, the highest score they can get is (21+38)*3 = 177, which is less than (10+38)*3 + 21+38 = 203, the lowest score the other player can get. We cannot have the two players missing an unequal nonzero number of suits, because a player can only be missing 0, 1, or 2 suits, and if someone is missing 2 suits they have all the cards of the other 2 suits.

R, 320 298 265 238 229 224 211 209 179 bytes
This is a solution mostly due to @digEmAll, in the form of a function.
Try it online!
function(h,S=sum,A=apply,l=99+c(11,8,5:2,6,!1:3)%o%!!1:4)S(S(p<-outer(c(7:2,'A','K','J','Q'),c('D','C','H','S'),paste0)%in%h)>20,S(p[1:10])>5,p[1],S(A(l*p,2,max)-A(l*!p,2,max))>0)

Below is the best of my old mediocre attempts for 209 bytes.
edit: golfed down by aliasing some functions, then by taking Doorknob's idea of adding a constant to the score instead of checking the suits.
next edit: got rid of some redundancy and then incorporated some improvements from Giuseppe
next edit: -2 bytes thanks to digEmAll
I am terrible at this, so I'm sure someone can improve on this if they care to take the time. I feel like the sapply and function are super long and could get rid of them but I can't figure out how. Inputs are two-character strings in the standard notation.
function(h,s=sum,l=c(11,8,5:2,6,!1:3)+99)s(length(h)>20,s(grepl('D',h))>5,'7D'%in%h,s(sapply(c('D','C','H','S'),function(i,r=c(7:2,'A','K','J','Q')%in%substr(h[grep(i,h)],1,1))s(l[r][1],-l[!r][1],na.rm=T)))>0)

You may be able to get help in the R golf chatroom, digEmAll is even a fellow Italian!

Just some advice but if you can swap a semi-colon just a newline (which looks to be one byte in R), it's a free swap that makes your answer more readable. Also, check out Try It Online which is an online code runner if you haven't. Not required, but again, nice to use. It can even generate CGCC posts

253 bytes -- I'm not totally sure this will work, since I was mostly trying the usual set of golfs, but feel free to test and let me know.

@Giuseppe thanks! I golfed it further to 240 bytes by replacing the multiple calls of match with some greps, so then I added your golfs to get it to 238!

It's recommended to post a link to TIO if possible, so people can verify your code :) (if you click on the "chain" button you can then copy the "Code Golf submission (Stack Exchange)" entry which contains the pre-compiled markdown for a standard codegolf stackexchange answer :)

Moved your answer into a function (same byte count)

209

This should work as well for 181

@digEmAll bellissimo! :-D

@digEmAll shaved 2 bytes off by getting rid of a parentheses for 179

@qdread: great! now just post it ! ;)

05AB1E, 41 bytes
39ÝsK‚εg9y@Oy0å•Dδ¿m(/d•₆вy.γT÷}è€àO)}`›O

Try it online or check all test cases.
Suits DCHS are respectively represented by 0123. Ranks 7A65432KJQ are respectively represented by 0123456789. Those are taken as strings, not integers, as required by the challenge (but then 05AB1E converts them to integers when needed anyway).
As in other solutions, we add a large constant (14) to each primiera score in order to make the check for missing suits unnecessary.
39Ý                      # range 0..39 (the list of all cards in the game)
   sK                    # remove all elements that appear in the input
      ‚                  # pair with the input: [player's hand, opponent's hand]

ε                     }  # map each hand to a list of its 4 subscores:
 g                       #  first subscore: length (number of cards)
 9y@O                    #  second subscore: count elements <= 9 (diamonds)
 y0å                     #  third subscore: is 0 (representing 7D) in the list
            y.γT÷}       #  group the hand by suit
 •Dδ¿m(/d•₆в      è      #  map each rank to its primiera score
                   €à    #  maximum primiera score in each suit
                     O   #  fourth subscore: the sum of those

`›                       # for each subscore: is player's > opponent's?
  O                      # sum
```

JavaScript (ES6),  171  163 bytes
Takes input as a set of cards, using their standard representation.
c=>(c.size>20)+((g=o=>[..."CHSD"].map(s=>[..."JQK2345A67"].map((v,i)=>(S=o^c.has(v+s))?m="111345679"[++n,i]||12:0,n=m=0)|(n?0:T=1,t-=m),T=t=4)|t*T)(1)>g``)+S+(n>5)

Try it online!
Commented
c =>                                // c = set of cards
  (c.size > 20) + (                 // +1 point if we have more than 20 cards
    ( g = o =>                      // g is a function taking the flag o (for 'opponent')
      [..."CHSD"].map(s =>          // for each suit s, ending with diamonds:
        [..."JQK2345A67"]           //   for each rank v at position i, sorted from
        .map((v, i) =>              //   lowest to highest primiera score:
          (S = o ^ c.has(v + s)) ?  //     if the player owns this card, set S to 1 and:
            m = "111345679"[++n, i] //       increment n; update m to the score of this
                || 12               //       rank (we use the official score - 9)
          :                         //     else:
            0,                      //       do nothing
          n = m = 0                 //     start with n = m = 0
        ) |                         //   end of inner map()
        ( n ? 0 : T = 1,            //   if n = 0, set T to 1
          t -= m ),                 //   subtract m from t
        T = t = 4                   //   start with T = t = 4
      ) | t * T                     // end of outer map(); yield t * T
    )(1) > g``                      // +1 point if g(1) is greater than g(0)
  ) +                               // (we test this way because the scores are negative)
  S +                               // +1 point if we own the 7 of diamonds
  (n > 5)                           // +1 point if we own more than 5 diamonds

C# (Visual C# Interactive Compiler), 193 bytes
x=>x.Count/21+x.Count(g=>g>48)+x.Sum(g=>g/40)/6+("".Sum(m=>{var r=x.Where(g=>g/10==m);return(r.Any()?r.Max()%10+50:0)-(r.Count()<10?"	".Max(l=>x.Contains(m*10+l)?48:l+50):0);})>0?1:0)

Try it online!

MS SQL Server 2017, 525 bytes
CREATE FUNCTION f(@ NVARCHAR(MAX))RETURNS TABLE RETURN
SELECT q/21+IIF(d>6,2,IIF(d=6,1,0))+IIF(m=0,IIF(n=0 AND a>b,1,0),IIF(n=0 OR a>b,1,0))p
FROM(SELECT SUM(q)q,MAX(IIF(s='D',q,0))d,SUM(a)a,MIN(q)m,SUM(b)b,MIN(10-q)n
FROM(SELECT s,COUNT(k)q,MAX(IIF(r=k,v,0))a,MAX(IIF(r=k,0,v))b
FROM(SELECT LEFT(value,1)r,s,ASCII(RIGHT(value,1))-38 v
FROM STRING_SPLIT('7;,68,A6,5,4,3,2,Q0,J0,K0',','),(VALUES('D'),('C'),('H'),('S'))s(s))d
LEFT JOIN(SELECT LEFT(value,1)k,RIGHT(value,1)u FROM STRING_SPLIT(@,','))a
ON r+s=k+u GROUP BY s)t)t

Try it on db<>fiddle.

Retina 0.8.2, 334 bytes
$
 ¶234567JQKA
r`.\G
$&C $&D $&H $&S
+`((\w\w).*¶.*)\2
$1
T`67AJQK`8960
%O$`(\w)(\w)
$2$1
m`^(?=(...)*)(.C )*(.D )*(.H )*(.S )*
$3;$#1 $#2 $#3 $#4 $#5;${2}${3}${4}$5
m`^(?=(9D))?...;
$#1;
(;(?!.*10).* 0.*;).*
$1
\d[C-S]
1$&
19\w
21$*@
\d+(\w )?
$*@
(@)?;(@*) @* (@*).*;(@*)¶@?;((?!\2))?@* @* ((?!\3))?.*;((?!\4))?.*
$#1$#5$#6$#7
1

Try it online! Link includes test cases. Explanation:
$
 ¶234567JQKA
r`.\G
$&C $&D $&H $&S

Create a list of all 40 cards.
+`((\w\w).*¶.*)\2
$1

Remove the cards the player holds.
T`67AJQK`8960

Replace each rank by its sort order, which is 9 for 7 and 10 less than its value for other cards.
%O$`(\w)(\w)
$2$1

Sort the cards by suit and rank.
m`^(?=(...)*)(.C )*(.D )*(.H )*(.S )*
$3;$#1 $#2 $#3 $#4 $#5;${2}${3}${4}$5

Count the number of cards in each suit and also capture the highest ranked card in each suit, capturing the highest diamond twice.
m`^(?=(9D))?...;
$#1;

Check whether the highest diamond was the 7.
(;(?!.*10).* 0.*;).*
$1

Delete all of the highest cards if one of the suits has no cards.
\d[C-S]
1$&
19\w
21$*@
\d+(\w )?
$*@

Convert the highest cards to their unary score and sum them together. Also convert the total number of cards and suit lengths to unary.
(@)?;(@*) @* (@*).*;(@*)¶@?;((?!\2))?@* @* ((?!\3))?.*;((?!\4))?.*
$#1$#5$#6$#7

Score points if the total, diamonds, or primiera, is higher.
1

Total the score.

Python 3, 249 245 239 238 bytes
-4 bytes thanks to @ovs
-6 bytes thanks to @movatica
lambda C:sum([len(C)>20,'7D'in C,len([c for c in C if'E'>c[1]])>5,p(C)>p({n+s for n in'9876543210'for s in S}-C)])
p=lambda C:[not S.strip(''.join(C)),sum(max([(c[1]==s)*int('9gcdefil99'[int(c[0])],22)for c in C]+[0])for s in S)]
S='DcHS'

Try it online!

2 bytes less with int('0734569c00'[int(x[0])],13) and if x[1]<'E' can be written as if'E'>x[1]

all(s in''.join(C)for s in S) can be shortened to not S.strip(''.join(C)), saving 6 bytes

AWK, 235 bytes
{s[9]=35;s[8]=32;s[7]=30;s[6]=29;s[5]=28;s[4]=27;s[3]=26;s[2]=s[1]=s[0]=24;a[$1 $2]=s[$1]}END{while(i++<4){D=0;for(j=0;j<10;j++){if(a[j i]<1){B[i]=s[j];D++}if(A[i]<a[j i])A[i]=a[j i]}x+=A[i];y+=B[i]}print(20<NR)+(D<5)+(1<a[9 4])+(y<x)}

Try it online!
Suits map to 1234 (4 is diamonds), values map to 0123456789.  This program transforms the test cases into the accepted format:
BEGIN{RS=", ";FS="";t[7]=9;t[6]=8;t["A"]=7;t[5]=6;t[4]=5;t[3]=4;t[2]=3;t["Q"]=2;t["J"]=1;t["K"]=0;u["D"]=4;u["C"]=1;u["H"]=2;u["S"]=3}{gsub("[\\[\"\\]]","",$0);print t[$1],u[$2]}

My goal was just to beat the leading Python implementation :D

232 bytes


text:
Write a piece of code that prints out itself
I'm new to this site, so I don't know whether this challenge already appeared:
Write a piece of source code, so that after running the code, it prints out exactly (i.e. not longer, not shorter) the source code itself.
The code can be in any programming language, but preferably in commonly used ones, such as the C family, Java, Python, Haskell, Ruby...

Duplicate

Ah, thanks for the link!


text:
Find the percentage
We haven't had any nice, easy challenges in a while, so here we go.
Given a list of integers each greater than \$0\$ and an index as input, output the percentage of the item at the given index of the total sum of the list.
Output should be whatever the natural representation for floats/integers is in your language (unary, decimal, Church numerals etc.). If you choose to round the output in any way, it must have at minimum 2 decimal places (when reasonable. \$1.2\$ doesn't need to be rounded, but \$1.20\$ is also perfectly acceptable).
Indexes can be either 1-indexed or 0-indexed, and will always be within the bounds of the array.
This is code-golf, so the shortest code in bytes wins!
Examples
Using 1-indexed and rounded to 2 d.p
list, index                    =>         output
[1, 2, 3, 4, 5], 5             => 5 / 15    => 33.33
[7, 3, 19], 1                  => 7 / 29    => 24.14
[1, 1, 1, 1, 1, 1, 1, 1, 1], 6 => 1 / 9     => 11.11
[20, 176, 194, 2017, 3], 1     => 20 / 2410 => 0.83
[712], 1                       => 712 / 712 => 100

Or, as three lists:
[[1, 2, 3, 4, 5], [7, 3, 19], [1, 1, 1, 1, 1, 1, 1, 1, 1], [20, 176, 194, 2017, 3], [712]]
[5, 1, 6, 1, 1]
[33.33, 24.14, 11.11, 0.83, 100]

Sandbox post (now deleted)

how exactly can non-integers be output as unary / church numerals?

@Doorknob Maybe a unary number, the dot, and another unary number?

Since the output can be rounded to two decimal places, it might also be permissible to output rounded times 100?

What if I don't choose to round the result, given that I only have an integer division operator?

test case 4 should be 20/2410

@Doorknob I don't know, I was just allowing people to take input in the most natural way

@Neil Only using integer division isn't acceptable, sorry

"Given a list of integers", it says. Can I take [1.0] in place of [1]?

@Khuldraesethna'Barya Yes that's perfectly fine

Python 3, 26 bytes
lambda i,a:a[i]/sum(a)*100

An unnamed function accepting an integer (0-indexed index) and a list which returns the percentage.
Try it online!

APL (Dyalog Unicode), 9 bytesSBCS
Anonymous tacit infix function. Takes index as left argument and list as right argument.
100×⌷÷1⊥⊢

Try it online!
100 one hundred
× times
⌷ the indexed element
÷ divided by
1⊥ the sum (lit. the base-1 evaluation) of
⊢ the right argument

C# (Visual C# Interactive Compiler), 22 bytes
x=>y=>x[y]*100/x.Sum()

Try it online!

Jelly, 7 bytes
ị÷S}ȷ2×

A dyadic Link accepting an integer, one-based index on the left and a list of numbers on the right which yields the percentage.
Try it online!
How?
ị÷S}ȷ2× - Link: integer, i; list, L
ị       - (i) index into (L)
   }    - use right argument:
  S     -   sum (L)
 ÷      - divide
    ȷ2  - literal 10^2 = 100
      × - multiply

Nice! That's byte for byte what I had :P

05AB1E, 6 bytes
è²O/т*

A full program taking the index then the list. Uses 0-indexing.
Try it online!
How?
è²O/т*
è      - index (input 1) into (input 2)
 ²     - push 2nd input
  O    - sum
   /   - divide
    т  - push 100
     * - multiply
       - print top of stack

Java (JDK), 47 bytes
a->i->1e2*a[i]/java.util.Arrays.stream(a).sum()

Try it online!

Why did you wrote 1e2 instead of 100? Is it because 100 is integer and 1e2 is considered as a floating point number?

@IsmaelMiguel Yes: 1e2 carries the double type, which a[i] and the sum don't. Since the challenge requires to return floating point numbers, that's where I can use it.

Change it to a BiFunction<int[], Integer, Double> and you can save 10 bytes with this: (a,i)->1e2*a[i]/IntStream.of(a).sum(). Edit: >:( my poor lambda arrow

@Avi The import is still required, so I'd have to write: (a,i)->1e2*a[i]/java.util.stream.IntStream.of(a).sum(), which is 54 bytes long. My current answer is only 47 bytes long. Also, a->i-> is one byte shorter than (a,i)->.

Is the import required? That's weird, I thought it wouldn't be

@Avi Yes, they are required, and it's usually shorter to write the full class name instead of the import, so that's what I do here

Do things in the JDK count as built-ins or external libraries? Edit: nevermind, I think I understand now.

@OlivierGrégoire Thank you. That makes sense.

J, 10 bytes
100*{%1#.]

Try it online!
0-indexed

R 28 bytes
function(n,l)100*l[n]/sum(l)

Try it online!

I don't know R, but this doesn't look like it works (not sure how to test it on TIO with arbitrary arrays), as you are supposed to retrieve the element of l at index n, not just divide by n (see the [7, 3, 19], 1 testcase)

@cairdcoinheringaahing My bad, had a typo (forgot the l[] around the n)

There's a thing on the TIO link page that can format this for you.

C (gcc), 64 bytes
0-indexed. The only fun bit was the realization that 1e2 is a double, saving a byte over 100.!
float f(v,n,t)int*v;{n=v[n];for(t=0;*v;t+=*v++);return n*1e2/t;}

Try it online!

Try it online! 59 using C(clang)

JavaScript (ES6), 30 bytes
Takes input as (array)(index), where index is 0-based.
a=>n=>a[n]*100/eval(a.join`+`)

Try it online!

Haskell,  20  18 bytes
i?a=a!!i/sum a*100

A dyadic operator (?) taking the (0-indexed) index on the left and a list on the right which yields the percentage.
Try it online!

PHP (7.4), 35 bytes
fn($l,$i)=>100/array_sum($l)*$l[$i]

Try it online!
Input index is 0-based.

Wolfram Language (Mathematica), 15 bytes
100##[[]]/Tr@#&

Try it online!
Input as list, index

##[[]] is awesome!

MATL, 9 bytes
)1Gs/100*

Try it online!
Explanation
          implicitly take two inputs
)         get the entry within the first input at the index specified by the second
 1G       push the first input onto the stack again
   s      compute the sum
    /     divide first entry of the stack by this number (the sum)
     100* multiply by 100

Try it online!

K (oK), 15 14 bytes
-1 byte thanks to ngn!
{100*x[y]%+/x}

Try it online!
0-indexed

(x@y) -> x[y]

TI-Basic, 12 bytes (12 tokens)
Prompt X
Ans(X)E2/sum(Ans

1-indexed
Takes the list in Ans and prompts the user for the index
Example run
Explanation:
Prompt X         # Prompt the user for the index
Ans(X)E2/sum(Ans
Ans(X)           # The value at the Xth index in the list
      E2         # times 100
        /sum(Ans # Divided by the sum of the list
                 # The result of the last expression in a program is implicitly returned

Red, 31 29 bytes
-2 bytes thanks to ErikF
func[b i][1e2 * b/:i / sum b]

Try it online!

(-2 bytes) suggest using 1e2 instead of 100.0: Try it online!. It's pretty neat how many languages can use this trick!

@ErikF Thank you! I know this in theory, but as it seems, I forgot to use it :)

Zsh, 32 30 bytes
-1 thanks to @ErikF, using 1e2 instead of 100..
<<<$[1e2*$@[`<&0`]/(${@/#/+})]

Try it online!
Try it online!
Accepts the list as arguments and the index on stdin.
<<<$[1e2*$@[`<&0`]/(${@/#/+})]  # $[ arithmetic ]
   $[       `<&0`            ]  # capture stdin
   $[    $@[     ]           ]  # index into the arguments
   $[1e2*$@[`<&0`]           ]  # multiply by 100.0 (casts to float)
   $[              (${@/#/+})]  # prepend each element with + and add
   $[             /          ]  # divide
<<<                              # print to stdout

Alternate 30 byte solution

(-1 bytes) 1e2 instead of 100. works just like in C to cast to float: Try it online!

Oops, this beats my 39 bytes solution!

MathGolf, 7 6 bytes
§\Σ/♀*

0-based indexing.
Try it online.
Explanation:
§       # Index the (implicit) second input-integer into the first (implicit) input-list
 \      # Swap so the first (implicit) input-list is at the top of the stack
  Σ     # Take the sum of that input-list
   /    # Divide the earlier indexed number by this sum
    ♀*  # Multiply it by 100
        # (after which the entire stack joined together is output implicitly as result)

Factor, 46 bytes
: f ( i l -- n ) dup [ nth ] dip sum / 1e2 * ;

Try it online!
0-indexed

Save three bytes by replacing dup [ nth ] dip with [ nth ] keep Try it online!

PowerShell, 34 bytes
param($l,$n)$l|%{$i+=$_};$l[$n]/$i

Try it online!
Shame parameters are so dang expensive in Powershell.

Go, 79 bytes
func f(a[]float64,i int)float64{s:=0.
for _,v:=range a{s+=v}
return a[i]/s*100}

This has a nice amount of accuracy. It takes a Go slice and uses range to calculate the sum.
Try it online!

Scratch 3.0 24 23 blocks/239 228 bytes

Alternatively in SB syntax
when gf clicked
set[s v]to(0
ask()and wait
repeat until<(answer)=(
add(answer)to[m v
ask()and wait
end
set[n v]to(item(length of(n))of(m
repeat(length of((m)-(1
change[s v]by(item(1)of[m v
delete (1)of[m v
end
say(((n)/(s))*(100

Saved 11 bytes thanks to @JoKing
Try it on scratch
Answer History

Alternatively in SB syntax
when gf clicked
set[s v]to(0
ask()and wait
repeat until<(answer)=(
add(answer)to[m v
ask()and wait
end
set[n v]to(item(length of(n))of(m
delete(n)of[m v
repeat(length of(m
change[s v]by(item(1)of[m v
delete (1)of[m v
end
say(((n)/(s))*(100

Try it on scratch
Input is in the form of:
item1
item2
...
itemN
index

I really should stop doing this to myself. But it is very fun!

Can you change repeat length of m to length of m-1 and save yourself the delete n?

No, because if I did, it wouldn't tally the last item.

Well, if you remove the delete n of m like I suggested then it would

Pyth, 13 bytes
c*100@hQeQshQ

Try it online!
First time using Pyth so theres probably some pretty big optimizations here, but I dont know where they are...
0-index, takes input as list, index

Snap!, 79 bytes (scratchblocks syntax)
((L)(i))::hat
report((combine(L)using((()+()@addInput)@addInput::grey ring))/(i

This is a "custom block" (function), and it takes a "list" (array) as the first argument and the idnex as the second argument.
Wow, having to manually mark hats/grey rings/grey ring inputs really makes short Snap! code in scratchblocks look relatively ugly.

CJam, 14 12 bytes
-2 bytes thanks to @luis-mendo
_@=\:+d/1e2*

Try it online!
0-indexed. Takes input as index [list]
Explanation
code         | explanation
-------------|------------
_@=\:+d/1e2* | whole program
 @=          | get the item at the index
_  \:+       | sum the array
      d      | convert to a *d*ouble
       /     | divide
        1e2* | multiply by 100

You can replace {+}* by :+ (quick fold) to save 2 bytes

Erlang 41 bytes
f(X,N)->lists:nth(N,X)/lists:sum(X)*100.

Perl 5 -ap -MList::Util=Sum, 19 bytes
$_=100*$F[<>]/sum@F

Try it online!
Take the list, space separated on the first line, the index (0-based) on the second.

Japt, 8 bytes
gV
*L/Vx

Try it

Retina 0.8.2, 102 bytes
\d+
$*
^(1)+((?<-1>.(1+))+)
$3$2
,

\G1
10000$*
;(1+)\1
$1;$1$1
r`.*(\2)*;(1+)
$#1
+`^..?$
0$&
..$
.$&

Try it online! Link includes test cases. Takes input as index;list,.... Explanation:
\d+
$*

Convert to unary.
^(1)+((?<-1>.(1+))+)
$3$2

Index into the list.
,

Sum the list.
\G1
10000$*
;(1+)\1
$1;$1$1
r`.*(\2)*;(1+)
$#1

Multiply the desired value by 10000 and divide by the sum with rounding by adding on half of the sum first.
+`^..?$
0$&

Ensure that the result has at least three digits.
..$
.$&

Insert a decimal point at the second last position.

Bash, 77 75 73 72 80 76 75 bytes
a=($@)
((b=10000*${a[$1]}/(${@/%/+}-$1),b<10))
echo $[b/100].${?/1}$[b%100]

Try it online!
+8 bytes thanks to GammaFunction, who found a bug with large numbers
-5 bytes thanks to GammaFunction, who golfed his original bug fix

Ah, nice catch.  Ty!

Whoops, saved one more. I don't think bash is going to let me be any more clever than this, though

Ruby, 25 23 21 bytes
->a,i{1e2*a[i]/a.sum}

Try it online!

AWK, 43 40 bytes
{s+=a[NR]=$1}END{print 100*a[$1]/(s-$1)}

Try it online!
-3 bytes thanks to CowsQuack
Takes the index as the last line of input

I saw you mention in chat for more test cases, here's a bash wrapper.

@GammaFunction Thanks!  I had no idea you could write to the file system in TIO.

@GammaFunction What's the reason we need the space and single quotes around EOF there to make it work?

Single quotes prevent $expansions from happening in the heredoc. The space does nothing either way

{s+=a[NR]=$1} shaves 3 bytes

@Cowsquack thank you. updated.

Racket, 81 43 bytes
Accepts a list and index. Outputs rationals (default for division in Racket).
Big thanks to Galen Ivanov for finding the apply function. Still learning as I go :) .
(λ(l i)(*(/(list-ref l i)(apply + l))100))

Try it online!

To my understand, #lang racket is not counted into bytes if submission is a function.

I think tsh is right. You can make it work in TIO by assigning the lambda to a variable. Since this is code-golf, you need to remove all the whitespaces like this for 60 bytes

(foldl (λ (a b) (+ a b)) 0 l) -> (apply + l) for 44 bytes

@GalenIvanov The last ) is matched to (define and is not a part of function. So it should not be included too.

@tsh Yes, of course! I forgot to move it to the footer. So it is 43 bytes

Perl 6, 21 bytes
{100*@^a[$^b]/@a.sum}

Try it online!
The simple solution, since I can't use curried parameters with the $b parameter being indexed. A funner solution that doesn't have to handle two parameters by using the rotate function instead:
{100*.[0]/.sum}o&rotate

Try it online!
But it is unfortunately two bytes longer

Octave, 21 bytes
@(a,n)a(n)/sum(a)*100

Try it online!

Icon, 53 bytes
procedure f(L,i)
s:=0;s+:=!L&\z
return 1e2*L[i]/s
end

Try it online!
The only interesting thing here is finding the sum. Icon was one of the first languages to have generators. ! generates all the values of the list L that are accumulated to s. Normally we need to write every s+:=!L, but I used backtracking with &\z, which checks if the non-existent z variable is non-null, which is not, and extracts the next value from the list until exhaustion.

Batch, 111 bytes
@shift
@set s=%*
@call set/as=%s: =+%-%0,s=(%%%0*10000+s/2)/s,h=s%%%%10,t=s/10%%%%10,s/=100
@echo %s%.%t%%h%

Takes input as index and list as command-line arguments. Note: Only works for index values from 1 to 9 due to limitations of Batch; a 0-indexed version could be written which would be able to index the first 10 elements. Explanation:
@shift

Shift the index to %0 and the list to %1...%9 (or less). Note however that Batch's shift does not affect %*.
@set s=%*

Get all of the parameters, space separated.
@call set/as=%s: =+%-%0,s=(%%%0*10000+s/2)/s,h=s%%%%10,t=s/10%%%%10,s/=100

Change the spaces to +s and evaluate arithmetically, thus taking the sum, but subtract the index. Then index into the list, multiply by 10000, add half of the sum, and divide by the sum. Finally perform divmod by 10 twice to generate the decimal places. (The % arithmetic operator has special meaning in Batch and normally needs to be doubled but the call then requires a further doubling.)
@echo %s%.%t%%h%

Output the result and the decimal places.

Swift, 60 bytes
{(n:[Int],i)->Float in
1e2*Float(n[i])/Float(n.reduce(0,+))}

Try it online!
I picked Swift to participate and bumped into its type sensitivity !

T-SQL 2008, 41 bytes
To find the row number equal to the index:
A division of index and row number multiplied with division of row number and index, if both results are 1, index and row are the same because both are above 0 and integer division round down. This saves 1 byte compared to using IIF

a - value
b - row number

Using table variable as input. 1-indexed
SELECT max(b/@*(@/b)*a*100)/sum(a)FROM @x

Try it online

Julia 1.0, 21 bytes
f(l,i)=100l[i]/sum(l)

Try it online!

Stax, 7 bytes
â└╡Æå'W

Run and debug it at staxlang.xyz!
0-indexed. Requires at least one item in the input list to be of the form N.0 rather than simply N. Replacing / in the unpacked version with :_ gets around this restriction at the cost of one byte.
Unpacked (8 bytes) and explanation:
@AJ*x|+/    Index atop the stack, with the list beneath
@           Element at index...
 AJ*        Times 100
    x|+     Sum of list
       /    Divide

k4, 14 bytes
{%+/x%100*x y}

can save 1 byte from @Galen Ivanov's solution (in oK) as % is inverse operation in k4 as opposed to square root

Clojure, 40 bytes
(fn[a b](* 1e2(/(nth a b)(apply + a))))

Try it online!
It's nice to know about the 1e2 trick. :-)

Pyt, 10 bytes
Đ←⦋⇹Ʃᵮ/2ᴇ*

Try it online!
Zero-based indexing.
Takes the array, then the index
Đ                 implicit input; Đuplicate
 ←                get input
  ⦋               get element at index
   ⇹              swap top two items on stack
    Ʃ             get Ʃum
     ᵮ            cast to ᵮloat
      /           divide
       2ᴇ*        multiply by 100; implicit print

Arturo, 23 bytes
$[a,i][100*a\[i]//∑a]

Try it

PowerShell Core, 39 bytes
param($a,$i)$a[$i]/($a-join'+'|iex)*1e2

Try it online!
Uses 0 indexed input and doesn't do rounding

Itr, 11 bytes
#ä#@áS/100*
zero-indexed, outputs a fraction
online Interpreter
7 bytes to output the proportion as a fraction:
#ä#@áS/
Explanation
#           ; read the first input
 ä          ; duplicate it
  #         ; read the second input
   @        ; get the element at that index in the first input
    á       ; swap the two elements
     S      ; sum up the array
      /     ; divide the element by the sum
       100* ; convert the result to percent
            ; implicit output

Itr, 14 bytes
#ä#@áS/0e100**
outputs the result as a float

Rust, 36 bytes
|v,i|v[i]*100./v.iter().sum::<f32>()

0-indexed, assuming integers cast to floats before the function call
Rust Playground

Canvas, 8 bytes
＠；∑÷ＡＡ××

Try it here!
Uses 1-indexing.
The last half just multiplies by 100, so 4 bytes can be saved if percentage over interval [0,1] is allowed as opposed to percentage over interval [0,100].

Explanation of example run: list = [1, 2, 3, 4, 5], index = 5.
Stack Visualization                 | Executed Instruction | Explanation
------------------------------------+----------------------+-----------------------------------------------------------------------------
..., [1,2,3,4,5], 5, [1,2,3,4,5]    | (program start)      | Canvas starts with the stack populated with the inputs repeating infinitely
..., [1,2,3,4,5], 5                 | ＠, get item         | ＠NA gets the Nth item of A
..., 5, [1,2,3,4,5]                 | ；, swap two ToS     | Swaps the position of the two top items in the stack
..., 5, 15                          | ∑, sum               | Sums all items in an array
..., 0.33333333333333333333         | ÷, divide            | Divides the two top items in the stack
..., 0.33333333333333333333, 10     | Ａ, push 10          | Pushes 10 to the stack
..., 0.33333333333333333333, 10, 10 | Ａ, push 10          | "                    "
..., 0.33333333333333333333, 100    | ×, multiply          | Multiplies the two top items in the stack
..., 33.333333333333333333          | ×, multiply          | "                                       "
...                                 | (end of program)     | Pop and print ToS

Forth (gforth), 61 bytes
: f 8 * over + f@ 0e swap 0 do dup f@ f+ 8 + loop f/ 1e2 f* ;

Try it online!
It's way too painful to work with arrays in Forth...
A function that takes three items (array length, array start address, index; rightmost being the top) from the main stack, and gives the answer on the FP stack. The array contains floating-point values.
How it works
: f ( len addr idx -- F: ans )
  8 * over + ( len addr addr[idx] ) \ compute the address for the item
  f@ 0e ( len addr F:x F:sum )      \ fetch the float at addr[idx] and push 0 on FP stack
  swap 0 do ( addr F:x F:sum )      \ repeat len times..
    dup f@ f+                       \   fetch the float at addr, add it to the sum
    8 +                             \   increment the addr by one cell
  loop                              \ end loop
  f/ 1e2 f*                         \ compute x / sum * 100
;

Vyxal, 6 bytes
₌i∑/₁*

Try it Online!
Another 6 byter joins the fray. Takes index then list. 0-indexed
Explained
₌i∑/₁*
₌i∑     # Push list[index], sum(list)
   /    # ^ / ^
    ₁*  # times 100

Thunno, \$ 9 \log_{256}(96) \approx \$ 7.41 bytes
AHz1S/Z2*

Attempt This Online!
Uses 1-indexing. Change AH to AI for 0-indexing.
Explanation
AHz1S/Z2*  # Implicit input
AH         # Index into the list
  z1S      # Sum the list
     /     # Divide
      Z2*  # Multiply by 10**2

Thunno 2, 6 bytes
i$S/ɦ×

Try it online!
0-indexed. Change i to İ for 1-indexing.
Explanation
i$S/ɦ×  # Implicit input
i       # Index in
 $      # Push the first input again
  S     # Take the sum
   /    # Divide
    ɦ×  # Multiply by 100
        # Implicit output


text:
Decode a UTF-8 string to character byte counts
Given a UTF-8 string, give a string that represents byte counts of each characters.
Rules:

As long as the input string is encoded in UTF-8 (without BOM), its type doesn't matter. In C++, it can be char[] or std::string. In Haskell, it can be [Int8] or [CChar].
The output must be (in usual case) a string of ASCII digit characters. Its encoding doesn't matter.
When given an invalid UTF-8 sequence (including representation of surrogates), every bytes of the sequence are to be represented as the replacement character �.
Reserved characters and noncharacters are still considered as valid UTF-8 sequences, and thus must have corresponding output digit.
As this is a code-golf, the shortest code in bytes wins.

Example:
When given the following byte sequence:
00 80 C0 80 EB 80 80

The output must be:
1���3

Recommended test case: b'Hej d\xc3\xc5!' (i.e. 48 65 6A 20 64 C3 C5 21) (invalid continuation byte (C5) after a valid start byte (C3)) (expected output: 11111��1)

Closely related

Python 3, 135 bytes
def f(b):
	B=b.decode(errors="ignore")[:1].encode();l=len(B)
	if B and b[:l]!=B:return"�"+f(b[1:])
	return str(l)+f(b[l:])if b else''

Try it online!
Explanation:
def f(b):
	B=b.decode(errors="ignore")[:1].encode();l=len(B)
	 # B is the UTF-8-encoded version of the first Unicode character in the given bytes
	 # (Or the Nth, if the first N-1 bytes were invalid Unicode bytes)
	if B and b[:l]!=B:return"�"+f(b[1:])
	 # If the two encoded byte-strings don't match,
	 # then the first byte in b is invalid,
	 # so append "�" to the returned string, and recurse
	return str(l)+f(b[l:])if b else''
	 # If the byte-string is not empty,
	 #  append the length of the first character and recurse.
	 # Else (the input is empty) return the empty string (recursion base case)