Advertisement
gruntfutuk

string merges

Oct 24th, 2019
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. from random import choice, randint
  2. from string import ascii_lowercase
  3.  
  4.  
  5. def create_strs(num=5, low=3, high=6):
  6.     "return list of two-string tuples with <num> elements"
  7.     "strings formed as per the new_str function"
  8.  
  9.     def new_str():
  10.         "return string consisting of a lower case letter repeated"
  11.         "a random number of times (between <low> and <high>)"
  12.         return choice(ascii_lowercase) * randint(low, high)
  13.  
  14.     return [(new_str(), new_str()) for _ in range(randint(5, 10))]
  15.  
  16.  
  17. def balance(alpha, beta):
  18.     "return string of whichever is longer of <alpha> or <beta>"
  19.     "that constitutes the substring of the longer part"
  20.     "(return empty string if same length)"
  21.     len_alpha = len(alpha)
  22.     len_beta = len(beta)
  23.     if len_alpha < len_beta:
  24.         return beta[len_alpha:]
  25.     elif len_beta < len_alpha:
  26.         return alpha[len_beta:]
  27.     else:
  28.         return ""
  29.  
  30.  
  31. source = create_strs(20)  # list of 20 tuples of random strings
  32. for first, second in source:
  33.     merged = "".join(
  34.         [letter for letter_pair in zip(first, second) for letter in letter_pair]
  35.     ) + balance(first, second)
  36.     print(f"{merged:12} {len(merged):2}: {len(first)} + {len(second)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement