Strings
a. Given a string s, return a new string made of all the chars from s which are 'd' or 'o' or 'g' (not case sensitive).
'xdxggy' -> 'dgg' | def doggy(s):
'DOggy' -> 'DOgg' |
'abdGxo' -> 'dGo' |
'xyz' -> '' |
View solution
def doggy(s):
result = ''
for ch in s: # for/i/range also fine
low = ch.lower()
if low == 'd' or low == 'o' or low == 'g':
result += ch
return result
Preserve each matching character’s original case; use lowercase only for the comparison.
b. Given a string s. Find the first '@' in s. If there is a digit 3 chars after the '@', such as the '6' in 'x@106', then return the numeric value of that digit doubled. If there is no '@' or no digit, then return -1. Use the s.find() function.
'x@106x' -> 12 | def digit2x(s):
'xx@ab51' -> 10 |
'x@abx' -> -1 |
'abc@' -> -1 |
'abc' -> -1 |
View solution
def digit2x(s):
at = s.find('@')
if at == -1:
return -1
if at + 3 < len(s) and s[at + 3].isdigit():
return int(s[at + 3]) * 2
return -1
Check that @ exists and the target index is in bounds before reading the character.
c. Given a string s, find the first double left-bracket '[[' in s, and the first double right-bracket ']]'. If the double left-brackets are before the double right-brackets, then return a new string where the text between the brackets is replaced by the string 'NOPE'. If the left or right double brackets are missing or they are in the wrong order, then return the empty string. Do not use loops. Use s.find() and slices.
'xx[[hi there!]]zzz' -> | def nope(s):
'xx[[NOPE]]zzz' |
'a[[]]b' -> 'a[[NOPE]]b' |
'xx[[abc' -> '' |
'xx]]abc' -> '' |
'x]]ab[[' -> '' |
View solution
def nope(s):
left = s.find('[[')
right = s.find(']]')
if left == -1 or right == -1:
return ''
# Right before left = wrong order
if right < left:
return ''
# Slice for each side, 'NOPE' in the middle!
return s[:left + 2] + 'NOPE' + s[right:]
Reject missing or reversed delimiters; keep both brackets when joining the slices.