I am able to make one anagram via this code
import random
x = input()
x = list(x)
random.shuffle(x)
y = "".join(x)
print(y)
but I dont know how to specife how many times it should generate anagram.
You could use a while loop so that once you have entered your word and recieved the anagram, the program asks whether you want another anagram. This process continues after you tell it to stop by typing 'n' when it asks if you would like to repeat the process.
Here is the code:
import random
while True:
question = input('\nYour Word: ')
question = list(question)
random.shuffle(question)
y = "".join(question)
print('Your Output is: ',y)
question2 = input('\nWould you like to repeat this process with a different word? ')
if question2 == 'n':
print('Ok. Thanks for using this anagram maker :D')
break
I would say create a function which takes in 2 inputs(x, the letters and num, the number of anagrams you want to generate). Within that function I would do this:
import random
def generateAnagrams(x, num):
anagrams = []
for i in range(num):
random.shuffle(x)
y = "".join(x)
anagrams.append(y)
print(anagrams)
If you want to call the function, just do this:
x = input()
x = list(x)
#Set num to an int that is the number of anagrams you want
num = 3
generateAnagrams(x, num)
It's important to take into consideration the possibility that the input word has duplicate letters, so just using permuatations is not enough -- you need to remove the duplicate permutations and the original word, which is included among the permutations:
import itertools
def anagram(word):
s = set(itertools.permutations(word)) - set([tuple(word)])
return [''.join(permutation) for permutation in s]
print(anagram('ass'))
print(anagram('ready'))
Prints:
['sas', 'ssa']
['yarde', 'yaedr', 'yadre', 'yader', 'edayr', 'edyar', 'yeard', 'erady', 'erday', 'eardy', 'eadry', 'dyrae', 'dyare', 'ardye', 'aryde', 'yerda', 'yedra', 'earyd', 'eayrd', 'edray', 'edary', 'aydre', 'rdeay', 'eyrda', 'eydra', 'rdaey', 'adeyr', 'adyer', 'aredy', 'ardey', 'yared', 'yaerd', 'daeyr', 'dayer', 'dyrea', 'edrya', 'edyra', 'dyera', 'rdyea', 'eyadr', 'eydar', 'rdeya', 'rydae', 'eadyr', 'eaydr', 'draye', 'dryae', 'rdaye', 'rdyae', 'ayder', 'redya', 'reyda', 'reday', 'ayedr', 'aeryd', 'aeyrd', 'raeyd', 'rayed', 'erdya', 'eryda', 'ydear', 'ydaer', 'adrey', 'adery', 'dreya', 'dryea', 'derya', 'deyra', 'darey', 'daery', 'yrade', 'yrdae', 'radey', 'raedy', 'erayd', 'eryad', 'dyear', 'dyaer', 'dreay', 'draey', 'adrye', 'adyre', 'aerdy', 'deray', 'deary', 'yerad', 'areyd', 'aryed', 'aedyr', 'aeydr', 'ayrde', 'ayred', 'ayerd', 'radye', 'rayde', 'yeadr', 'yedar', 'yreda', 'yrdea', 'ryeda', 'rydea', 'eyrad', 'eyard', 'darye', 'dayre', 'ydrea', 'ydera', 'ryead', 'ryaed', 'yread', 'yraed', 'deyar', 'deayr', 'ydrae', 'ydare', 'reyad', 'ryade', 'aedry', 'reayd']
This generates all the anagrams of the original word. You can select one or all of these.
Try this:
from itertools import permutations
for anagram in permutations("abcd"):
print("".join(anagram))
It generates all anagrams for a given word. To specify how many times you would like it to generate a new anagram, do this:
from itertools import permutations
n_anagrams = 3
all_anagrams = ["".join(anagram) for anagram in permutations("abcd")]
print(all_anagrams[:n_anagrams])
Hope you can find this piece of code useful.
Related
from easygui import *
from time import *
from statedict import *
import random
correctnum = 0
questionsanswered = 0
print("Indian Map Quiz v1")
sleep(0.5)
print("Note all features might not work correctly, this is a work in progress.")
msgbox("Welcome to Indian Map Quiz", "INDIA", "Continue")
title = "Guess The State"
msg = "What Indian state is this?"
stateFactList = [APdict, ARdict, ASdict, BRdict, CTdict, GAdict, GJdict, HPdict, HRdict, JHdict,
KAdict, KLdict, MHdict, MLdict, MNdict, MPdict, MZdict, NLdict, ODdict, PBdict,
RJdict, SKdict, TGdict, TNdict, TRdict, UPdict, UTdict, WBdict]
stateID = random.choice(stateFactList)
print(stateID["state"])
stateQuestion = buttonbox(msg=msg, title=title, choices=stateID["choices"], image=stateID["image file"])
if stateQuestion == stateID["correct"]:
print("it's correct")
correctnum += 1
questionsanswered += 1
else:
print("incorrect")
questionsanswered += 1
Here is the code, essentially when you run the program, it should randomly pick a state and provide some multiple choice answers based on the state. It randomly picks a state from the stateFactlist list and matches it with a dictionary stored in another file. Whenever the user answers a question, I want it to generate a new, random state to be displayed to the user, along with the respective multiple choice answers, but I can't find a way to implement it. Help is appreciated.
To help clear up the confusion, random.sample() includes a parameter, k, which lets you specify the number of unique elements to randomly choose from the specified sequence. It can work well for what OP has in mind. Here is a simplified example for illustration purposes:
import random
arr = ["A", "B", "C", "D"]
for x in random.sample(arr, k=len(arr)):
print(x)
Output:
C
D
A
B
EDIT: In response to OP's question on how to implement this in their code, here is a rough approximation. The key is to move the state Q&A code inside of a loop that is iterating (in random order) over stateFactList. Note, I wasn't able to run this code since I don't have access to OP's data structures or GUI library, so take it as a rough guide, not working code.
stateFactList = [APdict, ARdict, ASdict, BRdict, CTdict, GAdict, GJdict, HPdict, HRdict, JHdict,
KAdict, KLdict, MHdict, MLdict, MNdict, MPdict, MZdict, NLdict, ODdict, PBdict,
RJdict, SKdict, TGdict, TNdict, TRdict, UPdict, UTdict, WBdict]
for stateID in random.sample(stateFactList, k=len(stateFactList)): # iterate over stateFactList in random order
msg = "What Indian state is this?"
# This statement no longer needed
# stateID = random.choice(stateFactList)
print(stateID["state"])
stateQuestion = buttonbox(msg=msg, title=title, choices=stateID["choices"], image=stateID["image file"])
if stateQuestion == stateID["correct"]:
print("it's correct")
correctnum += 1
questionsanswered += 1
else:
print("incorrect")
questionsanswered += 1
Just shuffle the list, then iterate normally.
randome.shuffle(stateFactList)
for state in stateFactList:
...
you can remove the already picked element from the list for fair share
Like below example:
>>> a = [1,2,3,4,5]
>>> choice = random.choice(a)
>>> choice
4
>>> a.remove(a.index(choice)) # removes 4 from the list
>>> a
[1, 2, 4, 5]
>>> choice = random.choice(a)
>>> choice
2
import random
quizwords = [["hot", "cold"],["summer","winter"],["hard","soft"],["dry","wet"],["simple","complex"],["light","darkness"],["weak","strong"],["male","female"],["sad","happy"],["win","lose"],["small","big"],["ignore","pay attention"],["sell","buy"],["succeed","fail"],["reject","accept"],["prevent","allow"],["exclude","include"]]
c = 0
random.shuffle(quizwords)
for i in quizwords:
print(i[0][0],"is to",i[0][1],"as",i[1][0],"is to...")
ans = input()
This is my code so far and I believe it would for example output 'e is to c as s is to...'
im trying to have it instead say 'exclude is to include as reject is to...(answer: accept)'
import random
quizwords = [["hot", "cold"],["summer","winter"],["hard","soft"],["dry","wet"],["simple","complex"],["light","darkness"],["weak","strong"],["male","female"],["sad","happy"],["win","lose"],["small","big"],["ignore","pay attention"],["sell","buy"],["succeed","fail"],["reject","accept"],["prevent","allow"],["exclude","include"]]
c = 0
random.shuffle(quizwords)
for i in range(len(quizwords) - 1)[::2]:
first_pair = quizwords[i]
second_pair = quizwords[i+1]
print(f'{first_pair[0]} is to {first_pair[1]} as {second_pair[0]} is to...')
ans = input()
Since you're already iterating through items in the list in the for-loop, doing two levels of indexing was pulling the first letter of each word.
I'm trying to implement the following "game" in python:
Given a start word, find the goal word with modifications
allowed modification per step: remove or add any letter and permute
The task is to find the way from start to goal with the least steps.
My approach was to add/remove a letter, permute the resulting letters and look up each permutant in a dictionary.
This quickly results in long run times (for a 9-letter word and the first step approx 60sec).
Here is my code.
import time
from itertools import permutations
startword = 'croissant'
nodes = list()
nodes.append(startword)
dicts = set([line.rstrip('\n') for line in open('wordList.txt')])
alpha = set([chr(i) for i in range(ord('a'),ord('z')+1)])
def step(nodes):
nnodes = list()
for word in nodes:
for s in word:
new_word = word.replace(s, '', 1)
perms = [''.join(p) for p in permutations(new_word)]
for per in perms:
if per in dicts:
nnodes.append(per)
for s in alpha:
new_word = word + s
perms = [''.join(p) for p in permutations(new_word)]
for per in perms:
if per in dicts:
nnodes.append(per)
return set(nnodes)
btime = time.time()
step(nodes)
print time.time() - btime
How can I improve the performance/logic? We are specifically asked to use a breadth first search.
Interesting question! There is a way that you can dramatically improve the performance. Instead of checking each new word by traversing through the wordlist and checking if it is present, you can alphabetize the characters for each word in the wordlist and compare those directly to the alphabetized shortened/lengthened word of interest.
For example using croissant, I can alphabetize the characters to generate acinorsst instead. Then, I check to see if acinorsst with a character removed or added is in a defaultdict of lists where the keys are alphabetized strings and retrieve the corresponding value (which is the list of actual words corresponding to that alphabetical ordering).
It is much less confusing to explain in code, so I have posted it below:
from collections import defaultdict
import itertools as its
import time
def get_alpha_dicts():
wa_dict = {}#word: alphabetized dict
aw_dict = defaultdict(list)#alphabetized: corresponding WORDS dict
for line in open('wordList.txt'):
word = line.rstrip('\n')
alpha_word = ''.join(sorted(word))
wa_dict[word] = alpha_word
aw_dict[alpha_word].append(word)
return wa_dict, aw_dict
def step(nodes, aw_dict):
alpha = set([chr(i) for i in range(ord('a'),ord('z')+1)])
nnodes = list()
for word in nodes:
alpha_word = ''.join(sorted(word))
#remove a char from word
short_words = set([''.join(w) for w in its.combinations(alpha_word, len(start_word)-1)])
for short_word in short_words:
nnodes.extend(aw_dict[short_word])
#add a char to word
long_words = [''.join(sorted(alpha_word + s)) for s in alpha]
for long_word in long_words:
nnodes.extend(aw_dict[long_word])
return set(nnodes)
if __name__ == "__main__":
start_word = 'croissant'
nodes = list()
nodes.append(start_word)
wa_dict, aw_dict = get_alpha_dicts()
btime = time.time()
print step(nodes, aw_dict)
print time.time() - btime
Hope it helps!
I made my own Python code like this:
import random
# nouns-----------------------------------------------------------------------------------------------------------------
nouns = 'noun1 noun2 noun3 noun4 noun5 noun6 noun7 noun8 noun9 noun10 noun11 noun12 noun13 noun14 noun15 noun16' .split()
def getRandomWord(nounList):
wordIndex = random.randint(0, len(nounList) - 1)
return nounList[wordIndex]
noun_var = getRandomWord(nouns)
# verbs-----------------------------------------------------------------------------------------------------------------
verbs = 'verb1 verb2 verb3 verb4 verb5 verb6 verb7 verb8 verb9 verb10 verb11 verb12 verb13 verb14 verb15 verb16' .split()
def getRandomWord(verbList):
wordIndex = random.randint(0, len(verbList) - 1)
return verbList[wordIndex]
verb_var = getRandomWord(verbs)
# infinitives-----------------------------------------------------------------------------------------------------------
infi = 'verb1 verb2 verb3 verb4 verb5 verb6 verb7 verb8 verb9 verb10 verb11 verb12 verb13 verb14 verb15 verb16' .split()
def getRandomWord(infiList):
wordIndex = random.randint(0, len(infiList) - 1)
return infiList[wordIndex]
infi_var = getRandomWord(infi)
# print strings
for i in range(1):
print (noun_var, verb_var, infi_var)
But whenever I wanted to change the 1 in "Line 25, Char 16" into an input variable letting you be able to make the choice of how many sentences wanted, it just repeats the same sentence again and again instead of generating new ones. Is there another way to make an app with Python with the same principles or is there a way to fix this?
This code is in Python-3.x
If you want to display a different sentence in each iteration of your loop, then generate a new sentence. Right now you're picking 3 random words, and then printing them over and over again.
for i in range(int(input())):
print (random.choice(nouns), random.choice(verbs), random.choice(infi))
I'm setting up a simple sentence generator in python, to create as many word combinations as possible to describe a generic set of images involving robots. (Its a long story :D)
It outputs something like this: 'Cyborg Concept Downloadable Illustration'
Amazingly, the random generate I wrote only goes up to 255 unique combinations. Here is the script:
import numpy
from numpy import matrix
from numpy import linalg
import itertools
from pprint import pprint
import random
m = matrix( [
['Robot','Cyborg','Andoid', 'Bot', 'Droid'],
['Character','Concept','Mechanical Person', 'Artificial Intelligence', 'Mascot'],
['Downloadable','Stock','3d', 'Digital', 'Robotics'],
['Clipart','Illustration','Render', 'Image', 'Graphic'],
])
used = []
i = 0
def make_sentence(m, used):
sentence = []
i = 0
while i <= 3:
word = m[i,random.randrange(0,4)]
sentence.append(word)
i = i+1
return ' '.join(sentence)
def is_used(sentence, used):
if sentence not in used:
return False
else:
return True
sentences = []
i = 0
while i <= 1000:
sentence = make_sentence(m, used)
if(is_used(sentence, used)):
continue
else:
sentences.append(sentence)
print str(i) + ' ' +sentence
used.append(sentence)
i = i+1
Using randint instead of randrange, I get up to 624 combinations (instantly) then it hangs in an infinite loop, unable to create more combos.
I guess the question is, is there a more appropriate way of determining all possible combinations of a matrix?
You can make use of itertools to get the all possible combinations of matrix. I given one example to show how itertools will work.
import itertools
mx = [
['Robot','Cyborg','Andoid', 'Bot', 'Droid'],
['Character','Concept','Mechanical Person', 'Artificial Intelligence', 'Mascot'],
['Downloadable','Stock','3d', 'Digital', 'Robotics'],
['Clipart','Illustration','Render', 'Image', 'Graphic'],
]
for combination in itertools.product(*mx):
print combination
Your code can make use of recursion. Without itertools, here is one strategy:
def make_sentences(m, choices = []):
output = []
if len(choices) == 4:
sentence = ""
i = 0
#Go through the four rows of the matrix
#and choose words for the sentence
for j in choices:
sentence += " " + m[i][j]
i += 1
return [sentence] #must be returned as a list
for i in range(0,4):
output += make_sentences(m, choices+[i])
return output #this could be changed to a yield statement
This is quite different from your original function.
The choices list keeps track of the index of the column for each ROW in m that has been selected. When the recursive method finds that choices four rows have been selected, it outputs a list with just ONE sentence.
Where the method finds that the choices list doesn't have four elements, it recursively calls itself for FOUR new choices lists. The results of these recursive calls are added to the output list.