Python Forum
Bubble sort quiz: why the result is not the same?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Bubble sort quiz: why the result is not the same?
#1
Here's a quiz of a Math professor on Twitter:

[Image: ewX81x]

He says the results are:
1) 1 / 930
2) 1 / 14880

I did this code (python3) and while the first result is the same, the second is not the same.
I don't understand why the 2nd answer with my code is about 0.002.
I investigated my script for hours and i don't find any mistake...

Do you confirm that the code is right?

import random

def bubblesortOnePass(l):
    if len(l) == 1:
        return l
    else:
        for i in range(len(l)):
            try:
                if l[i] > l[i+1]:
                    l[i], l[i+1] = l[i+1], l[i]
            except:
                if l[-2] > l[-1]:
                    l[-2],l[-1] = l[-1],l[-2]
        return l

def bubblesortTwoPass(l):
    global counter
    if len(l) == 1 or counter == 2:
        return l
    else:
        for i in range(len(l)):
            try:
                if l[i] > l[i+1]:
                    l[i], l[i+1] = l[i+1], l[i]
            except:
                if l[-2] > l[-1]:
                    l[-2],l[-1] = l[-1],l[-2]
        counter += 1
        return bubblesortTwoPass(l[:-1]) + [l[-1]]

def generateList():
    L = []
    remaining = [i for i in range(1,41)]
    while len(L) < 40:
        random_N = random.choice(remaining)
        L.append(random_N)
        remaining.remove(random_N)
    return L

N = 1000000
totalOnePass = 0
totalTwoPass = 0
for i in range(N):
    L = generateList()
    f = L[19]
    K = L.copy()
    bubblesortOnePass(L)
    if f == L[29]:
        totalOnePass += 1
    counter = 0
    After2pass = bubblesortTwoPass(K)
    if f == After2pass[29]:
        totalTwoPass += 1

print("Probability after One Pass is {}".format(float(totalOnePass / N)))
print("Probability after Two Pass is {}".format(float(totalTwoPass / N)))
Reply


Messages In This Thread
Bubble sort quiz: why the result is not the same? - by lupoalberto - Apr-24-2018, 12:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  QUIZ GUI Form_When admin panel is open, main quiz form is getting freeze Uday 4 887 Aug-25-2023, 08:24 PM
Last Post: deanhystad
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,430 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Python Networkx: Visualize an edge weight with a bubble/circle uvw 0 2,111 Sep-01-2021, 06:26 AM
Last Post: uvw
  Bubble sort on randomized integers bellevie 4 5,543 May-16-2017, 05:28 PM
Last Post: bellevie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020