Reputation: 11
I need help with solving a problem. I have list of 8 words.
What I need to achieve is to generate all possible variants where exactly 3 of this words are included. All those variants need to be saved in different .txt file. The same words but in different positions should be treated as another variant.
It needs to be done on Raspberry Pi in Python.
To be honest i don't even know where to start with it...
I am total noob in any sort of programming...
Any clues how to do it?
Upvotes: 0
Views: 85
Reputation: 820
@lmiguelvargasf's answer only covers half the question, so here comes the part where you save the word combinations to individual files.
import itertools
import random
import string
class fileNames:
def __init__(self):
self.file_names = []
def randomString(self,stringLength):
letters = string.ascii_lowercase
file_name = ''.join(random.choice(letters) for i in range(stringLength))
if file_name in self.file_names:
randomString(stringLength)
self.file_names.append(file_name)
return file_name
# Original word list
l = [1, 2, 3]
# Create a new list, containing the combinations
word_combinations = list(itertools.permutations(l, 3))
# Creating an instance of fileNames() class
files = fileNames()
# Specifying the number of characters
n = 5
# For each of these combinations, save in a file
for word_comb in word_combinations:
# The file will be named by a random string containing n characters
with open('{}.txt'.format(files.randomString(n)), 'w') as f:
# The file will contain each word seperated by a space, change the string below as desired
f.write('{} {} {}'.format(word_comb[0], word_comb[1], word_comb[2]))
If you want the filename to be an integer which increases with 1 for every file, do swap the last part with this:
# For each of these combinations, save in a file
for n, word_comb in enumerate(word_combinations):
# The file will be named by an integer
with open('{}.txt'.format(n), 'w') as f:
# The file will contain each word seperated by a space, change the string below as desired
f.write('{} {} {}'.format(word_comb[0], word_comb[1], word_comb[2]))
Upvotes: 2
Reputation: 69655
You can easily solve this problem by using itertools
. In the following example, I will produce all possible combinations of 3 elements for the list l
:
>>> import itertools
>>> l = [1, 2, 3, 4, 5]
>>> list(itertools.permutations(l, 3))
[(1, 2, 3),
(1, 2, 4),
(1, 2, 5),
(1, 3, 4),
(1, 3, 5),
(1, 4, 5),
...
...
(2, 3, 4),
(2, 3, 5),
(2, 4, 5),
(3, 4, 5),
...
...
(5, 4, 2),
(5, 4, 3)]
Now, if you want to save those values in a different text file, you should do the following:
for i, e in enumerate(itertools.permutations(l, 3)):
with open(f"file_{i}.txt","w+") as f:
f.write(e)
Upvotes: 7
Reputation:
try using random.choice()
import random
# your code
word = []
for x in range(0, 7)
word.add(random.choice(words))
file.write(word)
repeat everything after word = []
using a for loop and you can even check if theyre the same using a method described here
Upvotes: 0