Exercises with tuples

Exercises with tuples#

Exercise - joined#

✪✪ Write a function which given two tuples of characters ta and tb having each different characters (may also be empty), return a tuple made like this:

  • if the tuple ta terminates with the same character tb begins with, RETURN the concatenation of ta and tb WITHOUT the join character duplicated.

  • otherwise RETURN an empty tuple

Hide code cell content
def joined(ta,tb):
    if len(ta) > 0 and len(tb) > 0:
        if ta[-1] == tb[0]:
            return ta[:-1] + tb

    return ()
assert joined(('a','b','c'), ('c','d','e','e','f')) == ('a', 'b', 'c', 'd', 'e','e','f')
assert joined(('a','b'), ('b','c','d')) == ('a', 'b', 'c', 'd')
assert joined((),('e','f','g')) == ()
assert joined(('a',),('e','f','g')) == ()
assert joined(('a','b','c'),()) == ()
assert joined(('a','b','c'),('d','e')) == ()
joined(("a", "b", "c"), ("c", "d", "e", "e", "f")), joined(("a", "b"), ("b", "c", "d"))
(('a', 'b', 'c', 'd', 'e', 'e', 'f'), ('a', 'b', 'c', 'd'))

nasty#

✪✪✪ Given two tuples ta and b, ta made of characters and tb of positive integer numbers , write a function nasty which RETURNS a tuple having two character strings: the first character is taken from ta, the second is a number taken from the corresponding position in tb. The strings are repeated for a number of times equal to that number.

Hide code cell content
def nasty(ta, tb):
    i = 0
    ret = []
    while i < len(tb):
        s = ta[i]+str(tb[i])    
        ret.extend( (s,) * tb[i] )
        i += 1
    return tuple(ret)
nasty(("u", "r", "g"), (4, 2, 3)), nasty(("g", "a", "s", "p"), (2, 4, 1, 3))
(('u4', 'u4', 'u4', 'u4', 'r2', 'r2', 'g3', 'g3', 'g3'),
 ('g2', 'g2', 'a4', 'a4', 'a4', 'a4', 's1', 'p3', 'p3', 'p3'))
assert nasty(('a',), (3,)) == ('a3','a3','a3')
assert nasty(('a','b'), (3,1)) == ('a3','a3','a3','b1')
assert nasty(('u','r','g'), (4,2,3)) == ('u4', 'u4', 'u4', 'u4', 'r2', 'r2', 'g3', 'g3', 'g3')
assert nasty(('g','a','s','p'), (2,4,1,3)) == ('g2', 'g2', 'a4', 'a4', 'a4', 'a4', 's1', 'p3', 'p3', 'p3')