Sorting question | Sololearn: Learn to code for FREE!

+4

# Sorting question

def sort(A): count=0 for i in range(len(A)): for j in range(i): if A[j]>A[j+1]: temp=A[j] A[j]=A[j+1] A[j+1]=A[j] A[j+1]=temp count+=1 break if count==0: print("yes") else: ("no") A=[3,2,1,4] sort(A) print(A) if count==0: print("yes") else: ("no") Question is i want to sort the given number but first i want to check elements are sorted or not if not then swap but the elements but swap only 1 time if elements taking 2 or more swaps then simply print no. I share my code but my code is giving me error on count is not defined i don't why.

4/24/2022 7:25:35 AM

Akash Gupta

+4

count is a local variable of your function.

+3

Akash Gupta , my goal was only to show you how to eliminate the error with the variable count. The other part of your question I do not understand yet at all.

+3

Akash Gupta There is an error in your bubble sort implementation. It fails on completely reversed list. Also, you can do in place swapping, no need for a temp variable. Also, why not just print the count and the check from inside the function? No need for globals and additional print statements. Korkunç TheTerrible , the reason for the nested for loop is that the process have to go over the list multiple times. Here is a RealPython link: https://realpython.com/sorting-algorithms-python/ https://code.sololearn.com/cu5XFteHSHUS/?ref=app

+2

Akash Gupta This is exactly what JaScript is trying to say?

+2

Lisa if i do something wrong you can tell me?

+2

JaScript def sort(A): global count count = 0 for i in range(len(A)): for j in range(i): if A[j]>A[j+1]: temp=A[j] A[j]=A[j+1] A[j+1]=A[j] A[j+1]=temp count+=1 break if count==1: print("yes") else: ("no") A=[3,1,2,4] print(A) sort(A) print(count) print("no") Actually I don't remember to remove if statement after i call the function now that's the actual code you want to swap only 1 time if elements takes 2 or more than print no if it taking 1 swap than print yes

+2

Ah yes now it works thanks to Lisa .

+1

JaScript yes but when i declared outside the function it giving me error of unboundlocalerror : local variable count referenced before assessment.

+1

The print() in the else-part in the function is missing?

+1

Lisa Hi, Lisa. Can you help me understand why the second loop with j needs to be introduced in this code? Looking at it, I thought list had items that were lists themselves (is it called an array?). Then looking down I saw that A was a list. Why is this not coded as [A]i but instead as [A]j?

+1

JaScript it's a codeshef problem bro you can search if you want to pseudo sorting codeshef problem in Google

+1

JaScript okay np

+1

Hello I'm new here. And I really want to learn a lot of code who can help me (thank you so much))

0