In today's challenge, you are asked to replace every letter with its position in the alphabet for a given string where 'a' = 1, 'b'= 2, etc.
For example:
alphabet_position("The sunset sets at twelve o' clock.")should return20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11as a string.
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
This challenge comes from MysteriousMagenta on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Latest comments (34)
Python
Here is the simple solution with PHP:
Python :
[gist.github.com/devparkk/d46fd8763...]
C#
A tiny python solutiuon:
a bit late but here's the answer anyway... in PHP
solved in rust made with tests first :)
One line Javascript
Haskell
Some function composition sorcery in Haskell.
Explanation
The
.operator composes functions, so they will be applied from right to left.filter isLetterwill remove all characters that are not letters from the string.map (show . (flip (-)) 64 . ord . toUpper)Transforms each character to its position in the alphabet.toUppertransforms the character to uppercase, so that we can substract 64 from it's code to know the position.ordmaps a character to its ASCII code.(flip (-) 64)subtracts 64 from the character code. Since the code for'A'is 65, this will give us the position in the alphabet starting at index 1. The way it works is it partially applies the second argument of the subtract operator to 64, i.e., this is equivalent to(\x -> x - 64)but fancier.showmaps any type deriving fromShow(Intin this case) toString.unwordsjoins a list of strings using space as a separator.