How do I debug a python multiple-sentence generator? - python

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))

Related

How to make more anagrams from one word

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.

I want to assign 2 variables at the same time, which are in the function imported from another file

I want to assign 2 variables at the same time, which are in the function imported from another file.
THIS IS THIS FUNCTION
def counter(init=[0]):
init[0] += 1
return init[0]
_____________________________________________
THIS IS ANOTHER SCRIPT
from Include.new_var import counter
first_letter = []
second_letter = []
def license_plate():
global first_letter, second_letter
characters = string.ascii_uppercase
prices_for_letters = dict(zip(characters, range(1, len(characters) + 1)))
print(prices_for_letters)
Actual results:
counter(first_letter), counter(second_letter) = random.choice(list(prices_for_letters.items()))
^
SyntaxError: can't assign to function call
Expected results:
new variable
I want to generate automaticlly new variables which will be storing random chosen value.
Assumptions:
1) Your function name seems to imply that you want to create a license plate.
2) Going through your profile, I see that you are from Poland so i assume you are trying to create a random license generator for vehicles in Poland.
3) A quick google search reveals that Poland license plates are 7 characters long with 2 or 3 initial chars followed by numbers.
def counter(some_char, draft_plate= []):
draft_plate.append(str(some_char))
return draft_plate
def license_plate():
final_license_plate = []
characters = string.ascii_uppercase
numbers = range(0,10)
prices_for_letters = dict(zip(characters, range(1, len(characters) + 1)))
prices_for_numbers = dict(zip(numbers, range(1, len(numbers)+1)))
numofchars = random.randint(2,3)
for i in range(0,numofchars):
counter(random.choice(list(prices_for_letters.keys())), final_license_plate)
final_license_plate.append(' ')
for j in range(numofchars,7):
counter(random.choice(list(prices_for_numbers.keys())), final_license_plate)
print(final_license_plate)
license_plate()
Could you please clarify what you're intending to do afterwards? Here you're just trying to call the function twice.
Please also provide an expected result etc.
However:
First, choice will only return one item - you're expecting two.
Second, just put the choice statement into your function call:
counter(random.choice(list(prices_for_letters.items())))
counter(random.choice(list(prices_for_letters.items())))

Random mutation

I am a beginner python coder and I am writing a code to generate random mutation at random position.
I have written a function which includes:
The sequence where mutation happens
A List of nucleotide from which a nucleotide is selected randomly and replaced to the nucleotide of the original sequence.
Basic concept of the code:
Say we have to pick one ball from (A) basket and replace with another ball from another basket (B). The colors of the two balls need to be different.
I know I need to use while loop but I am not able to do it.
def random(s)
length = len(s)
seq = list(s)
nucl = "ATGC" ## pick one nucleotide from this list
lengthnucl= len(nucleotide_list)
position_orgseq = np.random.choice(range(0,length))
position_nucl = np.random.choice(range(0,lengthnucl))
#while c < length:
##if the two nucleotides chosen are not equaul then:
#two nucleotides are from
# TTTTGGGCCCCAAA - original seq, ATGC = nucloetide list
if seq[position_orgseq] != nucleotide_list[position_nucl]:
seq[position_orgseq] = nucleotide_list[position_nucl]
final = "".join(seq)
return s,final
actual_seq, mut_seq = random("TTTTGGGCCCCAAA")
print(actual_seq)
print(mut_seq)
First, as #Error - Syntatical Remorse pointed out in the comment, there is no need to import numpy, use built in random instead (specifically, you can use random.randint()).
Your code as is, doesn't run, you have misnamed variables. Other than that, you are close. Your hunch to using a while loop is correct. You can simply keep looping until your two random values don't give the same nucleotide in the two lists. Like so:
from random import randint
def random(s):
length = len(s)
seq = list(s)
nucl = "ATGC"
lengthnucl = len(nucl)
position_orgseq = randint(0, length - 1)
position_nucl = randint(0, lengthnucl - 1)
while seq[position_orgseq] == nucl[position_nucl]:
position_orgseq = randint(0, length - 1)
position_nucl = randint(0, lengthnucl - 1)
seq[position_orgseq] = nucl[position_nucl]
final = "".join(seq)
return s, final
actual_seq, mut_seq = random("TTTTGGGCCCCAAA")
print(actual_seq)
print(mut_seq)
This may be optimized further.

Word Ladder without replacement in python

I have question, where I need to implement ladder problem with different logic.
In each step, the player must either add one letter to the word
from the previous step, or take away one letter, and then rearrange the letters to make a new word.
croissant(-C) -> arsonist(-S) -> aroints(+E)->notaries(+B)->baritones(-S)->baritone
The new word should make sense from a wordList.txt which is dictionary of word.
Dictionary
My code look like this,
where I have calculated first the number of character removed "remove_list" and added "add_list". Then I have stored that value in the list.
Then I read the file, and stored into the dictionary which the sorted pair.
Then I started removing and add into the start word and matched with dictionary.
But now challenge is, some word after deletion and addition doesn't match with the dictionary and it misses the goal.
In that case, it should backtrack to previous step and should add instead of subtracting.
I am looking for some sort of recursive function, which could help in this or complete new logic which I could help to achieve the output.
Sample of my code.
start = 'croissant'
goal = 'baritone'
list_start = map(list,start)
list_goal = map(list, goal)
remove_list = [x for x in list_start if x not in list_goal]
add_list = [x for x in list_goal if x not in list_start]
file = open('wordList.txt','r')
dict_words = {}
for word in file:
strip_word = word.rstrip()
dict_words[''.join(sorted(strip_word))]=strip_word
file.close()
final_list = []
flag_remove = 0
for i in remove_list:
sorted_removed_list = sorted(start.replace(''.join(map(str, i)),"",1))
sorted_removed_string = ''.join(map(str, sorted_removed_list))
if sorted_removed_string in dict_words.keys():
print dict_words[sorted_removed_string]
final_list.append(sorted_removed_string)
flag_remove = 1
start = sorted_removed_string
print final_list
flag_add = 0
for i in add_list:
first_character = ''.join(map(str,i))
sorted_joined_list = sorted(''.join([first_character, final_list[-1]]))
sorted_joined_string = ''.join(map(str, sorted_joined_list))
if sorted_joined_string in dict_words.keys():
print dict_words[sorted_joined_string]
final_list.append(sorted_joined_string)
flag_add = 1
sorted_removed_string = sorted_joined_string
Recursion-based backtracking isn't a good idea for search problem of this sort. It blindly goes downward in search tree, without exploiting the fact that words are almost never 10-12 distance away from each other, causing StackOverflow (or recursion limit exceeded in Python).
The solution here uses breadth-first search. It uses mate(s) as helper, which given a word s, finds all possible words we can travel to next. mate in turn uses a global dictionary wdict, pre-processed at the beginning of the program, which for a given word, finds all it's anagrams (i.e re-arrangement of letters).
from queue import Queue
words = set(''.join(s[:-1]) for s in open("wordsEn.txt"))
wdict = {}
for w in words:
s = ''.join(sorted(w))
if s in wdict: wdict[s].append(w)
else: wdict[s] = [w]
def mate(s):
global wdict
ans = [''.join(s[:c]+s[c+1:]) for c in range(len(s))]
for c in range(97,123): ans.append(s + chr(c))
for m in ans: yield from wdict.get(''.join(sorted(m)),[])
def bfs(start,goal,depth=0):
already = set([start])
prev = {}
q = Queue()
q.put(start)
while not q.empty():
cur = q.get()
if cur==goal:
ans = []
while cur: ans.append(cur);cur = prev.get(cur)
return ans[::-1] #reverse the array
for m in mate(cur):
if m not in already:
already.add(m)
q.put(m)
prev[m] = cur
print(bfs('croissant','baritone'))
which outputs: ['croissant', 'arsonist', 'rations', 'senorita', 'baritones', 'baritone']

How to NOT repeat a random.choice when printing a piece of text in python

I have three lists in text files and I am trying to generate a four-word message randomly, choosing from the prefix and suprafix lists for the first three words and the `suffix' file for the fourth word.
However, I want to prevent it from picking a word that was already chosen by the random.choice function.
import random
a= random.random
prefix = open('prefix.txt','r').readlines()
suprafix = open('suprafix.txt','r').readlines()
suffix = open('suffix.txt','r').readlines()
print (random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(suffix))
As you can see it chooses randomly from those two lists for three words.
random.sample(pop, k) selected k items from pop without replacement. Hence:
prefix1, prefix2, prefix3 = random.sample(prefix, 3)
suprafix1, suprafix2, suprafix3 = random.sample(suprafix, 3)
suffix = random.choice(suffix)
print (prefix1 + suprafix1, prefix2 + suprafix2, prefix3 + suprafix3, suffix))
Thankyou xnx that helped me sort out the problem by using the random.sample first then printing either of them afterwards, i might have done it the long way round but this is how i did it >
import random
a= random.random
prefix = open('prefix.txt','r').readlines()
suprafix = open('suprafix.txt','r').readlines()
suffix = open('suffix.txt','r').readlines()
prefix1, prefix2, prefix3 = random.sample(prefix, 3)
suprafix1, suprafix2, suprafix3 = random.sample(suprafix, 3)
suffix = random.choice(suffix)
one = prefix1, suprafix1
two = prefix2, suprafix2
three = prefix3, suprafix3
print (random.choice(one), random.choice(two), random.choice(three), suffix)

Categories

Resources