banovski

Sum or concatenate

Mar 19th, 2022 (edited)
642
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. #! /usr/bin/env python3
  2.  
  3. from random import randint as rnd
  4.  
  5. # Task: make a function that takes zero to three arguments. Each
  6. # argument may be either an integer or a string. The function must
  7. # either sum or concatenate its arguments.
  8.  
  9. def aoc(*args):
  10.     # a list for results
  11.     res = []
  12.     # check if any of the arguments are strings
  13.     string_flag = any(map((lambda x: type(x) == str), args))
  14.     # if some arguments are strings
  15.     if string_flag:
  16.         # iterate through the arguments
  17.         for arg in args:
  18.             # check if the argument is an integer, which in this case
  19.             # it shouldn't be
  20.             if type(arg) == int:
  21.                 # convert to a string and append to the list of results
  22.                 res.append(str(arg))
  23.             else:
  24.                 # or just append to the list of results
  25.                 res.append(arg)
  26.         # turn the result list into a string by interspersing its
  27.         # items with an empty string and concatenating the sequence
  28.         return "".join(res)
  29.     # if all arguments are integers, just sum them
  30.     else:
  31.         return sum(args)
  32.  
  33. ####### Testing #######
  34.  
  35. # Patterns for combining integers and strings are binary
  36. # representations of numbers 2 to 16 with the first digit
  37. # removed: '0', '1', '00', '01', '10', '11', '000', '001', '010',
  38. # '011', '100', '101', '110', '111'
  39. cp = [bin(i)[3:] for i in range(2, 16)]
  40.  
  41. for combination in cp:
  42.     # Depending on the combination every item is either a random
  43.     # number 0 to 9 or a random ASCII character with a decimal code 97
  44.     # to 122, i.e. any character within the range 'a' to 'z'
  45.     args = [rnd(0, 9) if i == '0' else chr(rnd(97, 122)) for i in combination]
  46.  
  47.     # a list with an asterisk as an argument gets split into separate
  48.     # items which are viewed by a function as separate arguments
  49.     print(args, "-->", aoc(*args))
  50.  
  51. # [5] --> 5
  52. # ['x'] --> x
  53. # [8, 2] --> 10
  54. # [3, 'd'] --> 3d
  55. # ['z', 8] --> z8
  56. # ['w', 'i'] --> wi
  57. # [2, 5, 2] --> 9
  58. # [5, 3, 'f'] --> 53f
  59. # [5, 'h', 7] --> 5h7
  60. # [7, 'g', 'n'] --> 7gn
  61. # ['t', 8, 8] --> t88
  62. # ['b', 5, 'r'] --> b5r
  63. # ['b', 'd', 8] --> bd8
  64. # ['h', 'p', 'w'] --> hpw
  65.  
Add Comment
Please, Sign In to add comment