Abbreviate a two word name

Permalink

Cannot retrieve contributors at this time

CodeWars Python Solutions


Abbreviate a Two Word Name

Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

Sam Harris => S.H

Patrick Feeney => P.F


Given Code

def abbrevName(name):
    pass

Solution

def abbrevName(name):
    return ".".join([w[0].upper() for w in name.split()])

See on CodeWars.com

  • Sign Up

    Time to claim your honor

  • Training
  • Practice

    Complete challenging Kata to earn honor and ranks. Re-train to hone technique

  • Freestyle Sparring

    Take turns remixing and refactoring others code through Kumite

  • Career
  • Opportunities

    Find your next career challenge – powered by Qualified Jobs

  • Community
  • Leaderboards

    Achieve honor and move up the global leaderboards

  • Chat

    Join our Discord server and chat with your fellow code warriors

  • Discussions

    View our Github Discussions board to discuss general Codewars topics

  • About
  • Docs

    Learn about all of the different aspects of Codewars

Abbreviate a Two Word Name

  • Details
  • Solutions
  • Discourse (277)

Description:

Loading description…

Similar Kata:

More By Author:

Check out these other kata created by samjam48

Stats:

Created Sep 27, 2016
Published Sep 27, 2016
Warriors Trained 163030
Total Skips 8178
Total Code Submissions 365883
Total Times Completed 119031
JavaScript Completions 52085
C# Completions 5667
Ruby Completions 3133
Python Completions 35813
NASM Completions 46
Java Completions 11587
Rust Completions 1295
C++ Completions 3737
PHP Completions 2691
Haskell Completions 641
TypeScript Completions 1583
Go Completions 2159
PureScript Completions 20
Factor Completions 19
CoffeeScript Completions 7
Crystal Completions 15
Julia Completions 41
R Completions 91
Kotlin Completions 627
C Completions 740
COBOL Completions 10
D Completions 4
RISC-V Completions 10
OCaml Completions 23
Scala Completions 65
Total Stars 1034
% of votes with a positive feedback rating 92% of 10063
Total «Very Satisfied» Votes 8661
Total «Somewhat Satisfied» Votes 1267
Total «Not Satisfied» Votes 135
Total Rank Assessments 11
Average Assessed Rank
Highest Assessed Rank
Lowest Assessed Rank

The challenge

Write a function to convert a name into initials. This challenge strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

Sam Harris => S.H

Patrick Feeney => P.F

The solution in Java

This is a really easy one, basically what we will do is the following:

  1. Convert our name toUpperCase so that we can just pull out the characters we want.
  2. Convert the name String into 2 separate values, stored in a names array.
  3. Return the first character of each, using charAt(0) with a dot inbetween.
public class AbbreviateTwoWords {

  public static String abbrevName(String name) {
    name = name.toUpperCase();
    
    String[] names = name.split(" ");
    
    return names[0].charAt(0)+"."+names[1].charAt(0);
  }
}

Test cases to validate our solutionn

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
 
    @Test
    public void testFixed() {
        assertEquals("S.H", AbbreviateTwoWords.abbrevName("Sam Harris"));
        assertEquals("P.F", AbbreviateTwoWords.abbrevName("Patrick Feenan"));
        assertEquals("E.C", AbbreviateTwoWords.abbrevName("Evan Cole"));
        assertEquals("P.F", AbbreviateTwoWords.abbrevName("P Favuzzi"));
        assertEquals("D.M", AbbreviateTwoWords.abbrevName("David Mendieta"));
        assertEquals("Z.K", AbbreviateTwoWords.abbrevName("Zenon Kapusta"));
        
        assertEquals("G.C", AbbreviateTwoWords.abbrevName("george clooney"));
        assertEquals("M.M", AbbreviateTwoWords.abbrevName("marky mark"));
        assertEquals("E.D", AbbreviateTwoWords.abbrevName("eliza doolittle"));
        assertEquals("R.W", AbbreviateTwoWords.abbrevName("reese witherspoon"));
    }
    
    @Test
    public void testRandom() {
      for(int i = 0; i < 200; i++){
        String testString = makeString();
        assertEquals(randomTest(testString), AbbreviateTwoWords.abbrevName(testString));
      }
    }
    
    private String makeString() {
        return makeWord(1, 20) + " " + makeWord(1, 20);
      }
    
    private String makeWord(int min, int max) {
      String word = "";
      String[] possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
      int length = (int) (Math.random() * max) + min;
    
      for(int i=0; i < length; i++) {
          int index = (int) (Math.random() * possible.length);
          word += possible[index];
      }
    
      return word;
    }
    
    private String randomTest(String name){
      String[] nameSplit = name.toUpperCase().split(" ");
      return nameSplit[0].substring(0, 1) + '.' + nameSplit[1].substring(0, 1);
    }
}

8kyu kata в кодовых направлениях.

Тема Описание:

Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.

The output should be two capital letters with a dot seperating them.

It should look like this:

Sam Harris => S.H

Patrick Feeney => P.F

Получите два слова в сокращенную форму. Форма, как Сэм Харрис -> С.Х.

Очень простая тема.

Код доллара:

public class AbbreviateTwoWords {
  public static String abbrevName(String name) {
    //name = name.toUpperCase();
    //int index = name.indexOf(' ');
    //String ch = name.substring(index+1, index+2);
    //name = name.substring(0, 1).concat(".");
    //name = name.concat(ch);
    name = name.substring(0, 1).concat(".").concat(name.substring(name.indexOf(' ')+1, name.indexOf(' ')+2)).toUpperCase();
    return name;
  }
}

Персональное резюме:

Из простого начните чистящуюся тему, этот вопрос может попробовать регулярные выражения.

I’m writing a function to convert a name into initials. This function return strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should be like this:

alex cross => A.C

jaber ali => J.A

Here is my solution

function initialName(firstLetterFirstName, firstLetterLastName) {
    'use strict'
    let x = firstLetterFirstName.charAt(0).toUpperCase();
    let y = firstLetterLastName.charAt(0).toUpperCase();
    return x + '.' + y;
}

console.log(initialName('momin', 'riyadh'));  // M.R

Have I solved this problem with hardcoded, and my approach is right? or could it be better!

asked May 6, 2020 at 9:56

Momin's user avatar

4

Use regex for that:

function initialName(words) {
    'use strict'
    
    return words
        .replace(/b(w)w+/g, '$1.')
        .replace(/s/g, '')
        .replace(/.$/, '')
        .toUpperCase();
}

console.log(initialName('momin riyadh'));  // M.R
console.log(initialName('momin riyadh ralph')); // M.R.R

answered May 6, 2020 at 10:02

Justinas's user avatar

JustinasJustinas

40.7k5 gold badges65 silver badges95 bronze badges

3

Try this:

name.split(' ').map(el => el[0]).join('.').toUpperCase()

In you case with multiple parts could be like this:

function make(...parts) {
   return parts.map(el => el[0]).join('.').toUpperCase()
}

answered May 6, 2020 at 10:01

Mark  Partola's user avatar

1

You can try this

    var str = "Abdul Basit";
    var str1 = "This is a car";
    console.log(getInitials(str));
    console.log(getInitials(str1));
    
    function getInitials(str) {
      var matches = str.match(/b(w)/g);
      return matches.join('.').toUpperCase();
    }

answered May 6, 2020 at 10:03

Abdul Basit's user avatar

Abdul BasitAbdul Basit

1,3221 gold badge10 silver badges18 bronze badges

It works, but it could be written in a one-liners:

console.log(
  ['john', 'doe']
  .map(word => `${word[0].toUpperCase()}.`).join('')
)

answered May 6, 2020 at 10:00

Nino Filiu's user avatar

Nino FiliuNino Filiu

16k11 gold badges55 silver badges80 bronze badges

Понравилась статья? Поделить с друзьями:
  • Abap excel to sap
  • Abap alv to excel
  • A в excel для расчета матрицы
  • A wow word for good
  • A word скачать приложение полная версия