Confused, help, tell me

The task of the code is to write a 3 letter word that will not be repeated in the list.

import random z = 0 def listSec(s): listSec = '' listSec = listSec + s + '\n' return listSec listToPrint = '' while z < 160: sec = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(3)) for i in range(len(listToPrint)): if sec != listToPrint[i]: print (z) listToPrint += listSec(sec) z += 1 def equal(s, listReit = '', a = 0): for i in range(len(s)): print (i) if s[i] == s[i + 1]: print(s[i]) a = a + 1 listReit = listReit + s[i] print ('reiterative: %s' % (s[i])) return a, listReit print ('Value reiterative: %s, \nlist: %s' % (a, listReit)) #equal(listToPrint) print (listToPrint) 

Now the console just hangs without any response.

upd:

 import random z = 0 def listSec(s): listSec = '' listSec = listSec + s + '\n' return listSec listToPrint = [] while z < 160: sec = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(3)) a = 0 while a < 1: listToPrint += listSec(sec) a = a + 1 for i in range(len(listToPrint)): k = i + 1 if listSec[i] != listSec[k]: print (z) listToPrint += listSec(sec) z += 1 print (listToPrint) input('press key for exit') 
  • one
    len(listToPrint) = 0 , therefore, you do not enter the for i in range(len(listToPrint)) loop for i in range(len(listToPrint)) and the variable z remains zero. - mkkik
  • If you need to generate a lot of words and performance matters, you can generate and break up many random bytes at a time, adding to the set and repeating the process until the required number of words is generated, sample code demonstrating several optimization tricks - jfs
  • If you want to use these lines in passwords or similar things, use random.SystemRandom() or os.urandom() directly instead of random.Random() , which is the default. See, also secrets module - jfs

1 answer 1

 import random, string listToPrint = set() while len(listToPrint) < 160: listToPrint.add(''.join(random.choice(string.ascii_lowercase) for i in range(3))) print(listToPrint) 

create file:

 import os path = 'logs' for num, name in enumerate(os.listdir(path)): name_, _ext = os.path.splitext(name) print(num, name) n = [name_, num.__repr__(), _ext] print(n) newfile = os.path.join(path, ''.join(n)) with open(newfile, 'w') as f: data = open(os.path.join(path, name)) f.write(data.read()) 

out:

 0 asd.log ['asd', '0', '.log'] 1 qwe.log ['qwe', '1', '.log'] 2 zxc.log ['zxc', '2', '.log'] 
  • I will gamble: in the original question the letter a is not used in the generated words :) - andreymal
  • need no repetitions! Mandatory check for repetitions - ALPHA
  • @ALPHA no repetitions!, Read about the data type set. - vadim vaduxa
  • @vadimvaduxa, thanks for the info about the set! - ALPHA
  • Maybe even tell me how best to read the name of the file in the folder, add + 1 to the name (name -> name1) and create the file? - ALPHA