Source
Girl Develop It San Francisco,
Teaching Materials,
Exercises: Strings: MixUp
Description
Given two strings s1
and s2
and an integer n
, swap the first n
characters of s1
and s2
and concatenate the results, separated by
a space. If either string is less than or equal to n
characters in
length, return them unmodified but concatenated, separated by a space.
1
2
| 'foo', 'bar', 3 ⟹ 'foo bar'
'foobar', 'bazqux', 3 ⟹ 'bazbar fooqux'
|
My solution
1
2
3
4
| def headswap(s1, s2, n):
short = len(s1) <= n or len(s2) <= n
swap = lambda a, b: f'{a[:n]}{b[n:]}'
return f'{s1} {s2}' if short else f'{swap(s2, s1)} {swap(s1, s2)}'
|
Tests
1
2
3
4
5
6
7
8
9
10
| import pytest
from headswap import *
def test_headswap_nomod():
"""Should leave strings unmodified."""
assert headswap('foo', 'bar', 3) == 'foo bar'
def test_headswap_mod():
"""Should modify strings."""
assert headswap('foobar', 'bazqux', 3) == 'bazbar fooqux'
|