Practical Applications of Branch and Loop Structures

by Pyrastra Team
Practical Applications of Branch and Loop Structures

Through the previous two lessons, everyone has gained an initial understanding of branch structures and loop structures in Python. Branch structures and loop structures are the foundation for constructing program logic, and their importance goes without saying. However, for beginners, this is also a relatively difficult part. Many people can understand the syntax of branch structures and loop structures, but when faced with actual problems, they don’t know where to start. It’s easy to understand other people’s code, but it’s difficult to write similar code yourself. If you have the same problems and confusion, don’t be discouraged. This is only because your programming journey has just begun, and your practice volume hasn’t reached the level where you can write code freely. As long as you strengthen programming practice and produce qualitative changes through quantitative accumulation, this problem will eventually be solved.

Example 1: Prime Numbers Within 100

Note: Prime numbers are positive integers (excluding 1) that can only be divided by 1 and themselves. We previously wrote code to determine prime numbers; this is an upgraded version.

"""
Output prime numbers within 100

Version: 1.0
Author: Luo Hao
"""
for num in range(2, 100):
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num)

Example 2: Fibonacci Sequence

Requirement: Output the first 20 numbers in the Fibonacci sequence.

Note: The Fibonacci sequence, usually also called the golden ratio sequence, is a sequence introduced by Italian mathematician Leonardo Fibonacci in “Liber Abaci” while studying the growth rate of rabbits under ideal hypothetical conditions. Therefore, this sequence is often jokingly called the “rabbit sequence”. The characteristic of the Fibonacci sequence is that the first two numbers in the sequence are both 1, and starting from the third number, each number is the sum of the two numbers before it. According to this rule, the first 10 numbers of the Fibonacci sequence are: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. The Fibonacci sequence has direct applications in modern physics, quasicrystal structures, chemistry, and other fields.

"""
Output the first 20 numbers in the Fibonacci sequence

Version: 1.0
Author: Luo Hao
"""

a, b = 0, 1
for _ in range(20):
    a, b = b, a + b
    print(a)

Note: The a, b = b, a + b in the loop above means assigning the value of variable b to a and assigning the value of a + b to b. Through this recurrence formula, we can sequentially obtain numbers in the Fibonacci sequence.

Example 3: Finding Narcissistic Numbers

Requirement: Find all narcissistic numbers in the range 100 to 999.

Tip: In number theory, a narcissistic number (also called a pluperfect digital invariant, an Armstrong number, or a plus perfect number) is an $\small{N}$-digit non-negative integer where the sum of each digit raised to the $\small{N}$th power equals the number itself. For example: $\small{153 = 1^{3} + 5^{3} + 3^{3}}$, so 153 is a narcissistic number; $\small{1634 = 1^{4} + 6^{4} + 3^{4} + 4^{4}}$, so 1634 is also a narcissistic number. For three-digit numbers, the key to solving the problem is to split it into ones, tens, and hundreds digits, then determine whether it meets the requirements of a narcissistic number. This is actually quite easy to do using Python’s // and % operators.

"""
Find narcissistic numbers in the range 100 to 999

Version: 1.0
Author: Luo Hao
"""
for num in range(100, 1000):
    low = num % 10
    mid = num // 10 % 10
    high = num // 100
    if num == low ** 3 + mid ** 3 + high ** 3:
        print(num)

The trick of using // and % to split a number above is quite commonly used when writing code. If we want to reverse a positive integer of unknown length, for example, turning 12389 into 98321, we can also use these two operations to implement it, as shown in the code below.

"""
Reversing a positive integer

Version: 1.0
Author: Luo Hao
"""
num = int(input('num = '))
reversed_num = 0
while num > 0:
    reversed_num = reversed_num * 10 + num % 10
    num //= 10
print(reversed_num)

Example 4: Hundred Coins Hundred Chickens Problem

Note: The Hundred Coins Hundred Chickens problem is a mathematical problem proposed by ancient Chinese mathematician Zhang Qiujian in the book “Suanjing”: A rooster costs 5 coins, a hen costs 3 coins, and three chicks cost 1 coin. With 100 coins to buy 100 chickens, how many roosters, hens, and chicks are there? Translated into modern language: Roosters cost 5 yuan each, hens cost 3 yuan each, chicks cost 1 yuan for three. With 100 yuan to buy one hundred chickens, how many roosters, hens, and chicks are there?

"""
Hundred Coins Hundred Chickens problem

Version: 1.0
Author: Luo Hao
"""
for x in range(0, 21):
    for y in range(0, 34):
        for z in range(0, 100, 3):
            if x + y + z == 100 and 5 * x + 3 * y + z // 3 == 100:
                print(f'Roosters: {x}, Hens: {y}, Chicks: {z}')

The method used above is called exhaustive search, also known as brute force search. This method enumerates all possible candidates in the alternative solutions one by one and checks whether each candidate meets the problem description, ultimately obtaining the solution to the problem. In the code above, we used nested loop structures. Assuming there are x roosters, obviously the value range of x is 0 to 20. Assuming there are y hens, its value range is 0 to 33. Assuming there are z chicks, its value range is 0 to 99 and the value is a multiple of 3. This way, we set the condition for 100 chickens x + y + z == 100 and the condition for 100 yuan 5 * x + 3 * y + z // 3 == 100. When both conditions are satisfied simultaneously, it’s the correct answer to the problem, and we output it with the print function. This method seems rather clumsy, but for computers with very powerful computing capabilities, it’s usually a feasible or even good choice. As long as a solution to the problem exists, it can be found.

In fact, the code above can be written better. Since we’ve already assumed there are x roosters and y hens, the number of chicks should be 100 - x - y. This way, by reducing one condition, we can rewrite the three-layer nested for-in loop above into a two-layer nested for-in loop. With fewer loop iterations, the code execution efficiency is significantly improved, as shown below.

"""
Hundred Coins Hundred Chickens problem

Version: 1.1
Author: Luo Hao
"""
for x in range(0, 21):
    for y in range(0, 34):
        z = 100 - x - y
        if z % 3 == 0 and 5 * x + 3 * y + z // 3 == 100:
            print(f'Roosters: {x}, Hens: {y}, Chicks: {z}')

Note: The z % 3 == 0 in the code above is to ensure that the number of chicks is a multiple of 3.

Example 5: CRAPS Gambling Game

Note: CRAPS, also known as Hazard, is a very popular table gambling game in Las Vegas, USA. The game uses two dice, and players play by rolling two dice to get points. The simplified rules are: If the player rolls 7 or 11 points on the first roll, the player wins; if the player rolls 2, 3, or 12 points on the first roll, the house wins; if the player rolls other points, the game continues and the player rolls again. If the player rolls 7 points, the house wins; if the player rolls the same points as the first roll, the player wins; for other points, the player continues rolling until there’s a winner. To add interest to the code, we set that at the start of the game, the player has 1000 yuan in bets. Before each game starts, the player places a bet. If the player wins, they can get a reward corresponding to the bet amount. If the house wins, the player loses the bet amount. The game ends when the player goes bankrupt (loses all bets).

"""
Craps gambling game

Version: 1.0
Author: Luo Hao
"""
import random

money = 1000
while money > 0:
    print(f'Your total assets: {money} yuan')
    # Bet amount must be greater than 0 and less than or equal to player's total assets
    while True:
        debt = int(input('Please place bet: '))
        if 0 < debt <= money:
            break
    # Use two uniformly distributed random numbers from 1 to 6 to simulate rolling two dice
    first_point = random.randrange(1, 7) + random.randrange(1, 7)
    print(f'\nPlayer rolled {first_point} points')
    if first_point == 7 or first_point == 11:
        print('Player wins!\n')
        money += debt
    elif first_point == 2 or first_point == 3 or first_point == 12:
        print('House wins!\n')
        money -= debt
    else:
        # If the first roll doesn't determine a winner, player needs to roll again
        while True:
            current_point = random.randrange(1, 7) + random.randrange(1, 7)
            print(f'Player rolled {current_point} points')
            if current_point == 7:
                print('House wins!\n')
                money -= debt
                break
            elif current_point == first_point:
                print('Player wins!\n')
                money += debt
                break
print('You are bankrupt, game over!')

Summary

Both branch structures and loop structures are very important and are the foundation for constructing program logic. You must achieve mastery through a large amount of practice. We can use the Craps game mentioned above as a standard. If you can complete this code smoothly, then you’ve already mastered the knowledge of branch structures and loop structures very well.