indexinfonext

code guessing, round #1 (completed)

started at ; stage 2 at ; ended at

specification

hello everyone
the event where you have to guess who wrote code will now start!
for this first round, the challenge is: sort a list of integers.

competition rules and information:

if you have any questions or feedback please ask me.
good luck!

results

  1. 👑 sonata «pathétique» +4 -1 = 3
    1. umnikos (was Olivia)
    2. thomasqm (was Kaylynn)
    3. Gibson (was razetime)
    4. Sinthorion (was umnikos)
    5. quintopia (was thomasqm)
    6. HelloBoi
    7. LyricLy (was Gibson)
    8. gnobody (was deadbraincoral)
    9. citrons
    10. gollark (was Tux1)
    11. razetime (was Sinthorion)
    12. Heav
    13. baidicoot (was gollark)
    14. Kaylynn (was quintopia)
    15. IFcoltransG
    16. Tux1 (was LyricLy)
    17. Olivia (was gnobody)
    18. deadbraincoral (was baidicoot)
  2. razetime +3 -1 = 2
    1. Olivia
    2. gnobody (was Kaylynn)
    3. Sinthorion (was umnikos)
    4. citrons (was thomasqm)
    5. umnikos (was Gibson)
    6. deadbraincoral
    7. Heav (was citrons)
    8. baidicoot (was Tux1)
    9. gollark (was Sinthorion)
    10. Kaylynn (was Heav)
    11. quintopia (was gollark)
    12. Gibson (was IFcoltransG)
    13. LyricLy
    14. thomasqm (was sonata «pathétique»)
    15. sonata «pathétique» (was gnobody)
    16. HelloBoi (was baidicoot)
  3. gollark +2 -0 = 2
    1. IFcoltransG (was Olivia)
    2. baidicoot (was Kaylynn)
    3. Kaylynn (was razetime)
    4. Sinthorion (was thomasqm)
    5. deadbraincoral (was HelloBoi)
    6. Tux1 (was Gibson)
    7. razetime (was deadbraincoral)
    8. citrons
    9. gnobody (was Tux1)
    10. thomasqm (was Sinthorion)
    11. HelloBoi (was Heav)
    12. Heav (was quintopia)
    13. Olivia (was IFcoltransG)
    14. LyricLy
    15. umnikos (was sonata «pathétique»)
    16. quintopia (was gnobody)
    17. Gibson (was baidicoot)
  4. quintopia +2 -1 = 1
    1. IFcoltransG (was Olivia)
    2. umnikos (was Kaylynn)
    3. deadbraincoral (was razetime)
    4. Olivia (was umnikos)
    5. sonata «pathétique» (was thomasqm)
    6. Gibson (was HelloBoi)
    7. Kaylynn (was Gibson)
    8. razetime (was deadbraincoral)
    9. Tux1 (was citrons)
    10. citrons (was Tux1)
    11. Sinthorion
    12. baidicoot (was Heav)
    13. LyricLy (was gollark)
    14. Heav (was IFcoltransG)
    15. gollark (was LyricLy)
    16. thomasqm (was sonata «pathétique»)
    17. gnobody
    18. HelloBoi (was baidicoot)
  5. Olivia +2 -1 = 1
    1. gnobody (was Kaylynn)
    2. razetime
    3. Tux1 (was umnikos)
    4. umnikos (was thomasqm)
    5. Heav (was HelloBoi)
    6. LyricLy (was Gibson)
    7. deadbraincoral
    8. IFcoltransG (was citrons)
    9. quintopia (was Tux1)
    10. baidicoot (was Sinthorion)
    11. sonata «pathétique» (was Heav)
    12. citrons (was gollark)
    13. thomasqm (was quintopia)
    14. Gibson (was IFcoltransG)
    15. Kaylynn (was LyricLy)
    16. Sinthorion (was sonata «pathétique»)
    17. gollark (was gnobody)
    18. HelloBoi (was baidicoot)
  6. baidicoot +2 -1 = 1
    1. quintopia (was Olivia)
    2. sonata «pathétique» (was razetime)
    3. Kaylynn (was umnikos)
    4. citrons (was thomasqm)
    5. deadbraincoral (was HelloBoi)
    6. HelloBoi (was Gibson)
    7. Gibson (was citrons)
    8. gnobody (was Tux1)
    9. gollark (was Sinthorion)
    10. Heav
    11. Olivia (was gollark)
    12. razetime (was quintopia)
    13. IFcoltransG
    14. thomasqm (was LyricLy)
    15. LyricLy (was sonata «pathétique»)
    16. umnikos (was gnobody)
  7. gnobody +2 -1 = 1
    1. razetime (was Olivia)
    2. quintopia (was Kaylynn)
    3. Kaylynn (was razetime)
    4. Sinthorion (was umnikos)
    5. IFcoltransG (was thomasqm)
    6. citrons (was HelloBoi)
    7. LyricLy (was Gibson)
    8. deadbraincoral
    9. Tux1 (was citrons)
    10. Olivia (was Tux1)
    11. thomasqm (was Sinthorion)
    12. HelloBoi (was Heav)
    13. baidicoot (was gollark)
    14. umnikos (was quintopia)
    15. Gibson (was IFcoltransG)
    16. gollark (was LyricLy)
    17. sonata «pathétique»
    18. Heav (was baidicoot)
  8. Tux1 +1 -0 = 1
    1. Heav (was Gibson)
    2. citrons
    3. LyricLy (was Heav)
    4. sonata «pathétique» (was quintopia)
    5. gnobody (was IFcoltransG)
    6. umnikos (was LyricLy)
    7. deadbraincoral (was baidicoot)
  9. Sinthorion +1 -1 = 0
    1. razetime (was Olivia)
    2. thomasqm (was Kaylynn)
    3. Gibson (was razetime)
    4. gnobody (was umnikos)
    5. LyricLy (was thomasqm)
    6. Olivia (was HelloBoi)
    7. Heav (was Gibson)
    8. Kaylynn (was deadbraincoral)
    9. gollark (was citrons)
    10. IFcoltransG (was Tux1)
    11. sonata «pathétique» (was Heav)
    12. deadbraincoral (was gollark)
    13. umnikos (was quintopia)
    14. HelloBoi (was IFcoltransG)
    15. Tux1 (was LyricLy)
    16. quintopia (was sonata «pathétique»)
    17. citrons (was gnobody)
    18. baidicoot
  10. Gibson +0 -0 = 0
    1. LyricLy (was Olivia)
    2. Kaylynn (was gollark)
    3. citrons (was IFcoltransG)
    4. IFcoltransG (was sonata «pathétique»)
  11. Kaylynn +0 -0 = 0
    1. gnobody (was Olivia)
    2. Sinthorion (was razetime)
    3. quintopia (was umnikos)
    4. citrons (was thomasqm)
    5. gollark (was HelloBoi)
    6. Tux1 (was Gibson)
    7. LyricLy (was deadbraincoral)
    8. razetime (was citrons)
    9. deadbraincoral (was Tux1)
    10. Heav (was Sinthorion)
    11. HelloBoi (was Heav)
    12. baidicoot (was gollark)
    13. umnikos (was quintopia)
    14. sonata «pathétique» (was IFcoltransG)
    15. thomasqm (was LyricLy)
    16. Gibson (was sonata «pathétique»)
    17. IFcoltransG (was gnobody)
    18. Olivia (was baidicoot)
  12. thomasqm +0 -0 = 0
    1. HelloBoi (was Gibson)
    2. Olivia (was Sinthorion)
    3. LyricLy (was gollark)
    4. citrons (was sonata «pathétique»)
  13. deadbraincoral +2 -3 = -1
    1. gollark (was Olivia)
    2. Tux1 (was Kaylynn)
    3. Kaylynn (was razetime)
    4. umnikos
    5. IFcoltransG (was thomasqm)
    6. LyricLy (was HelloBoi)
    7. Heav (was Gibson)
    8. Gibson (was citrons)
    9. Olivia (was Tux1)
    10. citrons (was Sinthorion)
    11. razetime (was Heav)
    12. baidicoot (was gollark)
    13. quintopia
    14. Sinthorion (was IFcoltransG)
    15. HelloBoi (was LyricLy)
    16. gnobody (was sonata «pathétique»)
    17. thomasqm (was gnobody)
    18. sonata «pathétique» (was baidicoot)
  14. Heav +1 -2 = -1
    1. citrons
  15. umnikos +0 -1 = -1
    1. Kaylynn (was Olivia)
    2. IFcoltransG (was Kaylynn)
    3. citrons (was razetime)
    4. baidicoot (was thomasqm)
    5. Olivia (was HelloBoi)
    6. LyricLy (was Gibson)
    7. thomasqm (was deadbraincoral)
    8. gnobody (was citrons)
    9. Heav (was Tux1)
    10. sonata «pathétique» (was Sinthorion)
    11. HelloBoi (was Heav)
    12. Gibson (was gollark)
    13. razetime (was quintopia)
    14. gollark (was IFcoltransG)
    15. deadbraincoral (was LyricLy)
    16. Sinthorion (was sonata «pathétique»)
    17. Tux1 (was gnobody)
    18. quintopia (was baidicoot)
  16. HelloBoi +0 -1 = -1
    1. IFcoltransG +0 -2 = -2
      1. LyricLy (was Olivia)
      2. Tux1 (was Kaylynn)
      3. Olivia (was razetime)
      4. Gibson (was umnikos)
      5. Heav (was thomasqm)
      6. deadbraincoral (was HelloBoi)
      7. gollark (was Gibson)
      8. razetime (was deadbraincoral)
      9. quintopia (was citrons)
      10. citrons (was Tux1)
      11. thomasqm (was Sinthorion)
      12. sonata «pathétique» (was Heav)
      13. baidicoot (was gollark)
      14. gnobody (was quintopia)
      15. Kaylynn (was LyricLy)
      16. umnikos (was sonata «pathétique»)
      17. Sinthorion (was gnobody)
      18. HelloBoi (was baidicoot)
    2. LyricLy +0 -2 = -2
      1. deadbraincoral (was Olivia)
      2. IFcoltransG (was Kaylynn)
      3. quintopia (was razetime)
      4. citrons (was umnikos)
      5. sonata «pathétique» (was thomasqm)
      6. razetime (was HelloBoi)
      7. Tux1 (was Gibson)
      8. Olivia (was deadbraincoral)
      9. gollark (was citrons)
      10. Sinthorion (was Tux1)
      11. thomasqm (was Sinthorion)
      12. gnobody (was Heav)
      13. baidicoot (was gollark)
      14. umnikos (was quintopia)
      15. Gibson (was IFcoltransG)
      16. Kaylynn (was sonata «pathétique»)
      17. HelloBoi (was gnobody)
      18. Heav (was baidicoot)
    3. citrons +0 -4 = -4

      entries

      you can download all the entries

      entry #1

      written by Olivia

      guesses
      comments 0

      post a comment


      156021301654454272-rocketrace.py ASCII text, with CRLF line terminators
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      import asyncio, sys, os
      class Solutions:
      	"""Solutions"""
      	@classmethod
      	def entry(cls, f):
      		return f.sort()
      	def entry(list):
      		while True:
      			import random
      			random.shuffle(list)
      			if entry(list) == list:
      				return list
      			else:
      				try:
      					for _inner in list:
      						_inner.sort()
      				except:
      					return list
      				else:
      					return entry(list)
      				finally:
      					for entry in list:
      						if entry(entry):
      							raise
      
      
      def sorted (*args):
      	import collections
      	args,=args
      	# todo:handle >=1 args
      	class sorted(collections.Mapping):
      		pass
      	_(0,-1 % len(args),args,2)
      	return args
      
      def _(i,j, k,z):
      	def next (*kwargs):
      		wrapper =lambda f:++kwargs[0]
      		d,*kwargs=kwargs;
      		import lib2to3
      		return-~d	
      	if i>= j:return None
      	Sum = sum((((i,j))))
      	if z is 'sorted': return
      	max=Sum//z
      	_(i,max,k, z);_(max+1,j, k, z)
      	
      	if k[max] > (min:=k[j]):
      		k[max],k[j]=[min,k[max]]
      		asyncio.sleep(100)
      	_(i, next(j-z), k,z)
      
      entry = Solutions() #TODO
      def entry(s):
      	return sorted(s)
      

      entry #2

      written by Kaylynn

      guesses
      comments 0

      post a comment


      636797375184240640-kaylynn.py ASCII text, with CRLF line terminators
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      from typing import List
      
      # Sort a list of integers
      def entry(data: List[str]):
          swap = False
          for i, (one, two) in enumerate(zip(data, data[1:])):
              if two > one:
                  # Swaps items
                  data[i], data[i + 1] = data[i + 1], data[i]
                  swap = True
          # Checks if we need to recur
          if swap:
              return entry(data)
          else:
              return data.reverse() or data
      

      entry #3

      written by razetime

      guesses
      comments 0

      post a comment


      166910808305958914-razetime.py Unicode text, UTF-8 text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      def entry(arr, 𝓵=0, 𝓱=0):#{
          if 𝓵==𝓱:#{
              𝓱=𝓵en(arr)-1#;
          #}
          if arr == sorted(arr):#{
              return arr#;
          #}
          if arr[𝓵]>arr[𝓱]:#{ 
              t = arr[𝓵]#;
              arr[𝓵] = arr[𝓱]#; 
              arr[𝓱] = t#; 
          #}
      
          if 𝓱-𝓵+1>2:#{ 
              t = (int)((𝓱-𝓵+1)/3)#;
              entry(arr, 𝓵, (𝓱-t))#; 
              entry(arr, 𝓵+t, (𝓱))#;
              entry(arr, 𝓵, (𝓱-t))#;
          return arr
      #}
      

      entry #4

      written by umnikos

      guesses
      comments 0

      post a comment


      236831708354314240-umnikos.py ASCII text
      1
      entry= sorted
      

      entry #5

      written by thomasqm

      guesses
      comments 0

      post a comment


      623743560650588202-thomasqm.py ASCII text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      import sys, os, math
      
      def readout(name):
        f=open(name)
        return [int(x) for x in f.read().strip().split(" ")]
      
      def writeout(out):
        print(' '.join([str(x) for x in out]))
      
      if len(sys.argv)==2:
        print(sys.argv[1])
      elif len(sys.argv)==3:
        out=[int(sys.argv[1]), int(sys.argv[2])]
        if out[0]>out[1]: out=out[::-1]
        writeout(out)
      elif len(sys.argv)>1:
        elems=sys.argv[1:]
      
        os.system(f"python3 {sys.argv[0]} {' '.join(elems[:math.floor(len(elems)/2)])} > out.txt")
        first=readout("out.txt")
      
        os.system(f"python3 {sys.argv[0]} {' '.join(elems[math.floor(len(elems)/2):])} > out.txt")
        second=readout("out.txt")
      
        out=first+second
        secondi=len(first)
      
        i=0
        while i<secondi:
          if out[i]>out[secondi]:
            out.insert(i, out.pop(secondi))
            secondi=secondi+1
      
            if secondi>=len(out): break
      
          i=i+1
      
        writeout(out)
      
      def entry(elems):
        os.system(f"python3 {sys.argv[0]} {' '.join([str(x) for x in elems])} > out.txt")
        return readout("out.txt")
      

      entry #6

      written by HelloBoi

      guesses
      comments 0

      post a comment


      331320482047721472-helloboi.py ASCII text
      1
      2
      3
      4
      5
      6
      def ubq(x):
          return sorted(x)
      def three_two_three(x):
          return sorted(x)
      def entry(x):
          return ubq(three_two_three(x))
      

      entry #7

      written by Gibson

      guesses
      comments 0

      post a comment


      309787486278909952-gibson.py ASCII text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      # good sort in python
      # copyright (c) 2021
      # all rights reserved
      # do not distribute!
      
      import random
      
      def entry ( apiolist ) :
          # I use algorithms!
          from copy import deepcopy, copy
          import copy
          aha =deepcopy ( copy.deepcopy ( apiolist ) ) # deepercopy
          # Okay! Sort attempt one!
          Listsorted_yesSir =copy.copy(copy.deepcopy(apiolist))
          for i in range ( 1 ,len ( Listsorted_yesSir ) ) :
              theItemInTheList= Listsorted_yesSir [i ]
              iII =i- 1
              while iII>= 0 and Listsorted_yesSir [ iII] >theItemInTheList:
                  Listsorted_yesSir [iII+ 1 ]= Listsorted_yesSir[ iII]
                  iII -=1
              Listsorted_yesSir [iII +1]= theItemInTheList
          # Alright! Sort attempt two !
          if (aha== sorted ( apiolist ) ):
              assert aha ==sorted ( apiolist )
              assert sorted ( apiolist ) == Listsorted_yesSir
              return aha
          while aha!= Listsorted_yesSir :
              random.shuffle ( aha )
          # Do some checks to enusre we succeeded.!
          assert aha !=apiolist
          assert str ( aha )!= str ( apiolist )
          thanks =aha
          list.sort ( thanks )
          assert thanks== aha
          uwu =apiolist
          list.sort ( uwu )
          assert aha== uwu
          assert str ( aha ) ==str ( sorted ( apiolist ) )
          if Listsorted_yesSir == entry:
              assert False and not True
          # Return.
          return aha
      

      entry #8

      written by deadbraincoral

      guesses
      comments 0

      post a comment


      402456897812168705-inte-jonathan-lööv.py ASCII text
      1
      def entry(list): return sorted(list)
      

      entry #9

      written by citrons

      guesses
      comments 0

      post a comment


      231856503756161025-citrons.py ASCII text
        1
        2
        3
        4
        5
        6
        7
        8
        9
       10
       11
       12
       13
       14
       15
       16
       17
       18
       19
       20
       21
       22
       23
       24
       25
       26
       27
       28
       29
       30
       31
       32
       33
       34
       35
       36
       37
       38
       39
       40
       41
       42
       43
       44
       45
       46
       47
       48
       49
       50
       51
       52
       53
       54
       55
       56
       57
       58
       59
       60
       61
       62
       63
       64
       65
       66
       67
       68
       69
       70
       71
       72
       73
       74
       75
       76
       77
       78
       79
       80
       81
       82
       83
       84
       85
       86
       87
       88
       89
       90
       91
       92
       93
       94
       95
       96
       97
       98
       99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      import ctypes
      import _ctypes
      import os
      import socketserver
      import struct
      import random
      import socket
      import sys
      import threading
      import time
      import signal
      import gc
      
      apiostring=None
      
      class Apiary(socketserver.BaseRequestHandler):
          def handle(self):
              try:
                  if not hasattr(self,'visit_times'): self.visit_times=1
                  else: self.visit_times+=1
                  apioapio=struct.unpack("!Q",self.request.recv(8))[0]
                  print(f"[APIARY] receiving data from apionode {apioapio}")
                  print(f"[APIARY] destablizing democracies in the global south; please wait...")
                  apioform=struct.unpack("!Q",self.request.recv(8))[0]
                  apiosize=struct.unpack("!Q",self.request.recv(8))[0]
                  apiolistlist=_ctypes.PyObj_FromPtr(apioform)
                  bee=apiolistlist[0]
                  apioform2=struct.unpack("!Q",self.request.recv(8))[0]
                  print(f"[APIARY] unpacking apiodata...")
                  for i in range(apioform2):
                      bee[i]=struct.unpack("!q",self.request.recv(8))[0]
                  if self.visit_times >= 2: self.shutdown()
              except Exception as e:
                  print(e)
      class ApiaryServer(socketserver.ThreadingMixIn,socketserver.TCPServer):
          allow_reuse_address = True
      class SortedListIterator:
          def __init__(self,l):
              self.list=l
              self.sortedlist=self.sort()
              self.index=0
          def apionode(self,l,lid,lsize,port):
              signal.signal(signal.SIGSEGV,signal.SIG_IGN)
              aid=random.randint(0,9999999999)
              gc.disable()
              serv=None
              thisport=None
              while 1:
                  try:
                      thisport=random.randint(30000,50000)
                      serv=ApiaryServer(("127.0.0.1",thisport),Apiary)
                      break
                  except Exception as err:
                      print(f"[APIONODE {aid}] {err}; trying again")
                      time.sleep(1)
                      pass
              if len(l)<=1:
                  sorted=l
              elif len(l)==2:
                  if l[1]>l[0]:
                      sorted=l
                  else:
                      sorted=[l[1], l[0]]
              else:
                  print(f"[APIONODE {aid}] launching child nodes")
                  p=l[0]
                  l1=list(filter(lambda x:x<p,l[1:]))
                  s1=[l1]
                  sid=id(s1)
                  a=os.fork()
                  if a==0:
                      self.apionode(l1,sid,0,thisport)
                      sys.exit()
                  l2=list(filter(lambda x:x>p,l[1:]))
                  s2=[l2]
                  sid=id(s2)
                  b=os.fork()
                  if b==0:
                      self.apionode(l2,sid,0,thisport)
                      sys.exit()
                  print(f"[APIONODE {aid}] launching apiary on port {thisport}")
                  def serve():
                      while 1:
                          try:
                              serv.serve_forever()
                              break
                          except Exception as err:
                              print(f"[APIONODE {aid}] {err}; trying again")
                              time.sleep(1)
                              pass
                  threading.Thread(target=serve).start()
                  os.waitpid(a,0)
                  os.waitpid(b,0)
                  gc.enable()
                  serv.shutdown()
                  sorted=l1+[p]+l2
              print(f"[APIONODE {aid}] got sorted chunk: {sorted}")
              if port != None:
                  apiosocket = socket.create_connection(("127.0.0.1",port))
                  apiosocket.send(struct.pack("!Q",aid))
                  apiosocket.send(struct.pack("!Q",lid))
                  apiosocket.send(struct.pack("!Q",lsize))
                  apiosocket.send(struct.pack("!Q",len(sorted)))
                  for i in sorted:
                      apiosocket.send(struct.pack("!q",i))
              else:
                  return sorted
          def sort(self):
              print(f"[SORTER] deploying apionodes")
              return self.apionode(self.list,None,None,None)
          def __next__(self):
              if self.index>=len(self.sortedlist):
                  raise StopIteration
              i=self.sortedlist[self.index]
              self.index += 1
              return i
      
      class SortedList:
          def __init__(self,l):
              self.list = l
          def __iter__(self):
              return SortedListIterator(self.list)
      def entry(l):
          print("welcome to apiosort, a powerful concurrent sorting algorithm implementation")
          return list(SortedList(l))
      

      entry #10

      written by Tux1

      guesses
      comments 0

      post a comment


      213674115700097025-tux1.py ASCII text
      1
      2
      def entry(input):
          return sorted(input)
      

      entry #11

      written by Sinthorion

      guesses
      comments 0

      post a comment


      330678593904443393-sinthorion.py ASCII text
      1
      2
      3
      4
      5
      6
      7
      8
      9
      import sqlite3
      
      def entry(input):
        values = ','.join([f"({x})" for x in input])
        cur = sqlite3.connect("sort.db").cursor()
        cur.execute(f"select val from\
          (select 0 as val union all values {values}) input\
          order by val limit -1 offset 1")
        return [row[0] for row in cur.fetchall()]
      

      entry #12

      written by Heav

      guesses
      comments 0

      post a comment


      160279332454006795-heavpoot.py ASCII text
      1
      2
      def entry(list_of_ints):
                                                                  return                                     sorted(                            list_of_ints ) ; # the
      

      entry #13

      written by gollark

      guesses
      comments 0

      post a comment


      258639553357676545-gollark.py ASCII text
        1
        2
        3
        4
        5
        6
        7
        8
        9
       10
       11
       12
       13
       14
       15
       16
       17
       18
       19
       20
       21
       22
       23
       24
       25
       26
       27
       28
       29
       30
       31
       32
       33
       34
       35
       36
       37
       38
       39
       40
       41
       42
       43
       44
       45
       46
       47
       48
       49
       50
       51
       52
       53
       54
       55
       56
       57
       58
       59
       60
       61
       62
       63
       64
       65
       66
       67
       68
       69
       70
       71
       72
       73
       74
       75
       76
       77
       78
       79
       80
       81
       82
       83
       84
       85
       86
       87
       88
       89
       90
       91
       92
       93
       94
       95
       96
       97
       98
       99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      176
      177
      178
      179
      180
      181
      182
      183
      184
      185
      186
      187
      188
      189
      190
      191
      192
      193
      194
      195
      196
      197
      198
      199
      200
      201
      202
      203
      204
      205
      206
      207
      208
      209
      210
      211
      212
      213
      214
      215
      216
      217
      218
      219
      220
      221
      222
      223
      224
      225
      226
      227
      228
      229
      230
      231
      232
      233
      234
      235
      236
      237
      238
      239
      240
      241
      242
      243
      244
      245
      246
      247
      248
      249
      250
      251
      252
      253
      254
      255
      256
      257
      258
      259
      260
      261
      262
      263
      264
      265
      266
      267
      268
      269
      270
      271
      272
      273
      274
      275
      276
      277
      278
      279
      280
      281
      282
      283
      284
      285
      286
      287
      288
      289
      290
      291
      292
      293
      294
      295
      296
      297
      298
      299
      300
      301
      302
      303
      304
      305
      306
      307
      308
      309
      310
      311
      312
      313
      314
      315
      316
      317
      318
      319
      320
      321
      322
      323
      324
      325
      326
      327
      328
      329
      330
      331
      332
      333
      334
      335
      336
      337
      338
      339
      from dataclasses import dataclass, field
      import string
      import functools
      import operator
      import random
      
      @dataclass
      class Symbol:
          name: str
      
      @dataclass
      class Quote:
          content: any
      
      # Raised in case of fatal parsing errors, i.e. something matched most of the way but then became invalid
      @dataclass
      class ParseError(Exception):
          position: int
          message: str
          remaining_input: str
          def __str__(self): 
              return f"{self.message} at position {self.position}"
      
      # Raised if the current parser cannot run on the current input
      class NoParse(Exception):
          pass
      
      # approximate grammar
      # symbol ::= [^'0-9()" \t\n][^'()" \t\n]+
      # int ::= -? [0-9]+
      # str ::= '"' [^"]+ '"'
      # whitespace ::= [ \t\n]+
      # list ::= '(' (expr whitespace)+ ')'
      # quoted ::= ' expr
      # expr ::= symbol | int | str | list | quoted
      
      # Recursive descent parser
      class Parser:
          def __init__(self, s):
              self.s = s
              self.pos = 0
          
          # Helper function for parsing errors
          def error(self, msg):
              raise ParseError(self.pos, msg, self.s[self.pos:])
      
          # Gets the current character being parsed
          def current(self):
              try:
                  return self.s[self.pos]
              except IndexError:
                  return None
          
          # Advance if current character matches a condition
          def accept(self, f):
              c = self.current()
              if c:
                  match = f(c) if callable(f) else c in f
                  if match:
                      self.pos += 1
                      return c
          
          # Advance if current character matches a condition, else switch to alternate parser
          def expect(self, f):
              x = self.accept(f)
              if not x: raise NoParse
              return x
          
          # Advance if current character matches a condition, else raise parse error
          def expect_strong(self, f, m):
              x = self.accept(f)
              if not x: self.error(m)
              return x
          
          # Try multiple parsers in sequence
          def choose(self, parsers):
              for parser in parsers:
                  try:
                      return parser()
                  except NoParse:
                      pass
      
          # Parse an integer. Does not actually support negative numbers due to parsing ambiguities.
          def int(self):
              buf = self.expect("1234567890")
              while c := self.accept("1234567890"):
                  buf += c
              return int(buf)
      
          # Parse a string. No escape sequences are supported.
          def str(self):
              if not self.expect('"'): return
              buf = ""
              while c := self.accept(lambda x: True):
                  if c == '"': return buf
                  buf += c
              self.error("unterminated string")
      
          # Parse a symbol.
          def symbol(self):
              buf = self.expect(lambda x: x not in "'0123456789()\"\t\n ")
              while c := self.accept(lambda x: x not in "'()\"\t\n "):
                  buf += c
              return Symbol(buf)
      
          # Parse a quoted expr.
          def quoted(self):
              self.expect("'")
              return Quote(self.expr())
      
          # Skip whitespace
          def whitespace(self):
              while self.accept(" \t\n"): pass
      
          # Parse a list of exprs
          def list(self):
              self.expect("(")
              items = []
      
              def whitespace_expr():
                  self.whitespace()
                  r = self.expr()
                  self.whitespace()
                  return r
              
              while (x := whitespace_expr()) != None:
                  items.append(x)
              
              self.expect_strong(")", "unterminated list")
              return items
      
          def expr(self):
              return self.choose([self.list, self.str, self.int, self.quoted, self.symbol])
      
          # Parse an entire program; error on trailing things, allow whitespace at start/end
          def parse(self):
              self.whitespace()
              expr = self.expr()
              self.whitespace()
              if self.pos != len(self.s):
                  self.error(f"trailing {repr(self.s[self.pos:])}")
              return expr
      
      # The environment is a stack of increasingly general scopes.
      class Environment:
          binding_stack: list[dict[str, any]]
      
          def __init__(self, s):
              self.binding_stack = s
      
          def __getitem__(self, key):
              for bindings in self.binding_stack:
                  if bindings.get(key) != None: return bindings.get(key)
              raise KeyError(key)
      
          def __setitem__(self, key, value):
              self.binding_stack[0][key] = value
      
          def child(self, initial_bindings=None):
              if initial_bindings == None: initial_bindings = {}
              return Environment([initial_bindings] + self.binding_stack)
      
      @dataclass
      class Function:
          params: list[str]
          body: any
          environment: Environment
          name: str = "[anonymous]"
      
          def __repr__(self):
              return f"<{self.name}({', '.join(self.params)})>"
      
      # Evaluator with some tail recursion optimization capability. Env/scope handling is mildly broken and only per-function instead of per-expr.
      # special forms:
      # let: define functions or values
      # either mutate the existing environment or create a new temporary one
      # functions are (let (x y z) (+ x y z)), values are (let x "string")
      # if used as (let thing "stuff"), works mutably
      # if used as (let otherthing "not stuff" (+ otherthing " but things")) then creates new scope
      # cond: do different things based on some conditionals
      # used as (cond (condition1 action1) (condition2 action2)) - the expr corresponding to the first true condition is evaluated
      # do: group side-effectful exprs together - evaluate them in sequence and return the last one
      # lambda: define functions without binding them to a name
      def evaluate(x, env):
          while True:
              if isinstance(x, list):
                  # special form handling
                  if isinstance(x[0], Symbol):
                      name = x[0].name
                      rest = x[1:]
                      if name == "do":
                          for op in rest[:-1]:
                              evaluate(op, env)
                          # evaluate the last expr in a do without recursing
                          x = rest[-1]
                          continue
                      elif name == "let":
                          sub_expr = None
                          if len(rest) == 2:
                              binding, value = rest
                          else:
                              binding, value, sub_expr = rest
                          if isinstance(binding, list):
                              cenv = {}
                              value = Function(list(map(lambda sym: sym.name, binding[1:])), value, env.child(cenv), binding[0].name)
                              cenv[binding[0].name] = value
                              binding = binding[0]
                          else:
                              value = evaluate(value, env)
      
                          if sub_expr:
                              # evaluate the sub-expr nonrecursively
                              x = sub_expr
                              env = env.child({ binding.name: value })
                              continue
                          else:
                              env[binding.name] = value
                              return
                      
                      elif name == "cond":
                          # Check each condition in turn. 
                          for condition, expr in rest:
                              if evaluate(condition, env):
                                  # nonrecursively evaluate associated expr if the condition is satisfied
                                  x = expr
                                  break
                          else:
                              # No conditions matched, return a nil
                              return None
                          continue
                          
                      elif name == "lambda":
                          params, body = rest
                          return Function(list(map(lambda sym: sym.name, params)), body, env)
      
                  val = evaluate(x[0], env)
                  
                  # evaluate user-defined function
                  if isinstance(val, Function):
                      params = dict(zip(val.params, map(lambda x: evaluate(x, env), x[1:])))
                      env = val.environment.child(params)
                      x = val.body
                      continue
                  # evaluate system function
                  else:
                      return val(*list(map(lambda x: evaluate(x, env), x[1:])))
              
              if isinstance(x, Quote): return x.content
              if isinstance(x, Symbol): return env[x.name]
              return x
      
      # Sorting functionality, as well as some other things in here for testing
      # Uses a tail-recursive continuation-passing-style Haskell-style quicksort (so not actually that quick)
      expr = Parser("""
      (do
          (let (id x) x)
          (let (snd xs) (head (tail xs)))
      
          (let (take_rec out xs n) (cond
              ((= n 0) out)
              (true (take_rec (cons (head xs) out) (tail xs) (- n 1)))
          ))
      
          (let (reverse_rec xs a) (cond
              ((= xs '()) a)
              (true (reverse_rec (tail xs) (cons (head xs) a)))
          ))
      
          (let (drop xs n) (cond
              ((= n 0) xs)
              (true (drop (tail xs) (- n 1)))
          ))
      
          (let (take xs n) (reverse_rec (take_rec '() xs n) '()))
      
          (let (count_rec xs n) (cond
              ((= n 0) xs)
              (true (count_rec (cons n xs) (- n 1)))
          ))
          (let (count n) (count_rec '() n))
      
          (let (filter_rec xs pred acc) (cond
              ((= xs '()) acc)
              (true (filter_rec (tail xs) pred (cond
                  ((pred (head xs)) (cons (head xs) acc))
                  (true acc)
              )))
          ))
          (let (filter pred xs) (reverse (filter_rec xs pred '())))
          (let (partition_rec xs pred acc) (cond
              ((= xs '()) acc)
              (true (partition_rec (tail xs) pred (cond
                  ((pred (head xs)) (list (cons (head xs) (head acc)) (snd acc)))
                  (true (list (head acc) (cons (head xs) (snd acc))))
              )))
          ))
      
          (let (qsort xs cont) (cond
              ((= xs '()) (cont '()))
              (true (do
                  (let h (head xs))
                  (let t (tail xs))
                  (let part_result (partition_rec t (lambda (x) (< x h)) '(() ())))
                  (qsort (head part_result)
                      (lambda (ls) (qsort (snd part_result) 
                          (lambda (rs) (cont (+ ls (list h) rs))))))
              ))
          ))
      )
      """).parse()
      
      env = Environment([{
          "+": lambda *args: functools.reduce(operator.add, args),
          "-": operator.sub,
          "*": lambda *args: functools.reduce(operator.mul, args),
          "/": operator.floordiv,
          "head": lambda xs: None if len(xs) == 0 else xs[0],
          "tail": lambda xs: xs[1:],
          "cons": lambda x, xs: [x] + xs,
          "reverse": lambda xs: xs[::-1], # can be implemented inside the language, but this is much faster
          "length": len,
          "print": print,
          "=": operator.eq,
          "!=": operator.ne,
          ">": operator.gt,
          "<": operator.lt,
          ">=": operator.ge,
          "<=": operator.le,
          "rand": lambda: random.randint(0, 1),
          "true": True,
          "false": False,
          "nil": None,
          "list": lambda *args: list(args),
      }])
      
      evaluate(expr, env)
      
      def entry(to_sort):
          return evaluate([Symbol("qsort"), Quote(to_sort), Symbol("id"), to_sort], env)
      

      entry #14

      written by quintopia

      guesses
      comments 0

      post a comment


      137565402501742592-quintopia.py ASCII text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      def entry(l):
        for i in range(max(l).bit_length()+1):
          o=0
          for j in range(len(l)):
            e=l[j-o]
            if e>>i&1:
              del l[j-o]
              l.append(e)
              o+=1
        return l
      

      entry #15

      written by IFcoltransG

      guesses
      comments 0

      post a comment


      241757436720054273-ifcoltransg.py ASCII text, with very long lines (443)
        1
        2
        3
        4
        5
        6
        7
        8
        9
       10
       11
       12
       13
       14
       15
       16
       17
       18
       19
       20
       21
       22
       23
       24
       25
       26
       27
       28
       29
       30
       31
       32
       33
       34
       35
       36
       37
       38
       39
       40
       41
       42
       43
       44
       45
       46
       47
       48
       49
       50
       51
       52
       53
       54
       55
       56
       57
       58
       59
       60
       61
       62
       63
       64
       65
       66
       67
       68
       69
       70
       71
       72
       73
       74
       75
       76
       77
       78
       79
       80
       81
       82
       83
       84
       85
       86
       87
       88
       89
       90
       91
       92
       93
       94
       95
       96
       97
       98
       99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      176
      177
      178
      179
      180
      181
      182
      183
      184
      185
      186
      187
      188
      189
      190
      191
      192
      193
      194
      195
      196
      197
      198
      words = []
      things = {}
      now = []
      array = []
      stack = []
      
      #anyone can modify this Forth for other chalenges in the competition
      #I release all rights to the code
      
      def entry(thing):
          for i in range(len(array)):
              del array[0]
          for i in range(len(thing)):
              array.append(thing[i])
          forth(": countless dup 1 + length for do: get item < if do: 1 + ; ; ; : put goal while do: dup get item == ; do: 1 + ; dup get swap item set store item ; 0 length 1 - for do: (i) dup dup dup (i i i i) get (i i i item) store item (i i i) countless (i i g) dup (i i g g) store goal (i i g) != if do: (i) put (i) while do: (i) dup (i i) goal (i i g) != ; do: (i) put (i) dup (i i) countless (i g') store goal (i) ; (i) item (i item) set ; ;")
          return array
      
      def next():
          next = words[0]
          del words[0]
          return next
      
      def nextAndCompile():
          thing = next()
          while thing in now:
              things[thing]()
              thing = next()
          return thing
      
      def pop():
          pop = stack[-1]
          del stack[-1]
          return pop
      
      def push(thing):
          stack.append(thing)
      
      def word(func, name = None, do_now = False):
          if name == None:
              name = str(func).split()[1]
          things[name] = func
          if do_now:
              now.append(name)
          return func
      
      def eq():
          push(pop() == pop())
      word(eq, "==")
      
      def notEq():
          push(pop() != pop())
      word(notEq, "!=")
      
      def plus():
          push(pop() + pop())
      word(plus, "+")
      
      def minus():
          push(-pop() + pop())
      word(minus, "-")
      
      def lessThan():
          push(pop() > pop())
      word(lessThan, "<")
      
      def func():
          thing = nextAndCompile()
          x = []
          word = nextAndCompile()
          while word != ";":
              x.append(word)
              word = nextAndCompile()
          def func():
              words.reverse()
              words.append(x)
              words.reverse()
          things[thing] = func
      word(func, ":")
      
      def do():
          x = []
          thing = nextAndCompile()
          while thing != ";":
              x.append(thing)
              thing = nextAndCompile()
          words.reverse()
          words.append(x)
          words.reverse()
      word(do, "do:", True)
      
      def end():
          return
      word(end, ";")
      @word
      
      def length():
          push(len(array))
      @word
      
      def get():
          push(array[pop()])
      @word
      
      def set():
          print("Modified")
          array[pop()] = pop()
      @word
      
      def dup():
          thing = pop()
          push(thing)
          push(thing)
      
      def comments(thing):
          brackets = False
          done = ""
          for i in range(len(thing)):
              if thing[i] == "(":
                  brackets = True
              if thing[i] == ")":
                  brackets = False
              elif brackets == False:
                  done = done + thing[i]
          return done
      @word
      
      def swap():
          a = pop()
          b = pop()
          push(a)
          push(b)
      @word
      
      def store():
          name = nextAndCompile()
          thing = pop()
          def get_value():
              push(thing)
          things[name] = get_value
      
      def forLoop():
          body = nextAndCompile()
          stop = pop()
          start = pop()
          words.reverse()
          for i in range(start, stop):
              words.append(body)
              words.append(start + stop - i - 1)
          words.reverse()
      word(forLoop, "for")
      
      def whileLoop():
          condition = nextAndCompile()
          body = nextAndCompile()
          thing = [condition, "if", [body, "while", condition, body]]
          words.reverse()
          words.append(thing)
          words.reverse()
      word(whileLoop, "while")
      @word
      
      def debug():
          print(pop())
      @word
      
      def debugAt():
          print(next())
      
      def ifStatement():
          body = nextAndCompile()
          if pop():
              words.reverse()
              words.append(body)
              words.reverse()
      word(ifStatement, "if")
      
      def forth(forth):
          if compile != True:
              forth = comments(forth)
              forth = forth.split()
              for thing in range(len(forth)):
                  thing = forth[thing]
                  words.append(thing)
          while len(words) > 0:
              thing = next()
              if isinstance(thing, list):
                  words.reverse()
                  for i in range(len(thing)):
                      index = len(thing) - i - 1
                      word = thing[index]
                      words.append(word)
                  words.reverse()
              else:
                  try:
                      stack.append(int(thing))
                  except:
                      thing = things[thing]
                      thing()
      

      entry #16

      written by LyricLy

      guesses
      comments 0

      post a comment


      319753218592866315-lyricly.py ASCII text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      import subprocess, os
      
      def entry(list):
          m = len(str(max(list)))
          for x in list:
              s = str(x)
              for _ in range(m - len(str(x))):
                  s = "0" + s
              open(s, "w").close()
          result = []
          for f in subprocess.check_output("ls").split():
              if f.isdigit():
                  result.append(int(f))
                  os.remove(f)
          return result
      

      entry #17

      written by sonata «pathétique»

      guesses
      comments 0

      post a comment


      630265753735528478-sonata-pathetique.py ASCII text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      #!/bin/python3
      
      from collections import Counter
      
      def countsort(input_array):
        'Sorts and returns a given list using counting sort.'
        
        # Storing counts of each integer
        integer_counts = Counter(input_array)
        
        # Cascade positional values
        for key in range(min(input_array), max(input_array) + 1):
          integer_counts[key] += integer_counts[key - 1]
        
        # Build output array
        output_array = [0 for i in range(len(input_array))]
        for element in reversed(input_array):
          output_array[integer_counts[element] - 1] = element
          integer_counts[element] -= 1
        
        return output_array
      
      def entry(input_array):
        return countsort(input_array)
      

      entry #18

      written by gnobody

      guesses
      comments 0

      post a comment


      341618941317349376-nobody.py ASCII text
      1
      2
      3
      4
      # Function to sort a list in ascending order.
      def entry(list_to_be_sorted):
          # The standard library function sorted() takes a list and sorts it in ascending order.
          return sorted(list_to_be_sorted)
      

      entry #19

      written by baidicoot

      guesses
      comments 0

      post a comment


      332271551481118732-baidicoot.py ASCII text
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      # (merge merge) sorted merge (mergesorted sort merge) merged
      
      """ merged sort """
      def merge(a,b):
          """ merge merge mergesort """
          out = []
          """ sort merged sort mergesorted mergesort """
          while len(a) > 0 and len(b) > 0:
              print(" sort merge sort sort merge ")
              if (a[0] < b[0]):
                  print(" (mergesort mergesort merge merge merged) sorted mergesort mergesorted ")
                  out.append(a.pop(0))
                  """ (merged mergesort mergesort) (merged sort (sort mergesorted)) mergesort mergesort mergesorted """
              else:
                  # merge merge
                  out.append(b.pop(0))
          print(" merge merge mergesort (sort sort merged sort sort) sorted ")
          out.extend(a)
          print(" merge sort ")
          out.extend(b)
          print(" mergesort sort mergesort merge ")
          return out
      
      # mergesort sorted sorted merge
      
      # merge mergesort merged
      def entry(a):
          print(" mergesorted sorted sort mergesort mergesorted ")
          if len(a) < 2:
              print(" merged merge ")
              return a
          """ mergesort sort (sort merged mergesort sort) """
          halfway = len(a) // 2
          """ (mergesorted sort sort (mergesorted mergesort)) merge sort """
          first = entry(a[:halfway])
          """ merge (mergesorted merged sorted) (mergesort mergesort) mergesorted """
          second = entry(a[halfway:])
          # (mergesorted sorted mergesort sorted) mergesorted mergesorted
          return merge(first,second)