Sub topic 2
Negative and Fractional Inputs
This chapter assumes you can work with signed integers, fractions, squares, and order of operations. The definition in each question is the only rule you use. Ignore any standard meaning the symbol might carry.
A made-up operation such as a★b = 2a + b² is a rule. To evaluate it, replace a with the first input and b with the second. Negative and fractional inputs cause most errors, because the squared term changes sign or size in ways that are easy to miss.
from fractions import Fraction
def star(a, b):
return 2 * a + b ** 2
print(star(-2, -3)) # 2(-2) + (-3)^2 = -4 + 9 = 5
print(star(Fraction(1, 2), 4)) # 1 + 16 = 17
print(star(3, Fraction(-1, 2))) # 6 + 1/4 = 25/4Argument Order: a★b Is Not b★a
The first input always fills the a slot, and the second fills the b slot. Swapping them changes the result unless the operation happens to be symmetric.
def star(a, b):
return 2 * a + b ** 2
print(star(3, 4)) # 2(3) + 4^2 = 22
print(star(4, 3)) # 2(4) + 3^2 = 17Nested Operations: Work from the Inside Out
In an expression like (1★2)★3, evaluate the parentheses first. Use that value as the first input to the outer operation.
def star(a, b):
return 2 * a + b ** 2
inner = star(1, 2) # 2(1) + 2^2 = 6
result = star(inner, 3) # 2(6) + 3^2 = 21
print(inner, result)Exercise
If a★b = 2a + b², what is (-1)★(1/2)?
Show answer
2(-1) + (1/2)² = -2 + 1/4 = -7/4.