ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def f(n):
out = []
while n:
n, r = divmod(n, -2)
if r < 0:
n, r = n + 1, r + 2
out.append(str(r))
return "".join(reversed(out)) or "0"
print(f(6), f(-3), f(0))- A. 11010 1101 0
- B. 110 1101 0
- C. 11010 11 0
- D. 11010 1101
Correct answer: A. 11010 1101 0
This converts to base -2, fixing negative remainders. 6 = 16 - 8 - 4 + 2 = 11010 and -3 = -8 + 4 + 1 = 1101 in negabinary. For 0 the loop never runs and the `or` supplies '0'.
More Python Programming questions
- What is printed? python def gen(n): if n == 0: yield "" return for s in gen(n - 1): yield s + "0" if not s.endswith("1"): yield s + "1"…
- What is printed? python cache = {} def ways(n): if n < 0: return 0 if n == 0: return 1 if n not in cache: cache[n] = ways(n - 1) + ways(n…
- What is printed? python def perms(s): if len(s) <= 1: return [s] out = [] for i, c in enumerate(s): for p in perms(s[:i] + s[i + 1:])…
- What is printed? python def makeops(): ops = {} for name, sym in [("add", "+"), ("mul", "")]: ops[name] = eval(f"lambda a, b: a {sym} b")…
- What is printed? python x = 1 def f(): return x def g(): x = 2 return f() def h(): global x x = 3 return f() print(g(), h(), f())
- What is printed? python class Celsius: def init(self, t=0): self.t = t def get(self, obj, owner): return self if obj is None else obj.c…