A shift register moves its bits one place at every clock edge, and takes a new bit in at one end. It turns a serial stream of bits into parallel bits.
What to build
Simulate a serial-in shift register that shifts to the left, and print its contents after every clock.
Requirements
- The new bit enters at the right end (the least significant bit). The leftmost bit is lost.
- Print the register as a string of
0and1after each clock, one line per clock.
Input
The first line has the starting contents of the register, as a string of bits. The second line has the serial input bits as one string, one bit for each clock.
Output
One line for each clock: the register contents.
Constraints
The register has 2 to 8 bits. There are 1 to 12 clocks.
Example
Input:
0000
1011
Output:
0001
0010
0101
1011
Why it works
In a real shift register every flip-flop copies the output of its neighbour at the same clock edge, so all bits move by one place together. Shifting left by one is also multiplication by 2 for the bits that are left: the new bit is the new low bit.
Examples
0000 1011
0001 0010 0101 1011
1111 000
1110 1100 1000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the register as a string. Shifting left drops the first character and adds the new bit at the end: reg = reg[1:] + bit.
Hint 2
Print the register after every clock.
Hint 3
The serial input is read one bit per clock, from left to right.
Solution
Show one correct solution (try it yourself first)
reg = input().strip()
bits = input().strip()
for b in bits:
reg = reg[1:] + b
print(reg)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step