Spanish Verb Conjugator

8

3

Explanation

¡Hola! For those of you who don't take Spanish, a verb is conjugated based on the person who does the action. Here's a chart:

English                   Spanish
I                         Yo
You                       Tú
He                        Él
She                       Ella
You (formal)              Usted
We all                    Nosotros
You all                   Vosotros
They (masculine, plural)  Ellos
They (feminine, plural)   Ellas
You (plural)              Ustedes

In Spanish, all verbs end with ar, er, or ir. Here's another helpful chart:

          Ar    Er    Ir
Yo        o     o     o
Tú        as    es    es
Él        a     e     e
Ella      a     e     e
Usted     a     e     e
Nosotros  amos emos imos
Vosotros  áis  éis  ís
Ellos     an   en   en
Ellas     an   en   en
Ustedes   an   en   en

Given a pronoun and a verb, print the verb conjugated using the pronoun in the present tense. Don't worry about stem changing and odd verbs.


Examples

Input        Output
Yo escribir  Escribo
Tu enseñar   Enseñas
Ella querer  Quere (It should be quiere but ignore stem changes)

If your language doesn't support printing with accents, you can omit them. Otherwise, it shouldn't take any more characters to use á instead of a in your code.

You can find more words with which to test here: http://spanish.speak7.com/spanish_vocabulary_verbs.htm. Note that contester should be contestar.


Challenge: Stem Changes

In Spanish, some verbs have stem changes. Let's take the verb querer for example. In all forms except nosotros and vosotros, the first e changes to ie. So, yo quiero, but nosotros queremos. If your program can account for stem changes, you may subtract twice the length of each word you support from your final score. For example, if you support the i -> ie change querer and only querer, you can subtract twice the length of querer, or 12, from your score.

For some stem-changing verbs, try this: https://conjuguemos.com/chart.php?language=spanish&id=2&etre=no&commands=no&all=no&source=public


Small Bonuses

Just for fun, if you explain what your code does in Spanish, take off 30 from your score. Don't just use Google Translate or I'll be able to tell that you cheated.


(As I am not a native Spanish speaker, please correct me on any mistakes)

nrubin29

Posted 2014-03-14T15:38:41.317

Reputation: 225

Empezo or Empiezo? – Stan Strum – 2018-04-26T16:15:52.967

2I don't take Spanish: I just speak it; but a) is the nominative form of the pronoun: tu is genitive; b) verbs aren't "paired" with pronouns; c) nominative pronouns are rarely used in Spanish, so this exercise teaches bad habits; d) you should mention that this is only conjugating the present indicative; e) you haven't said how to handle pronomial (aka reflexive) verbs; f) the most common verbs are irregular, so this isn't a practical tool: if you want to make a verb conjugation question without worrying about irregularities you should use Esperanto instead of Castellano. – Peter Taylor – 2014-03-14T15:50:00.447

a) With what should I replace it? b) How would you word it? c) Not quite sure what you mean. The first example, yo escribo seems like something someone would commonly say. d) I'll fix that. e) You can assume that the se isn't given (ex: yo despertar). f) Not really meant to be practical, and I'll add a challenge for stem changes and one for verbs like ser and estar. Also not sure what Esperanto and Castellano are. Different forms of Spanish? – nrubin29 – 2014-03-14T16:19:41.267

a) ; b) Verbs are conjugated according to tense, mood, and grammatical person; c) A native speaker would say Escribo with no pronoun unless really stressing the pronoun; f) Esperanto is an artificial language which has no irregular verbs. – Peter Taylor – 2014-03-14T16:35:47.953

1a) Fixing that now. b) Fair enough, fixing. c) True, but this is meant more as a challenge than a useable tool. I could remove the requirement to print the pronoun (yo escribir -> escribo) but I'd rather leave it in. f) I'll just leave it in "normal" Spanish and add a challenge for "special" verbs. Hope I didn't come off as rude, I appreciate the feedback. – nrubin29 – 2014-03-14T16:39:17.410

Input Yo, Escribir. Correct output: Escribo (except if the person REALLY wants to stress I write!) Input Tu, Enseñar. Correct output: Enseñas (except if the person really wants to stress YOU teach.) Forget about querer, it's irregular. Here's a list of regular verbs from a quick search (contester is wrong, it should be contestar but I haven't found any other mistakes.) http://spanish.speak7.com/spanish_vocabulary_verbs.htm. I'm a native english speaker who's spent 5 years in Madrid by the way.

– Level River St – 2014-03-14T16:44:06.080

How should the accented letters be handled? They're not part of standard 7 bit ASCII. You need to specify an extended ASCII codepage, or Unicode, or whatever. Alternatively there's the rather ugly alternative of typing apostrophe or ~ before the relevant letter (which is incorrect but unambiguous.) – Level River St – 2014-03-14T16:50:16.020

@steveverrill I'll amend the examples so they don't print the pronoun. Also, the querer example was just to show that even if an irregular verb was entered, the stem wouldn't need to be changed. I'll add a link to that list above. You can ignore accents if your language doesn't support printing with them. – nrubin29 – 2014-03-14T16:53:27.733

Linguistically it's looking much better now (except ustedes is you plural, not they.) However you need to clarify how to handle non ASCII accents in both input (especially the pronouns that need to be recognised) and output. Parsing accented pronouns is going to be a real headache. Either specify how this should be done or specify that it's not required (seeing as you've already cut the language down from 7 tenses to one.) That "quere" looks horrible to me but I accept that it's the only way. I have seen similar sacrilege of (for example) musical conventions in other questions. – Level River St – 2014-03-14T17:11:51.733

@rusher the OP has clarified we don't have to consider accents. Therefore we can parse él and ella as just e***. Relevant, and handy, given they conjugate the same. – Level River St – 2014-03-14T17:45:30.373

@steveverrill Fixed ustedes. – nrubin29 – 2014-03-14T18:16:36.597

3While I was in the middle of working on my answer, you changed the scoring by adding a bonus challenge! I'm no longer interested in golfing this because of the additional bonus score modification and the promise of more changes to come. I already wasted an hour on it, and that hour has become your downvote. – Rainbolt – 2014-03-14T20:30:31.340

@Rusher I don't quite understand what you mean. I'm sorry you feel like you wasted an hour, but I think you should still post your answer. I feel like adding challenges makes it more interesting, but you don't need to accept them. Besides, I can't think of too many more challenges that I could add. – nrubin29 – 2014-03-14T20:33:26.390

2@nrubin29: I didn't downvote but I agree w/ Rusher. You shouldn't change the scoring and rules after the question has been posted - especially after an answer has already been posted. Use the sandbox if you're not happy w/ the question yet. – Claudiu – 2014-03-14T20:34:02.533

@Claudiu Fair enough. This is my first question, so I wasn't quite sure how stuff works here. I won't make any more changes. – nrubin29 – 2014-03-14T20:35:45.010

just present tense? come on, we have a lot of tenses to pick from, some other has to be more interesting :p. As Claudiu said, if you think the question could benefit from feedback, post it in the last sandbox thread in http://meta.codegolf.stackexchange.com (I think the actual is X). Changing the requirements after posting here is rude towards the people who already started to work on an answer

– Einacio – 2014-03-14T20:48:10.640

@Einacio the problem with doing more tenses is that, beside having to take in a lot of linguistic data, there'll be a lot of abuse of irregular verbs (ya me choca un montón lo de "quere.") Anyway, as you say, I don't think he should change it more now. I don't fully agree with the new bonuses but -30 for explaining in Spanish is easy for me (even easier for you!) so I may as well take advantage. If I wanted I could probably get -1000 for stem changing verbs (but I think that's unsporting.) Theres about 100 verbs of that type here: http://www.spanishdict.com/answers/100045/present-tense#stem

– Level River St – 2014-03-14T21:21:33.887

@steveverrill The -30 for posting an explanation in Spanish is pointless. I don't know more than a few words of Spanish, and I certainly don't plan on learning it for a programming challenge. – grovesNL – 2014-03-15T18:58:16.310

1@grovesNL at least that -30 doesn't make a huge difference. The thing that's killed this question is the unlimited bonus for stem changing verbs. I thought we'd ironed out the ambiguities for the OP, then he suddenly threw in two new bonuses and offended Rusher. Hopefully he'll learn to think ahead, use the sandbox, and not add bits to his questions after posting. It's too late to go back now. – Level River St – 2014-03-15T19:05:51.390

The only reason why I implemented the Spanish explanation thing was to add a little fun and keep with the theme. I didn't realize how uber-competitve everyone was here. As I said before, I'm new here, so I didn't know that you couldn't add new challenges later (I did know that you can't overhaul the question, of course). I did not know what the sandbox was, therefore I didn't use it. Also, again, I'm sorry for offending anyone by changing the question. I'll probably stay away from asking questions from now on. – nrubin29 – 2014-03-15T19:13:15.960

1

@nrubin29 it's not a bad question at all. We aren't cutthroat competitive, but we do have a strong sense of fair play. We're also good at finding loopholes and if done right it's applauded. That means properly specifying a code-golf question is quite demanding as you must anticipate this (you can see the tricks people use!) Feel free to use the sandbox next time, the community will help you work on your question and make it as fair and unambiguous as possible. Judging by popularity-contest is another way to take the pressure off you. See also http://meta.codegolf.stackexchange.com/q/1061/15599

– Level River St – 2014-03-15T19:29:42.427

@steveverrill Thanks for the comment, that was extremely helpful. I'll use the sandbox next time. The reason why I chose code golf as opposed to popularity contest is that all answers will do the exact same thing. I guess it could go either way, but of course I'm not going to change anything ;) – nrubin29 – 2014-03-15T19:37:23.100

@nrubin29: I just want to add that I enjoyed doing this code-golf. The changing-stem challenge was a bit too open-ended (I have a huge negative score) but it was also fun to write that. So I do encourage you to ask more questions! It is indeed difficult to come up w/ a good one. – Claudiu – 2014-03-15T22:45:01.643

Answers

3

Python, 172 168 743 characters - 1796 bonus = -1053

Updated to take the stem-changing challenge.

p,v=raw_input().split()
y="aee";z=y+'n'
x=["ooo",y+'s',y,y,y,"aeimos","ae\x00is",z,z]["YoTuElEaUdNsVsEsUs".index(p[0]+p[-1])/2]
s=v[:-2]
X=v='eJw1UuHS5CAIe1aqrNsZhR6w/tj5Hv4Sv7uODRYDxEzlylKTplHS3xrS/3yIm4kntCTVSipkazaZ\n+AA32h3tY1ut+VL7NreXxsEEsgSheGynlJv/GNVvsPs9CIl2hoCSV+gYfuH7rdAyIQdr3+x92yCg\n2g7WEp4vMfTKgogyHabbL4z1l1p/1PLBCF4o9AjtmJBc6wpOTJykM+O0Ib2Y+FyCAuv5wcwCd+Ks\n4+XCdSwhqMIf/eJOFPMjV/rc0jw6IEvm8vjKdBuy/JryMPmEXwIiDInhtK01n1iDPrGu6/A5uy4/\nkBVd89R1OjvHCXbSnoDyaB23nhseElHosf45rzYC1zOevyDojQ548fjGCGg8M5aD8EAmB9GqgFHk\nBzRwDwJ6EcgK5aSDZ2/4TSAjKOMXd3gPh6sTq/+GApG0wkSYdzSBz/AXclUQ+g=='.decode('base64').decode('zip')
if s in X:
 j=X.index(s)<326
 s=(s.replace('oe'[j],'ui'[j]+'e'),s)[p[0]in'NV']
print s+x["aei".index(v[-2])]+x[3:]

Usage:

$ echo "Ellas querer" | python conj_golf2.py
quieren

Test on non-stem-changing inputs:

Yo ensenar -> enseno
Yo escribir -> escribo
Tu ensenar -> ensenas
Tu escribir -> escribes
El ensenar -> ensena
El escribir -> escribe
Ella ensenar -> ensena
Ella escribir -> escribe
Usted ensenar -> ensena
Usted escribir -> escribe
Nosotros ensenar -> ensenamos
Nosotros escribir -> escribimos
Vosotros ensenar -> ensenais
Vosotros escribir -> escribis
Ellos ensenar -> ensenan
Ellos escribir -> escriben
Ellas ensenar -> ensenan
Ellas escribir -> escriben
Ustedes ensenar -> ensenan
Ustedes escribir -> escriben

Stem-changing input examples:

It does both e->ie changes and o->ue changes, properly avoiding the nostros + vostros cases:

$ echo "Yo abstenir"|python conj_golf2.py
abstieno
$ echo "Nostros abstenir"|python conj_golf2.py
abstenimos
$ echo "Tu almorzar"|python conj_golf2.py
almuerzas
$ echo "Vostros almorzar"|python conj_golf2.py
almorzais

Here is how the bonus was determined and the data string generated, from which you can deduce the verbs on which it works:

e="absten.acert.adher.adquer.advert.apret.asent.atraves.calent.cerr."+\
  "circunven.comenz.confer.confes.consent.conten.contraven.conven.convert."+\
  "difer.diger.discern.disent.freg.gobern.hed.hel.her.herv.infer.inger."+\
  "invern.invert.malher.manifest.ment.neg.nev.obten.ofend.pens.perd."+\
  "quer.recomend.reg.seg.sembr.sent.serr.sosegsosten.soterr.subarrend."+\
  "suger.tembl.tend.ten.tent.transfer.tropez.ven.vert"

u="absolv.acord.acost.almorz.along.amobl.apost.aprob.asol.avergonz."+\
  "coc.col.colg.cont.cost.degoll.demol.demostr.desaprob.descolg.descontr."+\
  "desos.destorc.devolv.disolv.dol.dorm.encontr.engros.envolv.forz.holg."+\
  "holl.llov.mol.mor.mostr.mov.ol.pobl.prob.record.reforz.remord.remov.renov."+\
  "repobl.resolv.resoll.reson.retorc.revolc.revolv."+\
  "rod.rog.sol.sold.sol.solt.son.torc.tost.tron.vol.volc.volv"

words = e.split(".") + u.split(".")
bonus = 0
for word in words:
    bonus += (len(word)+2)*2
print "Bonus: %d from %d stem-changing verbs" % (bonus, len(words))

s=(e+"|"+u).replace(".","")
zipped = s.encode('zip')
b64 = zipped.encode('base64')
print "The separator is at index %d" % s.index("|")
print "Uncompressed: %d chars, %d repr" % (len(s), len(`s`))
print "Compressed: %d chars, %d repr" % (len(zipped), len(`zipped`))
print "Comp+B64: %d chars, %d repr" % (len(b64), len(`b64`))

print "v="+`b64`

Which gives:

$ python conj_help.py
Bonus: 1796 from 127 stem-changing verbs
The separator is at index 326
Uncompressed: 645 chars, 647 repr
Compressed: 331 chars, 1015 repr
Comp+B64: 450 chars, 458 repr
v='eJw1UuHS5CAIe1aqrNsZhR6w/tj5Hv4Sv7uODRYDxEzlylKTplHS3xrS/3yIm4kntCTVSipkazaZ\n+AA32h3tY1ut+VL7NreXxsEEsgSheGynlJv/GNVvsPs9CIl2hoCSV+gYfuH7rdAyIQdr3+x92yCg\n2g7WEp4vMfTKgogyHabbL4z1l1p/1PLBCF4o9AjtmJBc6wpOTJykM+O0Ib2Y+FyCAuv5wcwCd+Ks\n4+XCdSwhqMIf/eJOFPMjV/rc0jw6IEvm8vjKdBuy/JryMPmEXwIiDInhtK01n1iDPrGu6/A5uy4/\nkBVd89R1OjvHCXbSnoDyaB23nhseElHosf45rzYC1zOevyDojQ548fjGCGg8M5aD8EAmB9GqgFHk\nBzRwDwJ6EcgK5aSDZ2/4TSAjKOMXd3gPh6sTq/+GApG0wkSYdzSBz/AXclUQ+g==\n'

Claudiu

Posted 2014-03-14T15:38:41.317

Reputation: 3 870

I'll be staying away from the stem changes because it becomes question of linguistics rather than programming. Acordar should be Acord**, surely? And you can't give the right answer for both regar> riego,riegas etc and regir> rijo, riges etc. – Level River St – 2014-03-14T21:52:59.330

@steveverrill: oh yep I guess "acordar" slipped through. True I can't deal with same verbs of different stem but e.g. "regir" would be wrong anyway since I don't do g->j . Accuracy is not so important for this one. I see your point but I couldn't give up the enormous boon of bonus points =). – Claudiu – 2014-03-14T22:09:30.127

@steveverrill: Also there's chance for error if there's a verb that happens to fit in the concatenated verbs put together. e.g. if there's a regular verb "tenacar" it will be conjugated as a stem-changing one. This I can fix by leaving in the .s, would add 50 pts or so to the score – Claudiu – 2014-03-14T22:12:54.110

I'm trying to deduce the verb for which you have ten in your list of roots. teñir is e to i, not e to ie; tener is e to ie, but has an irregular stem change for 1s. Similarly abstener, circunvenir, obtener, sostener, venir, cocer, destorcer, oler, retorcer, torcer. On the other hand, your scoring script doesn't seem to count both sentar and sentir. And you're missing a . in sosegsosten, and descontr should probably be descont. – Peter Taylor – 2014-03-18T22:31:08.910

@PeterTaylor: It is tener I think. I didn't realize those verbs you listed had a special case. I can remove them or account for them (whichever is cheaper) and fix the typos if there's another close contender – Claudiu – 2014-03-18T22:52:36.140

3

Python, 240 bytes - (extremely large) bonus

from re import*;import urllib2 as u,sys;x=sys.argv
try:
 print search('>.*?'+sub('a','o',sub('ella','el',x[1]))+'.*? ([^<]*)',sub(u'\u00e9','e',sub(u'\u00fa','u',u.urlopen("http://smarturl.it/xz?word="+x[2]).read()))).group(1)
except:
 pass

Sample Output:

Input         | Output
yo escribir   | escribo
tu escribir   | escribes
tu ensenar    | ensenas
ella querer   | quiere
ellas querer  | quieren
nosotros vive | vi
tu acordar    | acuerdas

Explanation:

This code uses an existing free conjugation website (http://www.conjugation.org/) that returns various conjugations from a large database of verbs. I reduced the URL slightly by using a free online URL shortener that allows parameters to be passed through the redirection (http://smarturl.it/). I simply make a HTTP request based on the verb specified, remove the accents from the u and e in the source, find the pronoun in the HTML using regular expressions, then return associated conjugation.

It's impossible to tell how many verbs have stem changes without polling the entire database against a dictionary. It's probably safe to assume the negative bonus from this database is much larger than any bonus from encoded lists passed in (which increase the length of the code).

I could obviously have handled the accented characters better, but it would've required encode/decode and extra handling within the regular expressions.

grovesNL

Posted 2014-03-14T15:38:41.317

Reputation: 6 736

This answer breaks standard loopholes – None – 2015-10-13T19:06:03.490

3No longer funny – Claudiu – 2014-03-15T21:09:59.473

@Claudiu: It's not supposed to be a loophole - that post is not relevant here. The question itself has serious flaws which make some kind of external dependency necessary. Passing in a base64-encoded string of data isn't better than connecting to an external data source. – grovesNL – 2014-03-15T22:00:30.613

It is better because it is counted as part of my score. My script is entirely self-contained and actually does the conjugation work. Yours just retrieves it from an external data source. You can't even count your score because it depends entirely on how many verbs that data source processes. If that site or the URL shortener goes down then your answer becomes invalid. – Claudiu – 2014-03-15T22:42:27.710

@Claudiu: Regardless, it's irrelevant because the question is best suited to reference an external database. The conjugations themselves are as trivial as using re.sub or string.replace when not having to handle stem changes, etc. Even your program would receive a greater negative score if you keep adding further stem changing verbs to your encoded list. The question is flawed. – grovesNL – 2014-03-15T23:18:12.773

@Claudiu , grovesNL Hahaha. Haha. Calm down both of you. It is funny in this case because the question is flawed. It's only a game and both of you have errors in your Spanish. It's going to be impossible to call a winner on this because of that flaw. The win is only 15 reputation anyway. Here, have an upvote each and play nicely. – Level River St – 2014-03-19T17:45:51.780

1

Freepascal, 218 chars -30 = 189

It's a tough call to beat the (original) python answer, especially with Pascal. I may try and improve tomorrow, possibly with a similar concept in a different language. I will not be submitting a stem-changing answer, as I see this as a linguistic rather than programming challenge.

var y,p,v:string;BEGIN y:='amosemosimosais eis is  as  eso eso   o   an  en  en';readln(p);readln(v);writeln(copy(v,1,length(v)-2),copy(y,6*(7-pos(p[1],' yt v n'))+pos(v[length(v)-1],y),pos(p[length(p)],'u s')+1));END.

Ungolfed version:

var y,p,v:string;
BEGIN 
  y:='amosemosimosais eis is  as  eso eso   o   an  en  en';
  readln(p);readln(v);
  writeln(copy(v,1,length(v)-2),
  copy(y,6*(7-pos(p[1],' yt v n'))+pos(v[length(v)-1],y),pos(p[length(p)],'u s')+1));
END.

Explicación (In Spanish for the -30 bonus since you asked)

el primer copy extrae la raíz del verbo, teniendo como parámetros el string, el indice para empezar (en este caso 1) y la cantidad de letras (en este caso length-2.) El segundo extrae su desinencia.

6*(7-pos(p[1],' yt v n') se evalúa según la primera letra del pronombre. Si el pronombre es él/ella(o/s) o usted(es),pos se evalúa a cero, así que el valor dentro de los paréntesis es 7. pos(v[length(v)-1],y busca la penúltima letra del infinitivo en amosemosimos así que avanza 4 por cada tipo de verbo, formando un ciclo de 12. El resto de y consiste en todas las desinencias. Se ha logrado intercalar parcialmente las desinencias para "tu" y "yo." Sin embargo queda cierta cantidad de espacio en blanco que me gustaría eliminar. Así se define el indice para buscar la desinencia en y.

pos(p[length(p)],'u s')+1) determina el numero de caracteres para imprimir. si el pronombre no termina en s o u solo se imprime un cáracter. De esta manera suprimimos la segunda letra de an en en en el caso de un pronombre de tercera persona singular: él, ella, usted.

Output

enter image description here

Level River St

Posted 2014-03-14T15:38:41.317

Reputation: 22 049

1

perl, 155 chars

Just a bunch of regular expressions this time. You can get shorter code by rearranging things slightly so that the pronoun comes after the verb, since we only really care about the end of the verb:

$_=<>;s/(.+) (.*)(.)r/$2$3 $1/;s/. yo/o/||s/ tú/s/||s/ n.*/mos/||s/ v.*/is/||s/ .*s$/n/||s/ .*//;s/i(n?)$/e$1/;s/ais$/áis/;s/eis$/éis/;s/iis$/ís/;print

Seems like the above is currently the winner of code that ignores the bonus.

ski@anito:~$ c='$_=<>;s/(.+) (.*)(.)r/$2$3 $1/;s/. yo/o/||s/ tú/s/||s/ n.*/mos/||s/ v.*/is/||s/ .*s$/n/||s/ .*$//;s/i(n?)$/e$1/;s/ais$/áis/;s/eis$/éis/;s/iis$/ís/;print'; for p in yo tú él ella usted ellos ellas ustedes vosotros nosotros ; do for v in mar mer mir ; do echo "$p $v" | perl -e "$c" ; done ; done ; echo -n "$c" | wc -c
mo
mo
mo
mas
mes
mis
ma
me
me
ma
me
me
ma
me
me
man
men
men
man
men
men
man
men
men
máis
méis
mís
mamos
memos
mimos
155

skibrianski

Posted 2014-03-14T15:38:41.317

Reputation: 1 197

1

perl, 243 chars

This time focusing on hash lookup. I'm fairly surprised I couldn't get this smaller.

$_=<>;s/^(ustede|ell[oa])s\b/x/;s/^(él|ella|usted)\b/w/;%t=(yo,[o,o,o],"tú",[es,as,es],w,[e,a,e],x,[en,an,en],nosotros,[imos,amos,emos],vosotros,[qw(ís áis éis)]);@t=keys%t;$"="|";s/^(@t)\s+(\S*)([aei])r$/$2.$t{$1}[ord($3)%3]/e||die;print

And if input validation isn't important, 186 chars:

$_=<>;s/^[ue].*s /x /;s/^[éeu].* /w /;%_=(y=>[o,o,o],t,[es,as,es],w,[e,a,e],x,[en,an,en],n,[imos,amos,emos],v,[qw(ís áis éis)]);s/^(.)\S*\s+(.*)([aei])r$/$2.$_{$1}[ord($3)%3]/e;print

skibrianski

Posted 2014-03-14T15:38:41.317

Reputation: 1 197

Is this an improved answer to your last answer? – nrubin29 – 2014-03-19T01:11:16.903

I posted 3 different answers with 3 different methods. The best by char count is the regular expression one. – skibrianski – 2014-03-19T01:42:27.430

Got it. Thanks for the submissions! – nrubin29 – 2014-03-19T11:07:15.557

1

Bash, 301 309 (bugfix) 307 299 including new lines

Not great compared to the other ones out there. Could be improved.

It exploits some convenient coincidences.

The bugfix relies on no Spanish verb having "ii" anywhere, due to the way it saves characters when handling vosotros with -ir verbs. Please correct me if that's wrong.

Assumes valid input: first argument is the lower case pronoun, with any necessary accents; second argument is the infinitive of the verb. No stem changes implemented. Outputs the conjugated verb, in lower case, without accents.

e=`tail -c3<<<$2`
f=`echo ${e:0:-1}`
s=`echo ${2:0:-2}`
if [ $1 = yo ];then o="$s"o;elif [ $1 = nosotros ];then o="$s$f"mos;elif [ $1 = vosotros ];then o="$s$f"is;else
if [ $f = i ];then f=e;fi
if [ $1 = tú ];then
o="$s$f"s;elif [ `tail -c2<<<$1` = s ];then
o="$s$f"n;else o=$s$f;fi
fi
tr -s i<<<$o

Explained. ` ` is an obscure notation for $( ), saving one char.

e=`tail -c3<<<$2`

get the verb ending

f=`echo ${e:0:-1}`

get the first char of the verb ending

s=`echo ${2:0:-2}`

get the verb stem

if [ $1 = yo ]; then
o="$s"o;

Verb stem+o. $o is our output

elif [ $1 = nosotros ]; then
o="$s$f"mos;

take stem+first letter of ending+mos

elif [ $1 = vosotros ]; then
o="$s$f"is;

stem+first letter of ending+is (no accents)

else
if [ $f = i ];then f=e;fi

in all scenarios except the two above, -ir verbs behave as -er verbs. change $f to e if it is i.

if [ $1 = tú ]; then
o="$s$f"s;

stem+$f+s

elif [ `tail -c2<<<$1` = s ]; then 

if the last letter of the ending is s. this includes ellos, ellas, ustedes which all have the same endings. how convenient.

o="$s$f"n;

stem+$f+n

else o=$s$f;fi

we are assuming valid input, so the only other possibilities are Él, Ella and Usted, all with the same endings

fi
tr -s i <<< $0

print output, removing double i's (which appear when you use vosotros with an ir verb)

user16402

Posted 2014-03-14T15:38:41.317

Reputation:

0

perl, 298 characters

$_=<>;($p,$b,$x)=/^\s*(yo|tú|él|ellas?|ellos|usted|ustedes|[nv]osotros)\s+(\S*)([aei])r\s*$/;sub r{($z,$y)=@_;return if$p!~/^($z)/;if($p!~/ros$/){$x="e" if$x eq"i"}$x=""if$z eq yo;$x={qw(a áis e éis i ís)}->{$x}if$p=~/^v/;print"$b$x$y";exit}r yo,o;r t,"s";r"[eu].+s",n;r"[éeu]","";r n,mos;r v

or if we can throw caution to the wind and assume valid input, 246 chars:

$_=<>;($p,$b,$x)=/^(\S+)\s+(\S*)([aei])r$/;sub r{($z,$y)=@_;return if$p!~/^($z)/;if($p!~/ros$/){$x="e" if$x eq"i"}$x=""if$z eq yo;$x={qw(a áis e éis i ís)}->{$x}if$p=~/^v/;print"$b$x$y";exit}r yo,o;r t,"s";r"[eu].+s",n;r"[éeu]","";r n,mos;r v

test output:

ski@anito:~$ c='$_=<>;($p,$b,$x)=/^(\S+)\s+(\S*)([aei])r$/;sub r{($z,$y)=@_;return if$p!~/^($z)/;if($p!~/ros$/){$x="e" if$x eq"i"}$x=""if$z eq yo;$x={qw(a áis e éis i ís)}->{$x}if$p=~/^v/;print"$b$x$y";exit}r yo,o;r t,"s";r"[eu].+s",n;r"[éeu]","";r n,mos;r v'; for p in yo tú él ella usted ellos ellas ustedes vosotros nosotros ; do for v in mar mer mir ; do echo "$p $v" | perl -le "$c" ; done ; done ; echo -n "$c" | wc -c
mo
mo
mo
mas
mes
mes
ma
me
me
ma
me
me
ma
me
me
man
men
men
man
men
men
man
men
men
máis
méis
mís
mamos
memos
mimos
246

skibrianski

Posted 2014-03-14T15:38:41.317

Reputation: 1 197

I think it would be ok to assume valid input, but I didn't state that before. What do you guys think? – nrubin29 – 2014-03-18T19:20:34.613

@nrubin29 If you didn't state we had to handle invalid input, then we assume we don't have to handle it. (It would have been best to state explicitly in the question that we didn't have to handle it though.) If we did have to handle it, you would have to specify how. This is code golf, virtually all answers here can be broken with invalid input. Also Rusher and I discussed whether it was necessary to parse the whole pronoun in the comments on the question (He deleted his part, but mine is still there.) BTW, you absolutely made the right decision saying that we didn't have to handle accents. – Level River St – 2014-03-19T19:30:32.323

I'll add to the guidelines that valid input can be assumed as long as that doesn't count as "changing the rules". Don't want to anger anyone anymore. Also, when do I accept an answer? After a week? – nrubin29 – 2014-03-20T02:23:53.673

-1

Java – Too Long

I'm not even going to bother counting. If anyone would like to better golf this, please do. I'll eventually implement the stem-changing challenge.

public class Conjugator {

    public static void main(String[] args) {
        setup();
        String p = args[0].toLowerCase(), v = args[1]; 
        String e = v.substring(v.length() - 2);
        v = v.substring(0, v.length() - 2);
        String f = data.get(e).get(p);
        System.out.println(v + f);
    }

    static HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>();

    public static void add(String ending, String pronoun, String fin) {
        HashMap<String, String> hm = data.get(ending);
        if (hm == null) {
            hm = new HashMap<String, String>();
            hm.put(pronoun, fin);
            data.put(ending, hm);
            return;
        }
        hm = data.get(ending);
        hm.put(pronoun, fin);
    }

    public static void setup() {
        add("ar", "yo", "o");
        add("ar", "tu", "as");
        add("ar", "el/ella/usted", "a");
        add("ar", "nosotros", "amos");
        add("ar", "vosotros", "ais");
        add("ar", "ellos/ellas/ustedes", "an");

        add("er", "yo", "o");
        add("er", "tu", "es");
        add("er", "el/ella/usted", "e");
        add("er", "nosotros", "emos");
        add("er", "vosotros", "eis");
        add("er", "ellos/ellas/ustedes", "en");

        add("ir", "yo", "o");
        add("ir", "tu", "es");
        add("ir", "el/ella/usted", "e");
        add("ir", "nosotros", "imos");
        add("ir", "vosotros", "is");
        add("ir", "ellos/ellas/ustedes", "en");
    }
}

nrubin29

Posted 2014-03-14T15:38:41.317

Reputation: 225