nummax = max(nums) nummin = min(nums) cnt = 0 for i in nums: if nummin < i < nummax: cnt += 1 print(cnt)
2. 方程解的计数
问题描述
统计满足以下条件的整数解 (x, y, z) 的数量:
a ≤ x, y, z ≤ b
z = (100 - 2x - 3y) / 5
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
a, b = map(int, input().split()) cnt = 0
for x inrange(a, b + 1): r = 100 - 2 * x y_min, y_max = a, b
for y inrange(y_min, y_max + 1): z = r - 3 * y if z % 5 == 0: z //= 5 if a <= z <= b: cnt += 1 print(cnt)
3. 统计数字1的出现次数
问题描述
统计从 1 到 n 的数字中,数字 1 出现的次数。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
n = int(input()) cnt = 0 flag = 1 while flag <= n: l = n % flag c = (n // flag) % 10 h = n // (flag * 10) if c == 0: cnt += h * flag elif c == 1: cnt += h * flag + l + 1 else: cnt += (h + 1) * flag flag *= 10 print(cnt)
4. 特殊数字查找
问题描述
查找在 1 到 n 范围内能被 12 整除或包含子串“12”的数字。
代码
1 2 3 4 5 6 7 8 9 10 11
n = int(input()) cnt = 0 l = [] for i inrange(1, n + 1): stri = str(i) if i % 12 == 0: l.append(i) elif'12'in stri: l.append(i) for i in l: print(i, end=" ")
defis_palindrome_time(time_str): h, m = time_str.split(":") return h == m[::-1]
defformat_time(h, m): returnf"{int(h)}:{int(m)}"
deffind_previous_palindrome_time(h, m): whileTrue: m -= 1 if m < 0: m = 59 h -= 1 if h < 0: h = 23 if is_palindrome_time(f"{h:02}:{m:02}"): return format_time(h, m)
deffind_next_palindrome_time(h, m): whileTrue: m += 1 if m == 60: m = 0 h += 1 if h == 24: h = 0 if is_palindrome_time(f"{h:02}:{m:02}"): return format_time(h, m)
defmain(): s = input().strip() h, m = map(int, s.split(":"))
previous_palindrome = find_previous_palindrome_time(h, m) next_palindrome = find_next_palindrome_time(h, m)
print(previous_palindrome) print(next_palindrome)
if __name__ == "__main__": main()
6. 几何计算:垂足坐标
问题描述
计算点 (x, y) 到线段 (a1, b1) 和 (a2, b2) 的垂足坐标。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defperpendicular_foot(x, y, a1, b1, a2, b2): dx, dy = a2 - a1, b2 - b1 t = (dx * (x - a1) + dy * (y - b1)) / (dx**2 + dy**2) foot_x = a1 + t * dx foot_y = b1 + t * dy return foot_x, foot_y
defcan_ship_with_capacity(weights, days, capacity): current_weight = 0 days_needed = 1 for weight in weights: if current_weight + weight > capacity: days_needed += 1 current_weight = weight if days_needed > days: returnFalse else: current_weight += weight returnTrue
deffind_min_ship_capacity(weights, days): left = max(weights) right = sum(weights) while left < right: mid = (left + right) // 2 if can_ship_with_capacity(weights, days, mid): right = mid else: left = mid + 1 return left
defmain(): weights_size = int(input().strip()) weights = list(map(int, input().strip().split())) days = int(input().strip()) result = find_min_ship_capacity(weights, days) print(result)