12
\$\begingroup\$

Rules

You will receive as input a list that contains integers and strings. Your task is to move all of the strings to the end of the list and all of the integers to the beginning of the list.

This is so the answer with the least number of bytes wins.

\$\endgroup\$
9
  • \$\begingroup\$ Do the integers and strings need to stay in the original order relative to other elements of the same type? \$\endgroup\$
    – xnor
    Feb 15, 2020 at 14:06
  • \$\begingroup\$ @xnor No. The order may be destroyed. \$\endgroup\$ Feb 15, 2020 at 14:09
  • 1
    \$\begingroup\$ What do you do for a language that doesn't have integers except as strings of ASCII digits? \$\endgroup\$
    – Neil
    Feb 16, 2020 at 0:15
  • 1
    \$\begingroup\$ Does it have to be an integer or can it be a string of digits? If so, what about strings with digits in them? \$\endgroup\$
    – S.S. Anne
    Feb 16, 2020 at 2:42
  • 3
    \$\begingroup\$ What if it has no combined lists of integers and strings? \$\endgroup\$
    – S.S. Anne
    Feb 16, 2020 at 19:14

27 Answers 27

11
+50
\$\begingroup\$

Python 3, 24 bytes

lambda l:l.sort(key=dir)

Try it online!

Sorts in place, modifying the input list. It so happens that the dir of a number is smaller than that of a string because the __abs__ method that numbers have comes alphabetically first.

>> dir(1)
['__abs__', '__add__', '__and__', ...]
>> dir('a')
['__add__', '__class__', '__contains__', ...]

The only built-in to use as a key that would be shorter than dir is id, but it seems to puts strings before numbers, and I don't know if its behavior is consistent.


Python 2, 6 bytes

sorted

Try it online!

Python 2 allows comparing different types, and conveniently numbers come before strings.

\$\endgroup\$
4
  • \$\begingroup\$ @Victor The 05AB1E solution should win because it was posted first and is shortest, unless this is [popularity-contest] in which case it is off-topic. \$\endgroup\$
    – S.S. Anne
    Feb 18, 2020 at 14:32
  • 1
    \$\begingroup\$ @S.S Anne This code-golf question was inspired by a similar question on StackOverflow in Russian about python. So I'm interested mostly in python solutions but all other answers are interesting to me as well. Ok, I'll accept 05AB1E. \$\endgroup\$ Feb 18, 2020 at 14:41
  • 1
    \$\begingroup\$ @VictorsaysReinstateMonica Thank you for playing by the rules :) \$\endgroup\$
    – S.S. Anne
    Feb 18, 2020 at 15:43
  • 1
    \$\begingroup\$ @S.S.Anne I thought to accept an answer does not mean anything on this site but now I understood ;) Thanks for the explanation! \$\endgroup\$ Feb 18, 2020 at 18:09
7
\$\begingroup\$

05AB1E, 1 byte

05AB1E does this exactly as specified.

{

Try it online!

Or, verify all test cases (so far)

Explanation

Even if the answer is a one-byte answer, I still feel like typing the explanation.

Implicit input as a list
{ Sort the list (numbers go before the strings)
\$\endgroup\$
0
5
\$\begingroup\$

APL (Dyalog Extended), 1 byte

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Wolfram Language (Mathematica), 4 bytes

Sort

Try it online!

\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6), 31 bytes

a=>a.sort((a,b)=>!b.big-!a.big)

Try it online!

How?

The deprecated but still widely supported method .big() is defined for Strings and undefined for Numbers. Hence the sorting criterion !b.big-!a.big which is either \$-1\$, \$0\$ or \$1\$.

\$\endgroup\$
3
\$\begingroup\$

Ruby, 30 24 bytes

->l{l.sort_by &:methods}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 33 bytes

L.sort(key=lambda x:str(type(x)))

Try it online!

And in fact this is how I'd write it in live code too, probably...

\$\endgroup\$
3
  • \$\begingroup\$ Why not L.sort(key=lambda x:str(type(x)))? \$\endgroup\$ Feb 15, 2020 at 14:28
  • \$\begingroup\$ Ah yeah, that space is unnecessary indeed. \$\endgroup\$ Feb 15, 2020 at 14:29
  • \$\begingroup\$ It's a common output that higher-rep people are often outgolfed by lower-rep people ... \$\endgroup\$
    – user92069
    Feb 15, 2020 at 14:38
2
\$\begingroup\$

Red, 23 bytes

func[x][reverse sort x]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Java 8, 43 41 bytes

L->{L.sort((i,j)->i==i.toString()?1:-1);}

-2 bytes thanks to @Neil.

Input as a List of Objects, with String and Integer items.

Try it online.

Explanation:

L->{                    // Method with Object-List parameter and no return-type
  L.sort(               //  Sort the List by:
    (i,j)->             //   For every pair of items `i,j`:
      i==i.toString()?  //    If `i` is a String (by checking whether `i` and the builtin
                        //    String-conversion of `i` reference the same instance):
       1                //     Put it after item `j`
      :                 //    Else:
       -1);}            //     Put it before item `j`
\$\endgroup\$
2
  • 1
    \$\begingroup\$ i==i.toString()?1:-1 saves 2 bytes. (Obviously, this can only ever be true for String objects, and it's also fortunately trivially true for all String objects.) \$\endgroup\$
    – Neil
    Feb 18, 2020 at 19:47
  • \$\begingroup\$ @Neil Ah, very smart, thanks! This is only the second time I use Java's referencing on Strings as an advantage with codegolfing. :) (The first was once with s==s.trim() to check whether a String didn't contained any trailing and/or leading white-spaces.) \$\endgroup\$ Feb 18, 2020 at 20:56
2
\$\begingroup\$

Perl 6 Raku, 15 14 bytes

-1 thanks to Jo King.

*.sort(*~~Str)

Try it online!

This is an anonymous WhateverCode function nested within another. I didn't know I could do that.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 14 bytes with *~~Str \$\endgroup\$
    – Jo King
    Feb 19, 2020 at 1:17
1
\$\begingroup\$

Python 3, 78 bytes

lambda x:[*filter(lambda _:type(_)==int,x)]+[*filter(lambda _:type(_)==str,x)]

Try it online!

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

Japt, 2 bytes

ñy

Test it here

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

PHP, 20 bytes

fn(&$a)=>sort($a,2);

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ From the question Your task is to move all strings..., there is no output or function needed, and from what I see for example from the 05AB1E's answer, isn't sort($t,2); enough? \$\endgroup\$
    – Kaddath
    Feb 17, 2020 at 11:03
  • \$\begingroup\$ @Kaddath Unless otherwise specified, default rules require all submissions to be full programs or functions. \$\endgroup\$
    – Neil
    Feb 18, 2020 at 19:43
  • \$\begingroup\$ @Neil OK that's noted, thanks :) \$\endgroup\$
    – Kaddath
    Feb 19, 2020 at 8:09
1
\$\begingroup\$

Bash + GNU utilities, 36 bytes

p=egrep\ ^-?[0-9]+$
tee a|$p
$p -v<a

Try it online!

A value is considered to be an integer if: (1) the first character is either a digit or a minus sign; (2) any other characters are all digits; and (3) at least one digit is present. Any value that is not an integer is considered to be a string.

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

R, 26 bytes

function(L)sort(unlist(L))

Straightforward: unlist then sort the list L. Works because digits sort before alphabetic letters, be them upper or lower case.

Try it online!

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

C (gcc), 117 bytes

f(a,l,p,c)struct{int*s,i;}*a,*p;{for(c=l,p=a;c--;p++)p->s?:printf("%d ",p->i);for(;l--;a++)a->s&&printf("%s ",a->s);}

C does not have lists of combined strings and integers so instead I use an array of structures; if the string is NULL (which a real string never will be), then print the integer instead. Of course, go over the list an print the integers first, then the strings.

Stable sort.

Try it online!

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

T-SQL, 35 bytes

Decimals will be placed in the integer section

DECLARE @ table(a varchar(99))
INSERT @ values('1'),('a'),('abc'),('1'),('d'),('84753')

SELECT*FROM @ ORDER BY-isnumeric(a)
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 2 bytes

><

Try it online!

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

Pyth, 8 bytes

o$dir(N)

I don't know what it is about python eval that makes me feel like I'm bending the rules, but I like it :)

Try it online!

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

Retina 0.8.2, 24 bytes

O$^m`^(-?[0-9]+$)?.*$
$1

Try it online! Explanation:

m`^(-?[0-9]+$)?.*$

Match each line, capturing it if it's an integer.

O$
$1

Sort the matches by the captured integer, as a string. This sorts non-integers to the beginning as nothing was captured which results in the empty string in the substitution.

^

Reverse the list after sorting.

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

Charcoal, 15 bytes

F²ΦEθ⭆¹κ⁼ι⁼κ§θλ

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

F²

Make two passes over the input items.

Eθ⭆¹κ

Stringify all the input items...

Φ...⁼ι⁼κ§θλ

... and filter on those elements that are not or are unchanged under stringification respectively.

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

Batch, 320 Bytes

@ECHO OFF
Setlocal EnableDelayedExpansion
Set /P S=Str:
FOR %%B IN (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) DO (
IF "!L!"=="" (Set L=!S:%%B= !) Else (Set L=!L:%%B= !)
)
FOR %%C IN (0,1,2,3,4,5,6,7,8,9) DO (
IF "!R!"=="" (Set R=!S:%%C= !) Else (Set R=!R:%%C= !)
)
Set S=%L: =%%R: =%
ECHO(%S%
pause
\$\endgroup\$
1
\$\begingroup\$

Kotlin, 41 bytes

Expects and returns a List<Any>. The order of ints and strings in the returned list should be stable.

{it.partition{it is Int}.let{(a,b)->a+b}}

Try it online!

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

Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes

^'#s

See the README to see how to run this

^'#s # Expects the list as input
^'   # Sort the input using the following function as a key:
  #s # Is string?
\$\endgroup\$
0
\$\begingroup\$

Factor, 29 bytes

[ [ real? 0 1 ? ] sort-with ]

Try it online!

Is it a real number? Then sort it as though it were 0. Otherwise, sort it as though it were 1.

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

Uiua, 3 bytes

⊏⍏.

Try it!

This is the default behavior of sorting a boxed list in Uiua.

⊏⍏.
  .  # duplicate
 ⍏   # rise (grade up)
⊏    # select
\$\endgroup\$
0
\$\begingroup\$

Scala 3, 75 bytes

Golfed version. Attempt This Online!

_.sortWith{case(i:String,j:Any)=>2<1;case(i:Any,j:String)=>2>1;case _=>2>1}

Ungolfed version. Attempt This Online!

object Main {
  trait N {
    def c(L: List[Any]): List[Any]
  }

  val n: N = (L: List[Any]) => {
    L.sortWith {
      case (i: String, j: Any) => false
      case (i: Any, j: String) => true
      case _ => true
    }
  }

  def main(args: Array[String]): Unit = {
    test(1, 4, "2", "c", 6)
    test("a", 1, "b", 2, "c", 3, "1", "2", "3")
  }

  def test(a: Any*): Unit = {
    var list = a.toList
    prettyPrint(list)
    print(": ")
    list = n.c(list)
    prettyPrint(list)
    println()
  }

  def prettyPrint(list: List[Any]): Unit = {
    print("[")
    for (i <- list.indices) {
      val o = list(i)
      o match {
        case s: String => print("\"" + s + "\"")
        case _ => print(o)
      }
      if (i < list.size - 1) print(",")
    }
    print("]")
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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