Code Wars Python Challenge: Vowel Count
codewithmarky·@themarkymark·
0.000 HBDCode Wars Python Challenge: Vowel Count
 I haven't done a Code Wars challenge in a little bit, so I logged in and grabbed my next challenge. https://i.imgur.com/w6kVqWS.png This one looks pretty easy, but let's walk through it. Our starting code looks like this: https://i.imgur.com/pWq82CE.png We are given a few example tests, but the solution will be run through more random tests as well. https://i.imgur.com/XNfgafP.png As always, let's identify the problems we need to solve. * Process each character of the input string * Count each occurrence of any vowel outside of Y * Return count Seeing as I don't know any built-in that understands vowels, we are going to need to make our own collection. Let's use a set. https://i.imgur.com/1EOEbQp.png Using a set allows us to specify our collection and ignore Y easily. We are going to next iterate through each value of the string. Let's do that with a for loop. https://i.imgur.com/qWnwBm9.png Let's test this, as this looks like a complete solution. https://i.imgur.com/ajSnti4.png All tests pass! There is a lot of code here for such a simple problem, if you remember my previous lessons we had some more python ways to handle this sort of problem. I also don't think we need a counter variable. Let's refactor! We can eliminate half the code by using a **list comprehension**. https://i.imgur.com/hnFpU9Q.png https://i.imgur.com/sHQXj9Z.png This is much cleaner, and passes all test. But we can do better. https://i.imgur.com/akHKajJ.png Let's remove the counter variable and just return directly. This cuts our solution down to 2 lines of code. This is likely as succinct as you can get for this problem, but I want to bring up one caveat. While returning the count directly we have eliminated most of the useless code, we do open ourselves to one problem. I'll tell you about that in a second, let's submit this and compare to other solutions first. https://i.imgur.com/yV5tcMy.png Complete series of tests pass, we have a good solution. https://i.imgur.com/f5Sidtq.png There is always someone smarter and more clever. The top solution is a single line of code. I am not convinced it is better though. It is a little harder to read, and not as obvious, but still good code. I'm happy with our solution and that's the way I would do it even after reviewing "better" solutions. Now earlier I mentioned we have a caveat with our solution. Namely the fact we performed an action and directly returned it. While this is good a lot of the time, keep in mind in real world coding you likely want to do some validation on your output before returning it. In this case the code is pretty simple and trust worthy, many cases you will want to validate prior to using return. Keep that in mind when coding, ask yourself is this output sanitized, does it need error handling, are there scenarios this may fail? This probing questions will help you find bugs before they become bugs. Hope you enjoy this lesson, if you like this series let me know in the comments. --- <center>Securely chat with me on [Keybase](https://keybase.io/officialmarky) <center>https://images.hive.blog/0x0/https://steemitimages.com/DQmcWxV1dpA1eAtw2ipwZiWZkydyVNU5LaLa2Ak1GUnbGmS/The-Marky-Mark.png </center> # <center> [Why you should vote me as witness](https://peakd.com/witness-category/@themarkymark/why-you-should-vote-for-themarkymark-as-witness) </center> # [](https://hivesigner.com/sign/account-witness-vote?witness=themarkymark&approve=1)
👍 stmdev, tonimontana, coredump, stemd, tonimontana.neo, toni.pal, ferrate, limka, joseph1956, ikrahch, elkaos, khalpal, onestop, moeenali, olivier.jacobs, jtk1, noobster, eliassamuel, jk6276, mango-ag, shadowspub, silviathomson, dalz4, spinvest-leo, babytarazkp, julesquirin, abh12345.stem, laissez-faire, cd-stem, potplucker, enolife, crypticat, senseiphil, arctis, malenavargas, merlin7, solikyl, saraidiaz, dfacademy, manoldonchev, techslut, onealfa, ydavgonzalez, yoshiko, nichemarket, c4cristi3, jk6276.life, tinycurator, sepracore, glastar, dine77, roleerob, jphamer1, ctime, scaredycatguide, joele, g4fun, xyz004, tipsybosphorus, revisesociology, therealwolf, belen0949, ronavel, roomservice, smartsteem, whiterosecoffee, bilpcoinrecords, hiveonboard, tombstone, epicdice, star.lord, ronaldoavelino, mirkon86, dalz, anacristinasilva, chrismadcboy2016, jemmanuel, nautilus-up, tarazkp, nokodemion, kekos, dfacademy-pal, daath, moneytron, cpt-sparrow, sfr-treasury, iamjohn, rem-steem, asmr.tist, stevescoins, prettynicevideo, mercurial9, frankydoodle, blockbeard, bruneo, bala41288, marlians.token, borran, notconvinced, danielsaori, captainbob, netaterra, justinashby, thrasher666, monsterjamgold, garlet, shanghaipreneur, therealyme, baneenabear, peekbit, oakshieldholding, alphacore, mikepm74, enforcer48, blind-spot, brutoken, solcycler, crypto-gamer, rubencress, rehan-pal, priyanarc, hitmeasap, offgridlife, jongolson, broxi, alphahippie, recoveryinc, jaybird, hive-101493, elbrava, ericburgoyne, movement19, diabonua, szf, urtrailer, liz.writes, alexis555, jlsplatts, howiemac, foodfightfriday, kuku-splatts, themightysquid, tigerrkg, banvie, splatts, w-splatts, blewitt, likwid, suonghuynh, smartvote, gmlrecordz, nuthman, ioioioioi, fourfourfun, promobot, schlunior, mark-waser, digital-wisdom, ethical-ai, jwaser, herpetologyguy, morgan.waser, strong-ai, technoprogressiv, freebornsociety, yeaho, bozz, raorac, yaraha, wallvater, tmps, mvanhauten, vibrasphere, discohedge, edgarsart, bwaser, ellepdub, goblinknackers, dyrt88, magicmonk, otom, bronkong, cervisia, bynarikode, mys, kayoko, faustofraser, mawit07, cryptoandcoffee, conectionbot, steemfriends, fucanglong, logicforce, beleg, ecotone, julian2013, a-bot, offoodandart, whd, leilafrangie, hooiyewlim, philnewton, paragism, solominer, babschnae, src3, theywillkillyou, homeginkit, tubcat, viruk, smon-joa, denizcakmak, drorion, debtfreein2, angel33, arlettemsalase, enjar, d0zer, cst90, steem-tube, lorentm, dying, gingerbyna, properfraction, sugandhaseth, nfaith, wolffeys, the4thmusketeer, pal-isaria, steemychicken1, lovenfreedom, deniskj, fjcalduch, garybilbao, altonos, schlees, crimo, parauri, stemisaria, hungryhustle, roberto58, steemusa, uwelang, bigtom13, ljquimpo, ciuoto, espoem, coccodema, thenightflier, steempostitalia, heidi71, zaragast, marcolino76, cooperfelix, ma1neevent, engrsayful, blainjones, mahyulmaulana, we-are-palcoin, teamashen, tadstrange, holovision, alinakot, maxpatternman, keepinitsteem, rcshad0w, sonius94, iamtom, gerusan, smartmeme, tinyhousecryptos, calimeatwagon, i-c-e, tiffany4ever, yestermorrow, hyborian-strain, reinhard-schmid, letsplaywhatelse, emitste, vaansteam, leslierevales, necio, nathen007, retard-gamer-de, payroll, drew0, acromott, commonlaw, idig, steemcenterwiki, jkramer, yulem, mrnightmare89, suntree, bitcome, mrnightmare.net, axeman, obsesija, tijntje, ohmygoodness, gannibal, hive-108278, davinsh, cryptogee, ironhieronymus, thatterrioguy, jordangerder, seikatsumkt, spederson, hivewatchers, logic, light-hearted, anyx, kushed, complexring, aizensou, b0y2k, stoner19, sock, josephcraig289, igl00, hagie, coinbar, platinum-blue, steemizen, bigdaddy, kingsmind, pboc, romedog, spg, sammosk, dream-o, tushy, bilpcoinbpc, tdogvoid, razvanelulmarin, fabio, shawnamawna, caesarion, thebluepanda, thisisbenbrick, einsteinpotsdam, tejma, allesgruen, dannystravels, jerryblanceton, ssekulji, timbernana, sherlockcupid, dougkarr, dark.horse, toyman, i-gordan, buzzbeergeek, sunshinetraveler, biancajapan, horsepower, teneiced, sumayyahsaidso, teslaman, blondephysics, magictoni, luminaryhmo, amos811, steemcleaners, ahlawat, almi, c0wtschpotato, davidlionfish, mountaingod, rehan.neox, louisthomas, yggdrasil.laguna, iktisat, marcoteixeira, vikisecrets, abbenay, vabadaba, melbourneswest, riverflows, admiralbot, aninsidejob, memehub, steemflagrewards, munir12, asgarth, tazi, ibelin, marryiv, gank, xves, dickturpin, jesusmedit, colorcareer, alexbalan, jjdowie, sbi5, sbi-tokens, jlufer, koxmicart, cryptoknight12, dpend.active, sweet-memory, sketching, konda, jingdol, gudnius.comics, psyshock, sabari18, cryptycoon, dunkman, steemik, lucky-guy, elenasteem, andre-verbrick, kharma.scribbles, ykroys, dayerlis, brianbrogan1960, gitplait, tykee, kamchore, pal.alfa, santigs, giuatt07, chireerocks, mrs.goldkey, sultan-indo, zorg67, astil.codex, ilias.fragment, we-are, brofund-pal, craigcryptoking, richman, salty-mcgriddles, goldkey, goldvault, silverkey, imcharming, kingscrown, kingturd, silvervault, cryptoclerk, redwarbull, block-power, bullionstackers, inertia, stimialiti, r351574nc3, msp-foundation,