Home > database >  Difficulty creating random words under conditions
Difficulty creating random words under conditions

Time:06-13

I need k words to be generated, until the sum of all the characters that make up the list is equal to or greater than 25

    import random
    for x in range(k): 
        n=("a","b","c","d")
        cc=[''.join(random.choice(n) for _ in range(random.choice(range(2,5))))]
        print(cc)

    def sumt(input1):

        l = list(input1)
        total = sum(len(i) for i in l)
        return int(total)

    print(sumt([cc]))

CodePudding user response:

You can have a for loop if you have a variable amount of iteration to do

Have a method that generate a word, then call until you reach the good total length

chars = "abcd"

def new_word():
    return ''.join(random.choice(chars) for _ in range(random.choice(range(2, 5))))

def generate(total_length):
    result = []
    result_length = 0
    while result_length < total_length:
        result.append(new_word())
        result_length  = len(result[-1])  # sum with len of last word
    return result

x = generate(25)
print(x)

CodePudding user response:

If I understand, you want to build a list of words until the sum of all characters is >= 25? I prefer using classes...

import random

class WordList:
  def __init__(self):
    self.choices = ['a','b','c','d']
    self.threshold = 25
    self.char_sum = 0
    self.lst = []   

    self.build_list()
    
  def build_list(self):
    '''Build a list of words until sum of all chars
    meets or exceeds the threshold.
    '''
    while self.char_sum < self.threshold:
      self.generate_word()
      self.char_sum = sum(len(i) for i in self.lst)

  def generate_word(self):
    '''Generate a single word with 2 to 5 characters.
    '''
    _word = ''.join(random.choice(self.choices) for _ in range(random.choice(range(2,5))))
    self.lst.append(_word)

Usage:

new_list = WordList().lst
print(new_list)
  • Related