10
\$\begingroup\$

Inspired by the Codewars Kata.

Your goal is to take an input string such as this one:

"'Twas a dark and stormy night..."

and return a string containing the position of each character in the alphabet, separated by spaces and ignoring non-alphabetical characters, like this:

"20 23 1 19 1 4 1 18 11 1 14 4 19 20 15 18 13 25 14 9 7 8 20"

For an additional challenge, you can replace any numerical characters in the original string with themselves + 27. For example, "25" would become "29, 32". This is completely optional.

You must use 1-indexing ('a'==1, 'b'==2, etc)

Additional rules:

  • You must return a string, not an array.

  • Trailing whitespace is OK.

The winner has the lowest byte count.

Good luck!

\$\endgroup\$
  • \$\begingroup\$ closely related \$\endgroup\$ – Giuseppe May 31 '18 at 9:14
  • 5
    \$\begingroup\$ @TheoC Why? The general consensus is that answers should be able to output in any reasonable format, as it may add too much bloat and make it unfair to languages who can join by spaces in a shorter way. \$\endgroup\$ – Okx May 31 '18 at 9:42
  • 1
    \$\begingroup\$ @TheoC Why don't you just allow both? \$\endgroup\$ – Okx May 31 '18 at 9:54
  • 3
    \$\begingroup\$ Welcome to PPCG! This is a decent challenge overall, but for next time you post a challenge, here are some things to keep in mind. 1) This challenge is pretty simple. I think it would be more interesting if the optional part was mandatory (note, don't change that part now, it's too late). 2) You're pretty restrictive about some arbitrary parts. Why not allow an array? It's our standards than an array of characters is a string. I would recommend reading through this thread for ideas. \$\endgroup\$ – DJMcMayhem May 31 '18 at 16:37
  • 2
    \$\begingroup\$ Future notes: 1 and 0 indexing are usually one and the same, and both are usually allowed. Also, constraining output formats is frowned upon. If it's a list of values let the language decide the format. The challenge isn't about formatting output nor is it about shifting indices. Therefore, it shouldn't be a constraint when you could just allow languages to do what they'd do naturally and focus on the challenge intent. \$\endgroup\$ – Magic Octopus Urn May 31 '18 at 21:17

38 Answers 38

5
\$\begingroup\$

05AB1E, (5?) 7 bytes

Rightmost two bytes are output formatting

áÇ32%ðý

A port of my Jelly answer, but O5AB1E is more terse for the alphabet filtering.

Try it online!

How?

áÇ32%ðý - take input implicitly
á       - filter keep alphabetical characters
 Ç      - to ordinals
  32    - thirty-two
    %   - modulo (vectorises)
     ð  - push a space character
      ý - join
\$\endgroup\$
  • \$\begingroup\$ Since OP want it to be printed split by spaces, a trailing ðý can be added. But since halve of the answers output lists I guess just leave it for now. \$\endgroup\$ – Kevin Cruijssen May 31 '18 at 11:50
  • \$\begingroup\$ Ah. I have missed it in my answers... \$\endgroup\$ – Jonathan Allan May 31 '18 at 11:59
5
\$\begingroup\$

Java 8, 82 78 72 69 62 bytes

s->{for(int c:s)System.out.print(c>64&~-c%32<26?c%32+" ":"");}

-13 bytes thanks to @OlivierGrégoire.

Try it online.

Explanation:

s->                    // Method with character-array parameter and no return-type
  for(int c:s)         //  Loop over its characters as integers
    System.out.print(  //   Print:
     c>64&~-c%32<26?   //    If the current character is a letter:
      c%32+" "         //     Print the position in the alphabet with a trailing space
     :                 //    Else:
      "");}            //     Print nothing
\$\endgroup\$
  • 1
    \$\begingroup\$ s->s.chars().forEach(c->{if(c>64&~-c%32<26)System.out.print(c%32+" ");}) (72bytes). \$\endgroup\$ – Olivier Grégoire May 31 '18 at 15:01
  • 1
    \$\begingroup\$ @OlivierGrégoire Thanks! And -3 more bytes by changing it to a ternary if. :) \$\endgroup\$ – Kevin Cruijssen May 31 '18 at 15:08
  • \$\begingroup\$ s->{for(int c:s)System.out.print(c>64&~-c%32<26?c%32+" ":"");} (62 bytes) using a char[] as input instead of a String. \$\endgroup\$ – Olivier Grégoire Jun 1 '18 at 12:36
4
\$\begingroup\$

Python 3, 62 60 49 bytes

-5 bytes thanks to Jo King.
-8 bytes thanks to pLOPeGG.

After these improvements, this answer is now similar to Jonathan Allan's answer.

print(*[ord(c)%32for c in input()if c.isalpha()])

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Oh, I guess %32 works as well \$\endgroup\$ – Jo King May 31 '18 at 12:00
4
\$\begingroup\$

R, 55 50 bytes

cat(utf8ToInt(gsub("[^A-Za-z]","",scan(,"")))%%32)

Try it online!

Reads input from stdin, converts to uppercase, removes non-uppercase alphabetic letters, converts to code points, subtracts to 64 mods by 32, and prints to stdout, separated by spaces.

Thanks to Kevin Cruijssen for the golf!

\$\endgroup\$
  • \$\begingroup\$ 50 bytes \$\endgroup\$ – Kevin Cruijssen May 31 '18 at 12:06
  • \$\begingroup\$ @KevinCruijssen * facepalm * duh \$\endgroup\$ – Giuseppe May 31 '18 at 14:22
  • \$\begingroup\$ I have added two comments(questions) to the question - depending on the answer there is an opportunity to golf this down to 46 or even 39 chars. \$\endgroup\$ – JayCe May 31 '18 at 17:07
  • 1
    \$\begingroup\$ You can do 47 by using [^A-z] \$\endgroup\$ – MickyT May 31 '18 at 21:39
4
\$\begingroup\$

APL (Dyalog Unicode), 24, 20, 14 13 bytes

-4 bytes thanks to Zacharý (and Mr. Xcoder)!

-6 bytes thanks to Adám!

-1 byte thanks to ngn!

⎕A⍳⎕A∩⍨≡819⌶⊢

Try it online!

Explanation:

        ≡819⌶⊢  - to uppercase
   ⎕A∩⍨         - intersect with the letters A-Z (args swapped to preserve the order)
   ⍳              - index in
⎕A               - the A-Z letters list

My initial solution:

APL (Dyalog Unicode), 24 20 bytes

{⍵/⍨27>⍵}⎕A⍳1(819⌶)⊢

Try it online!

Explanation:

             ⍳           indices of     
              1(819⌶)⊢  the right argument (⊢) changed to uppercase
          ⎕A            in the list of uppercase letters
{⍵/⍨     }              copy (filter) those items from the list of indeces
     27>⍵               which are smaller than 27 (all non A-Z chars will have index 27)

Don't laugh at me, I'm new to APL :)

\$\endgroup\$
  • 1
    \$\begingroup\$ That's actually remarkably good for someone new to APL! You don't need the parentheses, they're assumed. Also,{1(819⌶)⍵} can be 1(819⌶)⊢. Otherwise, amazing job! Hope you enjoy APL in the future! \$\endgroup\$ – Zacharý May 31 '18 at 15:01
  • \$\begingroup\$ @Zacharý Thanks! I hope so (I have some knowledge in J , I'm not totally new into array languages) \$\endgroup\$ – Galen Ivanov May 31 '18 at 15:25
  • 1
    \$\begingroup\$ As Zachary noted, the parentheses are assumed, so you needn't include them into the byte count, resulting in 20 bytes. \$\endgroup\$ – Mr. Xcoder May 31 '18 at 15:33
  • 1
    \$\begingroup\$ @Jonah I added an explanation. You're right, capitalizing and the alphabet itself cost much more in J. \$\endgroup\$ – Galen Ivanov Jun 1 '18 at 6:25
  • 1
    \$\begingroup\$ Nice job! You can save a byte by composing the 1 to the 819⌶ and save five by removing 27s directly: 27~⍨⎕A⍳819⌶⍨∘1; or take the intersection with the alphabet: ⎕A⍳⎕A∩⍨819⌶⍨∘1 \$\endgroup\$ – Adám Jun 1 '18 at 12:57
3
\$\begingroup\$

Python 2, (45?) 55 bytes

11 bytes added to format the output, which also makes this incompatible with Python 3)

lambda s:' '.join(`ord(c)%32`for c in s if c.isalpha())

Another port of my Jelly answer.

Try it online!


Non-formatted version (returning a list of integers):

lambda s:[ord(c)%32for c in s if c.isalpha()]
\$\endgroup\$
  • 1
    \$\begingroup\$ It looks like OP is insisting on string output separated by spaces, unfortunately \$\endgroup\$ – Sok May 31 '18 at 11:32
  • 1
    \$\begingroup\$ Yep - I missed that on all my answers - one becomes so accustomed to the norms of the site! \$\endgroup\$ – Jonathan Allan May 31 '18 at 12:07
3
\$\begingroup\$

JavaScript (Node.js), 69 55 54 bytes

t=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join` `

Try it online!

Explanation :

t =>                       // lambda function accepting a string as input
    t.match(/a-z/gi).      // returns all parts of string that match as an array 
        map(i=>            // map over that array with argument i 
            parseInt(i,36) // convert to base 36 
                - 9        // and subtract 9 from it
        ).                 // end map
        join` `            // convert to space separated string

11 bytes saved thanks to @Kevin

1 more bytes thanks to @Neil


You can add support for numericals for some additional bytes (thanks to @neil)

JavaScript (Node.js), 62 bytes

t=>t.match(/[^_\W]/g).map(i=>(parseInt(i,36)+26)%36+1).join` `

Try it online!

\$\endgroup\$
  • \$\begingroup\$ -11 bytes by changing a-z to A-Za-z and i.toLowerCase().charCodeAt()-96 to i.charCodeAt()%32 \$\endgroup\$ – Kevin Cruijssen May 31 '18 at 11:20
  • 1
    \$\begingroup\$ parseInt(i,36)-9 saves another byte. \$\endgroup\$ – Neil May 31 '18 at 12:04
  • \$\begingroup\$ .match(/[^_\W]/g).map(i=>(parseInt(i,36)+26)%36+1) lets you support numbers, not sure if that's the best way though. \$\endgroup\$ – Neil May 31 '18 at 13:49
2
\$\begingroup\$

Jelly, (7?) 8 bytes

Rightmost byte is output formatting

fØẠO%32K

A full program accepting a string in Python format which prints the result to STDOUT

Try it online!

How?

fØẠO%32K - Main Link: list of characters (created from the string input)
 ØẠ      - yield the alphabet = ['A','B',...,'Z','a','b',...,'z']
f        - filter keep (discard non alphabet characters)
   O     - ordinals          ('A':65, 'Z':90, 'a':97, 'z':122, etc.)
     32  - literal thirty-two
    %    - modulo            (65:1,   90':26,  97:1,  122:26,  etc.)
       K - join with spaces (makes a list of characters and integers)
         - implicit print
\$\endgroup\$
2
\$\begingroup\$

Japt v2.0a0 -S, 12 10 bytes

r\L ¨c uH

Try it


Explanation

r              :Remove
 \L            :  Non-letter characters
    ¬          :Split to array
     ®         :Map
      c        :  Character code
        u      :  Modulo
         H     :  32
               :Implicitly join with spaces and output
\$\endgroup\$
2
\$\begingroup\$

x86 opcode, 35 bytes

0080h: AC 3C 24 75 04 88 45 FF C3 0C 20 2C 60 76 F1 D4
0090h: 0A 0D 30 30 86 E0 3C 30 74 01 AA 86 E0 AA B0 20
00a0h: AA EB DD                                       

f:  lodsb
    cmp al, '$'
    jnz @f
        mov [di-1], al
        ret
    @@:
    or al, 32
    sub al, 96
    jbe f
    aam
    or ax, 3030H
    xchg ah, al
    cmp al, 48
    jz @f
        stosb
    @@:
    xchg ah, al
    stosb
    mov al, 32
    stosb
    jmp f

Assuming the result contain at least one letter, and no {|}~

40 bytes, allowing all ASCII chars

0080h: AC 3C 24 75 04 88 45 FF C3 0C 20 2C 60 76 F1 3C
0090h: 1A 77 ED D4 0A 0D 30 30 86 E0 3C 30 74 01 AA 86
00a0h: E0 AA B0 20 AA EB D9                           
\$\endgroup\$
  • \$\begingroup\$ What's "x86 opcode"? Is this just an x86 machine code submission? \$\endgroup\$ – Jakob May 31 '18 at 18:13
  • \$\begingroup\$ @Jakob true. I here don't say ".COM" cuz it's a function and don't rely on ".COM" format \$\endgroup\$ – l4m2 Jun 1 '18 at 0:32
  • \$\begingroup\$ Hmm. Yeah, I think it's assumed that machine code solutions don't have to be complete executables. Might actually be better to just label it "x86 machine code" \$\endgroup\$ – Jakob Jun 1 '18 at 4:36
2
\$\begingroup\$

Stax, 9 10 9 bytes

üpÉÿ%}},√

Run and debug it

-1 byte thanks to @recursive

Explanation:

v{VaIvm0-J Full program, unpacked, implicit input
v          Lowercase
 {    m    Map:
  VaI        Index in lowercase alphabet (0-based, -1 for not found)
     ^       Increment
       0-  Remove zeroes
         J Join by space
           Implicit output

Stax, 7 bytes

É▌Xl»↔"

Run and debug it

This one outputs newline-separated. Unpacked: vmVaI^|c. Similar, but with map, which implicitly outputs with trailing newline.

\$\endgroup\$
  • \$\begingroup\$ Hm. There appears to be a problem packing programs that end in space \$\endgroup\$ – recursive Jun 1 '18 at 14:21
  • \$\begingroup\$ @recursive Oh, didn't notice that (usually I try the links, but apparently I forgot it here). I added a workaround. \$\endgroup\$ – wastl Jun 1 '18 at 14:48
  • \$\begingroup\$ I never noticed this bug either. I'll fix it in the next release of Stax. Existing packed programs will remain unchanged. \$\endgroup\$ – recursive Jun 1 '18 at 15:05
  • \$\begingroup\$ Here's a 9 back for your trouble. \$\endgroup\$ – recursive Jun 1 '18 at 15:09
2
\$\begingroup\$

Whitespace, 152 117 bytes

-35 bytes thanks to @Lynn.

[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate_input][S S S T S S S S S N
_Push_32][T S T T   _Modulo][S N
T   _Swap_top_two][S S S T  T   T   T   T   T   N
_Push_63][T S T S _Integer_divide][T    S S N
_Multiply][S N
S _Duplicate][S S S T   T   S T T   N
_Push_27][S T   S S T   N
_Copy_1st][S S S T  N
_Push_1][T  S S S _Add][T   S T S _Integer_divide][T    S S N
_Mulitply][N
T   S N
_If_0_Jump_to_Label_LOOP][T N
S T _Print_as_number][S S S T   S S S S S N
_Push_32_space][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Start LOOP:
  Character c = STDIN as character
  Integer n = (c modulo-32) * (c integer-divided by 63)
  Integer m = 27 integer-divided by (n + 1) * n;
  If(m == 0):
    Go to next iteration of LOOP
  Else:
    Print n as integer to STDOUT
    Print a space to STDOUT
    Go to next iteration of LOOP
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't have the time to write it in Whitespace, but maybe you could write something like this \$\endgroup\$ – Lynn Jun 23 '18 at 12:15
  • 1
    \$\begingroup\$ Looks like that's 117 bytes! (*I changed 64 to 63 in the code, as it's equivalent but shorter to represent in Whitespace) :) \$\endgroup\$ – Lynn Jun 23 '18 at 14:13
  • \$\begingroup\$ @Lynn Not bad, -35 bytes right there. Thanks. :) \$\endgroup\$ – Kevin Cruijssen Jun 23 '18 at 16:45
1
\$\begingroup\$

05AB1E, 8 bytes

láÇ96-ðý

Try it online!

or, if we can return an array:

05AB1E, 6 bytes

láÇ96-

Explanation:

l         Lowercase
 á        Only letters
  Ç       Codepoints
   96-    Subtract 96.

Try it online!

or if you want it to count numbers:

05AB1E, 13 bytes

lAžh«DŠÃSk>ðý

Try it online!

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 14 bytes

Handles numbers as well

žKÃlvžKlÙyk>ðJ

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 21 bytes

≔⁺β⭆χιβF↧S¿№βι«I⊕⌕βι→

Try it online! Link is to verbose version of code. Explanation:

≔⁺β⭆χιβ

Append the digits to the predefined lowercase letters variable.

F↧S

Loop over the lowercased input.

¿№βι«

If the current character is a letter or digit,

I⊕⌕βι

print its 1-indexed index,

and leave a space for the next value.

\$\endgroup\$
1
\$\begingroup\$

Red, 93 bytes

func[s][a: charset[#"a"-#"z"]parse lowercase s[any[copy c a(prin[-96 + to-char c""])| skip]]]

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I don't know enough about Red, but can #"a"-#"z" be changed to both lower and uppercase letters; and then the lowercase can be removed; and -96 + to-char c can be modulo-32? Not sure if that even saves bytes In Red, though. \$\endgroup\$ – Kevin Cruijssen May 31 '18 at 15:19
  • \$\begingroup\$ @Kevin Cruijssen Thanks, I'll try it later \$\endgroup\$ – Galen Ivanov May 31 '18 at 15:28
  • \$\begingroup\$ @KevinCruijssen parse function collects strings even when the match is a single character, that's why I always need the to-char. For the uppercase letters I would need to add to the charset #"A"-#"Z", which spoils the gain (if any) from eliminating lowercase. \$\endgroup\$ – Galen Ivanov Jun 1 '18 at 6:53
  • \$\begingroup\$ Yeah, I was kinda afraid #"A"-#"Z" might not gain much in comparison to lowercase, since it's only 1 byte shorter. And I knew you'd need the to-char, just wasn't sure if -96 + and modulo-32 would be similar in size. \$\endgroup\$ – Kevin Cruijssen Jun 1 '18 at 6:56
1
\$\begingroup\$

Perl 5, 47 bytes

With additional challenge of parsing digits:

print map{(ord(uc)-64)%43," "}<>=~/([A-Z\d])/gi

Try it online!

Reduced to 38 bytes by ignoring digits

print map{ord()%32," "}<>=~/([A-Z])/gi
\$\endgroup\$
1
\$\begingroup\$

PHP, 70 bytes

for(;$c=$argv[1][$i++];)if(($c=ord($c))>64&($c%=32)>0&$c<27)echo"$c ";

Try it online!

-5 bytes thanks to Kevin

\$\endgroup\$
  • \$\begingroup\$ Snippets aren't allowed as submissions here, but you can make it a function or a full program. \$\endgroup\$ – Nissa May 31 '18 at 12:50
  • \$\begingroup\$ Sorry, now it uses the first argument as input \$\endgroup\$ – user2803033 May 31 '18 at 13:13
  • \$\begingroup\$ Hi, welcome to PPCG! If you haven't already, tips for golfing in PHP and tips for golfing in <all languages> might be interesting to read through. As for parts you can golf: && can be &, and ord(strtolower($c))-96 can be ord($c)%32. Also, I think you can remove the ~ before $c, but I'm not sure. Haven't programmed much in PHP, and don't really know what the ~ is used for right here anyway. \$\endgroup\$ – Kevin Cruijssen May 31 '18 at 14:44
  • \$\begingroup\$ Thanks for your input. Mod 32 is a good idea. It saves some bytes but requires an additional check to make sure ord($c) is bigger than 64. \$\endgroup\$ – user2803033 May 31 '18 at 18:06
1
\$\begingroup\$

Perl 5 -p, 35 bytes

$_="@{[map{(-64+ord uc)%43}/\w/g]}"

Try it online!

Includes the extra portion about the digits.

\$\endgroup\$
  • 1
    \$\begingroup\$ /\w/ includes _ \$\endgroup\$ – Brad Gilbert b2gills May 31 '18 at 20:10
  • \$\begingroup\$ Much smaller than what I'd been playing with! You can save one byte, and fix the bug @BradGilbertb2gills mentioned, using -F/[^0-9\pL]|/: Try it online! \$\endgroup\$ – Dom Hastings Jun 7 '18 at 12:04
1
\$\begingroup\$

Japt 2.0 -S, 9 bytes

f\l ®c %H

Run it online

Explanation:

f\l ®c %H                                    Input: "Hello..."
f            Match:
 \l             [A-Za-z]                     ["H","e","l","l","o"]
    ®        Map Z over the results:
     c         char-code of Z                [72,101,108,108,111]
       %H      mod 32                        [8,5,12,12,15]
-S           Join the chars with a space     8 5 12 12 15
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 32 bytes (alpha), 41 bytes (alpha+digit)

{~(.uc.comb(/<:L>/)».ord X-64)}

Try it (32 bytes alpha)

{~((.uc.comb(/<:L+:N>/)».ord X-64)X%43)}

Try it (41 bytes alpha + digit)

Expanded:

32 bytes alpha

{  # bare block lambda with implicit parameter $_

  ~( # coerce to string (space separated)

      .uc                      # uppercase
      .comb( / <:L > / )\      # get letters as a sequence
      ».ord                    # get the ordinal of each
      X- 64                    # subtract 64 from each
  )
}

41 bytes alpha + digit

{  # bare block lambda with implicit parameter $_

  ~( # coerce to string (space separated)
    (
      .uc                      # uppercase
      .comb( / <:L + :N > / )\ # get letters and numbers as a sequence
      ».ord                    # get the ordinal of each
      X- 64                    # subtract 64 from each
    ) X% 43                    # modulus 43 for each
  )
}
\$\endgroup\$
  • \$\begingroup\$ This also matches non-ASCII characters like Э, but I've asked for clarification from the OP on whether the input is ASCII-only or not. \$\endgroup\$ – Jo King Jun 25 '18 at 6:35
1
\$\begingroup\$

Tcl, 93 bytes

puts [lmap c [split $argv ""] {if [string is alp $c] {expr ([scan $c %c]-64)%32} {continue}}]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PHP 108 105 Bytes

Try it online (108 Bytes)

Tri it online (105 Bytes)

-3 Bytes, thanks to @manassehkatz (Change the level of strtolower and remove A-Z from regex)

Code, tried to avoid any loop

<?=strtr(implode(" ",str_split(preg_replace(
"/[^a-z]/",'',strtolower($argv)))),array_flip(range("`",z)));

Explanation

$string = preg_replace("/[^a-z]/",'',strtolower($argv))  
//the string only contains letters

$string = implode(" ",str_split($string)); 
//the string has a space after every letter

$string = strtr($string, array_flip(range("`",z)));  
//replace every letter   acording to the array

$replacementArray = array_flip(range("`",z));
//this array contains the ansi characters from "`" to the "z"
//array_flip to change the keys with the values
//final array ["`"=>0,"a"=>1, "b"=>2...."z"=>26]
\$\endgroup\$
  • \$\begingroup\$ In order to get this to run without Warnings, I had to (a) change $argv to $argv[1] and (b) add " around the last z. But with or without those changes (which might be version dependent - I am using 5.6), you can save 3 bytes by moving the strtolower() in a level strtolower($argv) and remove capital A-Z from the regex. \$\endgroup\$ – manassehkatz May 31 '18 at 23:01
  • \$\begingroup\$ On php 7 it trows a warning, im gonna modified the answer now. I am sorry just no wi had time to check :-D \$\endgroup\$ – Francisco Hahn Jun 1 '18 at 14:58
  • 1
    \$\begingroup\$ @manassehkatz Taked your suggestion, and saved 3 Bytes, thanks a lot. \$\endgroup\$ – Francisco Hahn Jun 1 '18 at 15:10
  • \$\begingroup\$ Shouldnt that be $argv[1] or $argn instead of $argv?. join is 3 bytes shorter than implode. \$\endgroup\$ – Titus Jun 2 '18 at 9:43
0
\$\begingroup\$

Python 3, 84 bytes

print(*filter(int,['abcdefghijklmnopqrstuvwxyz'.find(c)+1for c in input().lower()]))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Python 2, 110 bytes 104 bytes, with user input

a="abcdefghijklmnopqrstuvwxyz";print" ".join(str(a.index(l)+1)for l in list(input().lower())if l in a)

Try it Online!


Python 2, 105 bytes 104 bytes 96 bytes, where t is predefined:

a="abcdefghijklmnopqrstuvwxyz";print" ".join(str(a.index(l)+1)for l in list(t.lower())if l in a)

Try it Online!

Let's break it down with a more readable version:

alphabet = "abcdefghijklmnopqrstuvwxyz"
foo = [str(alphabet.index(letter) + 1) for letter in list(t.lower()) if letter in alphabet]
print " ".join(foo)

First, we define alphabet as being, well, the alphabet.

Next, we use list comprehension to:

  1. Make a list where each item is a lowercase character from t
  2. For each letter, if it is not in the alphabet, discard it.
  3. If it is, find its index in the alphabet,
  4. add one to it (because we start counting at 1)
  5. and make it a string.

Finally, we join it all together and print it.


Edit: Changed to print (and lost portability) to save bytes and make it work outside a function

Edit 2: Added a version with input() instead of predefined variables

Edit 3: Removed 8 bytes in Solutions 1 and 2 thanks to Jo King

\$\endgroup\$
  • \$\begingroup\$ You've got 6 extraneous spaces in your code \$\endgroup\$ – Jo King May 31 '18 at 9:50
  • \$\begingroup\$ @JoKing I found three (after semicolon, surrounding +), where are the others? \$\endgroup\$ – Theo C May 31 '18 at 9:56
  • \$\begingroup\$ Before if,for and " " \$\endgroup\$ – Jo King May 31 '18 at 10:00
  • \$\begingroup\$ You can also remove the [] in the join \$\endgroup\$ – Jo King May 31 '18 at 10:04
  • \$\begingroup\$ Again, welcome to PPCG! FYI by default (i.e. if not explicitly overridden in the question) answer submissions may be functions or full-programs (like your 104 byte version) but not snippets (like your 96 byte version). Here you could submit a version which creates a function which returns the string for 100 bytes :) \$\endgroup\$ – Jonathan Allan May 31 '18 at 12:28
0
\$\begingroup\$

PowerShell, 63 bytes

"$(([char[]]"$args".ToUpper()|%{$_-($_,64)[$_-in65..90]})-ne0)"

Try it online!

(Seems long ...)

Takes input $args, converts it .ToUppercase, casts it as a char-array, feeds that into a for each loop. Inside the loop, we subtract either itself or 64 from the (ASCII int) value, based on whether or not the current value is -in the range 65 to 90 (i.e., it's an ASCII capital letter). Those values are left on the pipeline, and we use a -notequal to eliminate the non-letter values (because they're all zero). Those numbers are encapsulated in a string as the default stringification of an array is to space-separate it, so we get that pretty cheaply. That string is left on the pipeline and output is implicit.

\$\endgroup\$
0
\$\begingroup\$

MS-SQL, 133 bytes

SELECT STRING_AGG(ASCII(substring(upper(s),number+1,1))-64,' ')FROM
spt_values,t WHERE type='P'AND substring(s,number+1,1)LIKE'[a-z]'

Per our IO rules, input is taken via a pre-existing table t with varchar field s.

SQL 2017 or later is required. Must also be run in the master database, because I'm taking advantage of a system table called spt_values, which (when filtered by type='P') contains counting numbers from 0 to 2047.

Basically I'm joining a number table with the input string using SUBSTRING(), which returns a separate row for each individual character. This is filtered for only letters using LIKE'[a-z]', then we get their ASCII value and subtract 64. These numbers are joined back into a string using the (new to SQL 2017) function STRING_AGG.

\$\endgroup\$
0
\$\begingroup\$

Pyth, 10 bytes

jdfTmhxGr0

I'm pretty sure this can be golfed a little bit... -2 bytes if I can output as a list, some answers seem to but it's not in the spec

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You can remove the last d (jdfTmhGr0, 10 bytes). \$\endgroup\$ – Mr. Xcoder May 31 '18 at 15:40
0
\$\begingroup\$

C (gcc), 67 bytes

c;f(char*s){for(;*s;)(c=tolower(*s++)-96)>0&c<27&&printf("%d ",c);}

Try it online!

Converts each char to lowercase, offsets its code by -96 and, if it falls in the range of the 1-indexed alphabet, prints the offset code

\$\endgroup\$
0
\$\begingroup\$

jq, 45 bytes

[gsub("\\W";"")|explode[]%32|@text]|join(" ")

 gsub("\\W";"")                                # remove non-alpha characters
               |explode[]                      # get decimal values of characters
                         %32                   # get positions in alphabet
                            |@text             # convert back to string
[                                 ]|join(" ")  # join with a space

Try it online

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.