Generate All Unique 3‑Digit Numbers and Compute Tiered Bonuses with Python
This article demonstrates two Python programming exercises: generating all unique three‑digit numbers from digits 1‑4 using nested loops, and calculating a tiered profit‑based bonus by segmenting profit ranges, complete with source code, analysis, and sample outputs.
Example 1
Problem: With the digits 1, 2, 3, 4, how many distinct three‑digit numbers without repeated digits can be formed, and what are they?
Analysis: All three positions (hundreds, tens, units) can be filled by 1‑4. Generate every permutation and keep only those where the three digits differ.
<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != k and i != j and j != k:
print i, j, k
</code>Output:
<code>1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
</code>Example 2
Problem: A company distributes bonuses based on profit I with tiered percentages: up to 100,000 ¥ at 10%; the next 100,000 ¥ at 7.5%; 200,000‑400,000 ¥ at 5%; 400,000‑600,000 ¥ at 3%; 600,000‑1,000,000 ¥ at 1.5%; any amount above 1,000,000 ¥ at 1%. Write a program that reads the monthly profit and outputs the total bonus.
Analysis: Use a number line to locate the profit segment. Define the bonus as a long integer and apply the appropriate rate for each segment.
<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
i = int(raw_input('净利润:'))
arr = [1000000,600000,400000,200000,100000,0]
rat = [0.01,0.015,0.03,0.05,0.075,0.1]
r = 0
for idx in range(0,6):
if i > arr[idx]:
r += (i - arr[idx]) * rat[idx]
print (i - arr[idx]) * rat[idx]
i = arr[idx]
print r
</code>Sample Output (profit = 120,000 ¥):
<code>净利润:120000
1500.0
10000.0
11500.0
</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.