NumPy's integer types have a fixed size, and results that do not fit wrap around silently. Model int8, uint8 and int16 arithmetic.
What to build
A program that runs a sequence of operations in a fixed-size integer type.
Requirements
- Line 1 names the type:
int8(-128 to 127),uint8(0 to 255) orint16(-32768 to 32767). Line 2 is the starting value, wrapped into the type. - Each following operation is
+ K,- Kor* K; apply it and wrap the result. Print the value after each operation, and(wrapped)after it when the true result did not fit.
Input
Line 1: the type. Line 2: the start. Line 3: n. Then n operations.
Output
n lines.
Constraints
1 ≤ n ≤ 30; |K| ≤ 10^5; the start is a whole number with |x| ≤ 10^5.
Example
Input:
int8
100
3
+ 27
+ 1
- 1
Output:
127
-128 (wrapped)
127 (wrapped)
Why it works
The array keeps only the lowest bits of each result, which is the same as taking it modulo 2 to the number of bits and shifting signed types into their range; NumPy does not check, so the wrap is silent.
Examples
int8 100 3 + 27 + 1 - 1
127 -128 (wrapped) 127 (wrapped)
uint8 250 2 + 10 - 5
4 (wrapped) 255 (wrapped)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For a signed type of b bits: wrap(x) = (x + 2^(b-1)) mod 2^b - 2^(b-1). For unsigned: x mod 2^b.
Hint 2
Apply the wrap after every operation, as NumPy stores every result in the array's type.
Solution
Show one correct solution (try it yourself first)
RANGES = {"int8": (8, True), "uint8": (8, False), "int16": (16, True)}
def wrap(x, bits, signed):
size = 2**bits
if signed:
return (x + size // 2) % size - size // 2
return x % size
kind = input()
bits, signed = RANGES[kind]
value = wrap(int(input()), bits, signed)
n = int(input())
for _ in range(n):
op, k = input().split()
k = int(k)
exact = value + k if op == "+" else value - k if op == "-" else value * k
value = wrap(exact, bits, signed)
print(value, "(wrapped)" if value != exact else "")