Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python3
- from random import randint as rnd
- # Task: make a function that takes zero to three arguments. Each
- # argument may be either an integer or a string. The function must
- # either sum or concatenate its arguments.
- def aoc(*args):
- # a list for results
- res = []
- # check if any of the arguments are strings
- string_flag = any(map((lambda x: type(x) == str), args))
- # if some arguments are strings
- if string_flag:
- # iterate through the arguments
- for arg in args:
- # check if the argument is an integer, which in this case
- # it shouldn't be
- if type(arg) == int:
- # convert to a string and append to the list of results
- res.append(str(arg))
- else:
- # or just append to the list of results
- res.append(arg)
- # turn the result list into a string by interspersing its
- # items with an empty string and concatenating the sequence
- return "".join(res)
- # if all arguments are integers, just sum them
- else:
- return sum(args)
- ####### Testing #######
- # Patterns for combining integers and strings are binary
- # representations of numbers 2 to 16 with the first digit
- # removed: '0', '1', '00', '01', '10', '11', '000', '001', '010',
- # '011', '100', '101', '110', '111'
- cp = [bin(i)[3:] for i in range(2, 16)]
- for combination in cp:
- # Depending on the combination every item is either a random
- # number 0 to 9 or a random ASCII character with a decimal code 97
- # to 122, i.e. any character within the range 'a' to 'z'
- args = [rnd(0, 9) if i == '0' else chr(rnd(97, 122)) for i in combination]
- # a list with an asterisk as an argument gets split into separate
- # items which are viewed by a function as separate arguments
- print(args, "-->", aoc(*args))
- # [5] --> 5
- # ['x'] --> x
- # [8, 2] --> 10
- # [3, 'd'] --> 3d
- # ['z', 8] --> z8
- # ['w', 'i'] --> wi
- # [2, 5, 2] --> 9
- # [5, 3, 'f'] --> 53f
- # [5, 'h', 7] --> 5h7
- # [7, 'g', 'n'] --> 7gn
- # ['t', 8, 8] --> t88
- # ['b', 5, 'r'] --> b5r
- # ['b', 'd', 8] --> bd8
- # ['h', 'p', 'w'] --> hpw
Add Comment
Please, Sign In to add comment