![[Column] Complex Calculations](https://python101.tech/wp-content/uploads/2025/07/eyecatch_138.webp)
Complex Calculations
Even if a calculation formula looks complicated at first glance, you can get the result by carefully calculating each step. However, complicated calculation formulas make it difficult to decipher the code, and simply looking at them is tiring.
Not limited to Python, programming languages allow you to assign intermediate results of expressions to variables while continuing calculations, which can improve readability even in complex calculations. Here, we will examine the process of organizing complex calculations to make them easier to comprehend.
Let's look at the following example. You are organizing a party and have made a reservation at a restaurant. If everyone who said they would attend the party shows up and pays the fee, there will be no problem, but some people may cancel on the day of the party and not pay the cancellation fee. Let's think of a formula to calculate the loss to the organizer in that case. (※This calculation formula includes some redundant parts.)
loss = (((num_expected-num_canceled)*fee_person) + (num_canceled*fee_cancel)) - (((num_expected-num_canceled)*fee_person) + (num_paid_cancel * fee_cancel))
The above calculation formula attempts to determine the loss amount as “[total amount when everyone has paid] - [total amount actually paid].”
Although parentheses have been explicitly added to clarify the formula, the code is very complex and difficult to read due to the long lines.
The calculation can be performed by evaluating the expressions inside the innermost parentheses first; Python will then output the correct result. However, upon closer inspection, there are multiple instances of the same calculation within the expression, and complex code can be a breeding ground for bugs. Therefore, it is necessary to rewrite this code to make it more readable.
In the case of the above calculation formula, you can break down each element of the calculation and write the code. You can write the code as follows.
# Input value (example)
num_expected = 50 # Number of expected participants
num_canceled = 5 # Number of same-day cancellations
fee_person = 100 # Participation fee (per person)
fee_cancel = 20 # Cancellation fee
num_paid_cancel = 3 # Number of people who paid the cancellation fee
# Actual number of participants
num_attended = num_expected - num_canceled
# Participation fee and cancellation fee when all participants pay
ideal_fee_total = num_attended * fee_person
ideal_cancel_total = num_canceled * fee_cancel
# Actual participation fees and cancellation fees paid
actual_fee_total = num_attended * fee_person
actual_cancel_total = num_paid_cancel * fee_cancel
# Loss amount ([total amount when everyone paid] - [total amount actually paid])
loss = (ideal_fee_total+ideal_cancel_total) - (actual_fee_total+actual_cancel_total)
print(‘The loss is’, loss, ‘dollars’)
In this way, by separating each calculation and assigning them to easy-to-understand variable names, you can understand the order of calculations and what each calculation means. You will also notice that readability has improved. Given these advantages, it is very important to write calculations in separate lines rather than in a single line.
Incidentally, if you organize the code into separate lines, as shown above, you can see that there are unnecessary calculations. In the above code, there are two instances of the calculation “num_attended * fee_person” in lines 12 and 16. Since there is no need to perform this calculation twice, we will combine them into one. If we extract the calculation part of the code and organize it, it will look like this.
# number of actual participants
num_attended = num_expected - num_canceled
# Participation fee and cancellation fee when all participants pay
ideal_fee_total = num_attended * fee_person
ideal_cancel_total = num_canceled * fee_cancel
# Actual cancellation fees paid
actual_cancel_total = num_paid_cancel * fee_cancel
# Loss amount ([total amount when everyone paid] - [total amount actually paid])
loss = (ideal_fee_total+ideal_cancel_total) - (ideal_fee_total+actual_cancel_total)
print(‘The loss is’, loss, ‘dollars’)
The revised code deletes the calculation section of the “actual_fee_total” variable (original line 16) and replaces the “actual_fee_total” variable in the line “loss = ~” (original line 20) with the “ideal_fee_total” variable.
After rewriting it this far, if you look at the calculation formula in the line “loss = ~,” you can see that some calculations can be omitted.
loss = (ideal_fee_total+ideal_cancel_total) - (ideal_fee_total+actual_cancel_total)
Let's remove all the parts enclosed in parentheses. Please note that there is a minus sign immediately before the parentheses in the latter half, so the plus and minus signs of each variable in the latter half of the parentheses will be reversed.
loss = ideal_fee_total + ideal_cancel_total - ideal_fee_total - actual_cancel_total
Here, we can see that there are two variables named “ideal_fee_total.” Let's rearrange the order of the calculation formulas.
loss = ideal_fee_total - ideal_fee_total + ideal_cancel_total - actual_cancel_total
This results in the expression “ideal_fee_total - ideal_fee_total” appearing in the first half of the calculation formula. Since this expression evaluates to zero, it can be excluded from the calculation. Therefore, the formula can be rewritten as follows.
loss = ideal_cancel_total - actual_cancel_total
How about that? It's clear now. In other words, to calculate the loss, there was no need to calculate the actual participation fees paid. All you had to do was calculate the difference between the “cancellation fees that must be paid to the store” and the “cancellation fees received from those who canceled.”
Now, let's organize and rewrite the code, retaining only the necessary parts for calculating the loss amount.
# Input value (example)
num_canceled = 5 # Number of same-day cancellations
num_paid_cancel = 3 # Number of people who paid the cancellation fee
fee_cancel = 20 # Cancellation fee
ideal_cancel_total = num_canceled * fee_cancel
actual_cancel_total = num_paid_cancel * fee_cancel
# Loss amount
loss = ideal_cancel_total - actual_cancel_total
print(‘The loss is’, loss, ‘dollars’)
Compared to the original code, I think it looks much cleaner. As you can see, organizing complex code in this manner has several advantages, including eliminating unnecessary calculations and enhancing readability.
Strictly speaking, this code can be shortened to the expression “(num_canceled - num_paid_cancel) * fee_cancel,” but whether to shorten it or not should be decided based on the balance between the advantages of shortening and readability. (In this case, it should be fine to shorten it.) Even if there is some waste in the code, if the difference in processing speed is minimal, readability should be prioritized. Conversely, continuing to prioritize readability when processing speed is required is also a problem. In other words, it is a matter of balance.
When you first start programming, you may feel excited about writing complex calculations, but what is essential for programmers is to improve readability and write code that anyone can understand. This is necessary for ongoing long-term development. If you think an expression is complex, try breaking it into separate lines, or make it a habit to ask others for their opinions.