make this bubble sort python code shorter than this?

-3

i don't know if it can be made shorter than this

def bubble_sort(num):
  for j in range((len(num)-1)):
     for i in range((len(num)-1)):
        if(num[i]>num[i+1]): num[i] , num[i+1] = num[i+1],num[i]       
 return num
print (bubble_sort(list(input("enter the array/list elements:"))))

Phani Srikar

Posted 2018-08-05T03:00:43.987

Reputation: 1

Question was closed 2018-08-05T04:00:30.263

3If you want to ask others to make your code shorter, at least try to make your code already short. We don't want to post a trivial answer that says Remove unnecessary spaces around operators and Indent using only 1 space. – user202729 – 2018-08-05T03:10:08.217

3Also be explicit what you need, and what's the goal (tag it with [tag:tips], [tag:code-golf], and clarify whether it's byte count or character count; and what exactly is the requirement - the code can work differently while still satisfy the requirement) – user202729 – 2018-08-05T03:10:35.657

2

Have you had a look at Tips for Golfing in Python?

– Jo King – 2018-08-05T03:35:51.763

1

Welcome to PPCG! You should at lleast refer to this and this question to try to golf your program more, currently there seems to be no effort made to golf it (ie. the most trivial golfs such as removing the print statement or removing superfluous whitespace). Additionally you might be interested in this answer.

– ბიმო – 2018-08-05T03:36:56.757

Answers

2

I'm ignoring the function call right now and just golfing the function itself. I'm also assuming this is Python 2, since the original had a print statement rather than function.

Shorten variable names, remove excess whitespace and brackets

116 bytes

def b(n):
 for j in range(len(n)-1):
  for i in range(len(n)-1):
   if n[i]>n[i+1]:n[i],n[i+1]=n[i+1],n[i]
 return n

Try it online!

Change first for loop to repeat n times

102 bytes

def b(n):
 for j in n:
  for i in range(len(n)-1):
   if n[i]>n[i+1]:n[i],n[i+1]=n[i+1],n[i]
 return n

Try it online!

Change if statement to one liner

98 bytes

def b(n):
 for j in n:
  for i in range(len(n)-1):n[i:i+2]=n[i:i+2][::(n[i]<n[i+1])*2-1]
 return n

Try it online!

Change for loop to exec

96 bytes

def b(n):exec"for i in range(len(n)-1):n[i:i+2]=n[i:i+2][::(n[i]<n[i+1])*2-1]\n"*len(n);return n

Try it online!

Combine exec and for loop

94 bytes

def b(n):i=0;exec"n[i:i+2]=n[i:i+2][::(n[i]<n[i+1])*2-1];i+=1;i%=len(n)-1;"*len(n)**2;return n

Try it online!

Jo King

Posted 2018-08-05T03:00:43.987

Reputation: 38 234

2Just for the record, if j is unused then for j in [[]]*len(n) can be for j in n. – FryAmTheEggman – 2018-08-05T04:15:28.120

Additionally, I could have then used sorted for 81 bytes

– Jo King – 2018-08-06T10:10:35.267