CoolFace
Apppublic

Rubidium2107/BubbleSortDemostration

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
app.py101 linesDownload Raw Back to root
1import random2import gradio as gr3 4"""5STEP 1: GENERATE LIST6"""7 8def gen_list(): #Generate a random list of random length9    length = random.randint(10,20)10    the_list = random.sample(range(1, 50), length)11    display = f"Random List\n{the_list}"12    return display, the_list13        14 15"""16STEP 2: RUN SORT17"""18 19def run_sort(the_list):20    if not the_list: #If no list has bene generated yet:21        #Return list warning, blank step messages, blank range, and final result22        list_msg = "What list?"23        return(24            list_msg,25            *["" for _ in range(length)],26            *["" for _ in range(length)],27            "No list to search!"28        )29    30    31    else:32        steps = [] #A list of steps so far.33        arr = the_list.copy() #Copy the list to avoid mutating it34        35        #Start sorting36        for iteration in range(1, len(the_list)):   #Outer loop37            swaps = 0 #Reset number of swaps38        39            for inner in range(len(the_list) - iteration):  #For each element this iteration. If inner > length - iteration, it is already in the correct place.40                if arr[inner] > arr[inner + 1]:   #If the next element is less than the current element, swap their places.41                    arr[inner], arr[inner + 1] = arr[inner + 1], arr[inner]42                    swaps += 143                    44                        45            #Early exit: Count swaps. Stop sorting if none have occurred this iteration.         46            if swaps == 0:47                steps.append("List sorted.") #Show the list after this iteration as well a show many swaps occurred and the most recent sorted value.48                break49            else:50                #Show the list after this iteration as well a show many swaps occurred and the most recent sorted value. Create a copy of arr to avoid mutation.51                steps.append(f"{arr.copy()}: {swaps} swaps occurred, bringing {arr[len(the_list) - iteration]} to its correct position.")52 53        while len(steps) < 20: #pad to always output the maximum of 20 steps54            steps.append("List sorted")55 56        final_msg = arr #Display the final message.57 58        #Output list box, step boxes, result box59        return(60            str(the_list),61            *steps,62            final_msg63        )64 65#Title66with gr.Blocks(title="Bubble Sort") as demo:67    gr.Markdown(68        """69        # Bubble Sort!\n70        **Step 1:** Generate a List\n71        **Step 2:** Click Run72        """73    )74    75    list_state = gr.State([]) #App state to hold generate button across clicks76 77    with gr.Row(): #Generate buttons78        gen_btn = gr.Button("Generate List", variant="secondary")79        run_btn = gr.Button("Run!", variant="primary")80 81    #List display82    list_box = gr.Textbox(label="Generated List", lines=2, interactive=False)83    gr.Markdown("### Starting Steps")84    step_boxes = [gr.Textbox(label=f"Iteration {iteration + 1}", lines=1, interactive=False) for iteration in range(20)]85 86    #Final result87    result_box = gr.Textbox(label="Final Result", lines=1, interactive=False)88 89    #Wire up events90    gen_btn.click(91        fn=gen_list,92        inputs=[],93        outputs=[list_box, list_state],94    )95    run_btn.click(96        fn=run_sort,97        inputs=[list_state],98        outputs=[list_box, *step_boxes, result_box],99    )100                    101demo.launch()