DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #47 - Alphabets

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 return 20 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 11 as 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)

Collapse
 
matrossuch profile image
Mat-R-Such

Python

import string
def alphabet_position(text):
    text = [i for i in text.replace(' ','').lower() if i.isalpha() ]
    position = [str(string.ascii_lowercase.find(i)+1) for i in text ]
    return ' '.join(position)
Collapse
 
peter279k profile image
peter279k

Here is the simple solution with PHP:

function alphabet_position(string $s): string {
    $s = strtoupper($s);
    $alphabetNums = range(65, 90);
    $alphabets = [];

    foreach ($alphabetNums as $chr) {
        $aphabets[] = chr($chr);
    }

    $result = "";

    $index = 0;
    for (; $index < strlen($s); $index++) {
        if (in_array($s[$index], $aphabets) === false) {
            continue;
        }

        $result .= (string)(ord($s[$index]) - 64) . " ";
    }

    return substr($result, 0, -1);
}
Collapse
 
hectorpascual profile image
Héctor Pascual

Python :

lambda s : ' '.join([str(ord(c)-ord('a')+1) for c in s.lower() if re.search('[a-z]',c)])
Collapse
 
devparkk profile image
Dev Prakash
Collapse
 
sonugan profile image
sonugan

C#

public static string AlphabetPosition(string text)
{
   return string.Join(" ", text
    .ToLower()
    .Where(c => char.IsLetter(c))
    .Select(c => (c - 'a') + 1)
    .ToList());
}
Collapse
 
b2aff6009 profile image
b2aff6009

A tiny python solutiuon:

def alphabet_position(text):
    converted = [str(ord(c) - ord('a') + 1) for c in text.lower() if c >= 'a']
    return " ".join(converted)
Collapse
 
celyes profile image
Ilyes Chouia • Edited

a bit late but here's the answer anyway... in PHP

function alphabet_position($text){
    $alphabet = range('a', 'z');     
    $strippedText = str_split(strtolower(preg_replace("/[^a-zA-Z]/", "", $text)));   
    $result = "";
    foreach($strippedText as $letter){
        $result .= array_search($letter, $alphabet)+1 . " ";   
    }
    return $result;
}
echo alphabet_position("The sunset sets at twelve o' clock.");
Collapse
 
5422m4n profile image
Sven Kanoldt

solved in rust made with tests first :)

pub fn alphabet_position(s: &str) -> String {
  s.to_lowercase()
    .chars()
    .filter(|x| x.is_alphabetic())
    .map(|x| -> u8 { x as u8 - 'a' as u8 + 1 })
    .map(|x| -> String { x.to_string() })
    .collect::<Vec<String>>()
    .join(" ")
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn it_should_relace_the_a_with_1() {
    let replaced = alphabet_position("a");
    assert_eq!(replaced, "1");
  }

  #[test]
  fn it_should_relace_the_capital_a_with_1() {
    let replaced = alphabet_position("A");
    assert_eq!(replaced, "1");
  }

  #[test]
  fn it_should_ignore_non_characters() {
    let replaced = alphabet_position("'a a. 2");
    assert_eq!(replaced, "1 1");
  }

  #[test]
  fn it_should_relace_the_sentence() {
    let replaced = alphabet_position("The sunset sets at twelve o' clock.");
    assert_eq!(
      replaced,
      "20 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 11"
    );
  }
}
Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

One line Javascript

const alphaPosition = str => [...str]
  .filter(letter => /[a-zA-Z]/.test(letter))
  .map(letter => letter.toLowerCase().charCodeAt(0) - 96)
  .join(' ')
Collapse
 
avalander profile image
Avalander

Haskell

Some function composition sorcery in Haskell.

import Data.Char (isLetter, toUpper, ord)

alphabet_position :: String -> String
alphabet_position = unwords . map (show . (flip (-)) 64 . ord . toUpper) . filter isLetter

Explanation

The . operator composes functions, so they will be applied from right to left.

  1. filter isLetter will remove all characters that are not letters from the string.
  2. map (show . (flip (-)) 64 . ord . toUpper) Transforms each character to its position in the alphabet.
    1. toUpper transforms the character to uppercase, so that we can substract 64 from it's code to know the position.
    2. ord maps a character to its ASCII code.
    3. (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.
    4. show maps any type deriving from Show (Int in this case) to String.
  3. unwords joins a list of strings using space as a separator.