Duck, duck, gone!

40

4

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 (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 = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    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('<a>'+lang+'</a>').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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

user85052

Posted 2019-09-24T09:45:48.353

Reputation:

22I 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! – Shaggy – 2019-09-24T09:58:16.220

8Possible duplicate. Just kidding :) – Night2 – 2019-09-24T12:28:43.567

2That song lyrics sure made me go through a roller coaster of emotions. – Num Lock – 2019-09-25T10:04:04.620

2I 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... – Night2 – 2019-09-25T12:24:09.970

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

– Darrel Hoffman – 2019-09-25T20:53:46.280

2Nice challenge! Outputting the next verse is a really novel and creative twist on text-printing. – xnor – 2019-09-26T05:48:09.980

3Any reason the capitalization on "Mother duck" and "Mother Duck" is different in the 2 places it is used in the last verse? – Chill – 2019-09-26T18:00:52.990

Answers

4

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

recursive

Posted 2019-09-24T09:45:48.353

Reputation: 8 616

1When you run it with "One little duck", it responds "little ducknd little duckll of the little ducks came back." in the last line. – Dorian – 2019-10-02T10:25:24.533

1The 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. – recursive – 2019-10-02T16:26:54.933

19

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.".

Arnauld

Posted 2019-09-24T09:45:48.353

Reputation: 111 334

231 – Shaggy – 2019-09-24T12:00:46.610

1@Shaggy Nicely done. Thanks! – Arnauld – 2019-09-24T12:08:04.513

2Was just posting another comment to suggest exec when the page reloaded. Great minds ... ! – Shaggy – 2019-09-24T12:14:59.767

11

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!

Black Owl Kai

Posted 2019-09-24T09:45:48.353

Reputation: 980

for a in zip(T,T[-2:]+T):s=s.replace(*a) for 264 bytes. – ovs – 2019-09-24T11:17:43.563

Or lambda s:reduce(lambda s,a:s.replace(*a),zip(T,T[-2:]+T),s) for 262 bytes in Python 2. – ovs – 2019-09-24T11:19:58.987

@ovs Thanks, I got it to 263 with reodering some things and using T[2:] instead of T[-2:] – Black Owl Kai – 2019-09-24T13:18:28.783

9

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!

Adám

Posted 2019-09-24T09:45:48.353

Reputation: 37 779

1243 bytes – Black Owl Kai – 2019-09-24T13:24:55.700

1242 bytes – Kevin Cruijssen – 2019-09-24T13:29:51.450

7

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:

  1. Replace original (below) with an entirely different strategy
  2. Saved two bytes by switching to LEFT instead of SUBSTRING and eliminating a space
  3. 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.

BradC

Posted 2019-09-24T09:45:48.353

Reputation: 6 099

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. – CDC – 2019-09-27T19:26:51.257

BTW, really fun solution. I used formatmessage to get very close to you, but not quite. – CDC – 2019-09-27T19:28:03.947

Good suggestions, @CDC, thanks! – BradC – 2019-09-27T19:49:11.610

7

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

Kevin Cruijssen

Posted 2019-09-24T09:45:48.353

Reputation: 67 575

6

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.

Night2

Posted 2019-09-24T09:45:48.353

Reputation: 5 484

6

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]]

Prachiti Prakash Prabhu

Posted 2019-09-24T09:45:48.353

Reputation: 161

11

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.

– Post Rock Garf Hunter – 2019-09-24T22:22:07.413

wow @SriotchilismO'Zaic! that's helpful..thank you! :) – Prachiti Prakash Prabhu – 2019-09-24T22:44:33.537

1You 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 – Jo King – 2019-09-26T05:38:13.913

@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! :) – Prachiti Prakash Prabhu – 2019-09-26T17:34:59.870

5

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!

Οurous

Posted 2019-09-24T09:45:48.353

Reputation: 7 916

5

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!

Embodiment of Ignorance

Posted 2019-09-24T09:45:48.353

Reputation: 7 014

3

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

Andrei Odegov

Posted 2019-09-24T09:45:48.353

Reputation: 939

3

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.

mazzy

Posted 2019-09-24T09:45:48.353

Reputation: 4 832

2

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!

spuck

Posted 2019-09-24T09:45:48.353

Reputation: 649

2

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

Shaggy

Posted 2019-09-24T09:45:48.353

Reputation: 24 623

2

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

Dorian

Posted 2019-09-24T09:45:48.353

Reputation: 1 521

1

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.

Jo King

Posted 2019-09-24T09:45:48.353

Reputation: 38 234

1

Charcoal, 156 bytes

≔⌕tvuroe§θ²δ§⪪”↶0∨↘»≔xj➙⌈´βXPNLA‽⟦O⧴&▷V'¦³≧ψZρ⊞t”¶δF‹δ⁵”↶↧V4ⅉH‴G%”F‹δ⁴s⮌…⮌θ¹⁸⸿η⸿ζ⸿§⪪”}∧h⁴NQ≕Q^⪫ΦG✂q'ⅉMG./_⸿s⁵6P⁴″⊟±NNpOfBz↷Fι‖TM→⁻γ?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➙⌈´βXPNLA‽⟦O⧴&▷V'¦³≧ψZρ⊞t”¶δF‹δ⁵”↶↧V4ⅉH‴G%”F‹δ⁴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⁴NQ≕Q^⪫ΦG✂q'ⅉMG./_⸿s⁵6P⁴″⊟±NNpOfBz↷Fι‖TM→⁻γ?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.

Neil

Posted 2019-09-24T09:45:48.353

Reputation: 95 035

1

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.

Sara J

Posted 2019-09-24T09:45:48.353

Reputation: 2 576