-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyboard_shortcut.py
68 lines (56 loc) · 2.23 KB
/
keyboard_shortcut.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import unittest
# Weekly Challenge November 5, 2024
# Ctrl + C, Ctrl + V
# Given a sentence containing few instances of "Ctrl + C" and "Ctrl + V",
# return the sentence after those keyboard shortcuts have been applied!
#
# "Ctrl + C" will copy all text behind it.
# "Ctrl + V" will do nothing if there is no "Ctrl + C" before it.
# A "Ctrl + C" which follows another "Ctrl + C" will overwrite what it copies.
#
# Notes
# Keyboard shortcut commands will appear like normal words in a sentence but shouldn't be copied themselves (see example #2).
# Pasting should add a space between words.
def keyboard_shortcut(sentence: str) -> str:
clipboard = None
words = sentence.split()
new_sentence = []
in_command = False
for i, word in enumerate(words):
# If we are in the middle of a command, ignore the coming parts.
if in_command and word in ["C", "V", "+"]:
# C/V are the last parts so we exit command mode.
if word in ["C", "V"]:
in_command = False
continue
if word == "Ctrl":
in_command = True
# The actual command is two words ahead (skip the + sign)
command = words[i + 2]
if command == "C":
# Update the clipboard with a copy of what we have so far.
clipboard = new_sentence[:]
elif command == "V":
# If there's anything in our clipboard, extend our sentence with it.
if clipboard:
new_sentence.extend(clipboard)
else:
new_sentence.append(word)
return " ".join(new_sentence)
class KeyboardShortcutTest(unittest.TestCase):
def test_keyboard_shortcut(self) -> None:
self.assertEqual(
keyboard_shortcut("the egg and Ctrl + C Ctrl + V the spoon"),
"the egg and the egg and the spoon",
)
self.assertEqual(
keyboard_shortcut("WARNING Ctrl + V Ctrl + C Ctrl + V"), "WARNING WARNING"
)
self.assertEqual(
keyboard_shortcut("The Ctrl + C Ctrl + V Town Ctrl + C Ctrl + V"),
"The The Town The The Town",
)
if __name__ == "__main__":
unittest.main()