Featured Posts

CS50 Python , Nutrition Facts Table

Image
Nutrition Facts: Python Practice for Beginners Nutrition Facts Table for Python Practice Welcome to this comprehensive guide for Python beginners! If you are learning how to work with lists, dictionaries, and loops, this post will help you build practical skills using a real-world example: nutrition facts for fruits. Understanding how to organize and manipulate data is a key part of programming, and this exercise will give you hands-on experience. Below is a sample table of fruits and their calorie values, formatted as a Python list of dictionaries. This structure is ideal for coding exercises, projects, or even building your own nutrition calculator. You can expand this list, add new fruits, or use it as a foundation for more advanced Python tasks. Python List of Dictionaries Example: fruits = [ {'name': 'Apple', 'calories': 130}, {'name': 'Avocado', 'calories': 50}, {'name': 'Banana', 'ca...

Python 3.5.1.2 Sorting Simple Lists - the Bubble Sort Algorithm

The Bubble Sort Algorithm

3.5.1.2 LAB

you may wonder why I post this section here while it's not a LAB. Simply, to show you how to know the number of swaps happened to rearrange the list.

Sorting a list

How many passes do we need to sort the entire list?

The code is already written. I just added one thing, did you notice? Yes, a variable called swaps, and I assigned it to 0 value. Then, swaps variable is inserted under the for loop, if block. So; whenever the if condition is True (which means that the arranging order is not correct), we add 1 to swaps.

Solution Code:

my_list = [810624]  # list to sort
swapped = True  # It's a little fake, we need it to enter the while loop.
swaps = 0 # To count the number of loops happened to arrange the list in order
while swapped:
    swapped = False  # no swaps so far
    for i in range(len(my_list) - 1):
        if my_list[i] > my_list[i + 1]:
            swaps += 1 #Each loop add 1 to swaps variable
            swapped = True  # a swap occurred!
            my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
    
print(f"My list: {my_list} , Number of swaps: {swaps}")

Follow the Python page on the Blog to be the first to know


Comments

Popular posts from this blog

فرصتك للدراسة في ألمانيا: منحة ممولة بالكامل لطلاب الدراسات العليا

How to Deactivate Screen Reader in Kali Linux

Murphy's Law: Expect the Unexpected

Python 3.2.1.14 LAB: Essentials of the while loop

Data Analysis Roadmap 2026: From Excel Lover to Python-Powered Analyst