Hi for a given function I have 2 parameters which are string and an Int but I don't know which comes first. So I have a function "pick_type()" that tries to guess the order of the parameters. So my question is when "pick_type()" incorrectly guesses the order, how do I record this and make sure "pick_type()" never tries that specific order again ?
for iteration in range(0, 10):
args = []
print("\n def test%d(self):" % (iteration))
for input in range(num_arguments):
args += pick_type()
try:
result = target(*args)
code = test_to_string(target, args, result)
except TypeError as error:
code = test_to_string_exc(target, args, error)
for line in code.splitlines():
print(" "+line)
def pick_type():
lista = []
words = ['rhythms', 'rhythms', 'manager', 'training', 'hotel', 'destroy']
word = choice(words)
num = random.randint(-100, 100)
lists = [word,num]
choices = choice(lists)
if choices == word:
lista.append(word)
else:
lista.append(num)
return lista
I would suggest wrapping your method in a class, then you can have a persistent list of bad orders. It's not clear to me what you mean by an "order", but whatever it is, hopefully this pseudo-code helps:
class PickType:
def __init__(self):
self._bad_orders = []
def pick_type(self):
...# insert body here
if order in self._bad_orders:
## pick another order
## test the new order
if <order is bad>:
self._bad_orders.append(order)
## if your test for bad orders is performed outside pick_type(), you just need a method to add to the list of bad_orders
def add_bad_order(self, order):
self._bad_orders.append(order)
Related
import random
from random import randint as rand
upperCase = chr(rand(65,66))
lowerCase = chr(rand(97,122))
class PasswordLetters:
def __init__(self):
pass
def generateCapitalCaseLetter(self):
uppCase = chr(rand(65,91))
return uppCase
def generateLowerCaseLetter(self):
lowCase = chr(rand(97,122))
return lowCase
def generateSpecialLetter(self):
specLet = random.choice(specialCharacters)
return specLet
def generateNumber(self):
num = rand(1,99)
class PasswordGenerator:
def __init__(self,uppCase,lowCase,specLet,num):
self.uppCaseList = []
lowCaseList = []
specLet = []
numList = []
self.passLetter = PasswordLetters()
for i in range(0,uppCase):
self.uppCaseList.append(self.passLetter.generateCapitalCaseLetter)
password = PasswordGenerator(1,1,1,1)
password.uppCaseList
So The Problem I am facing is when I try to get uppCaseList back from my password object it comes back to me as an method in a list instead of a letter in a list. I think the problem is in my PasswordLetters class but I can't figure it out.
The only thing I want is for
password.uppCaseList
to return a list with letters
Since it's a function you are calling, it would need to include the ( open and close ) parentheses. You may refer here for explanation.
for i in range(0,uppCase):
self.uppCaseList.append(self.passLetter.generateCapitalCaseLetter())
I have two functions, updates_list updates values to the list altered_source_tables while the other picks the values in that list. The issue is, even though the first function updates the list, the second function use_list still has the list as empty.
altered_source_tables = []
table_name = 'table_1'
def updates_list(table_name, **kwargs):
# CODE
for e in job.errors:
fullstring = e['message']
substring = "No such field"
if search(substring, fullstring):
altered_source_tables.append(table_name)
print("altered_source_tables list ", altered_source_tables) # output from fn call: altered_source_tables = ['table_1']
else:
print('ERROR: {}'.format(e['message']))
def use_list(**kwargs):
print("altered_source_tables list ", altered_source_tables) # output from fn call: altered_source_tables = []
if len(altered_source_tables) > 0:
# Loop through all altered tables
for table_name in altered_source_tables:
# CODE
What I'm I missing?
I am trying to print frequencies of all words in a text.
I wanna print all keys according to their sorted values.
Namely, I wanna print the frequencies from most frequent to least frequent.
Here is my code:
freqMap = {}
class analysedText(object):
def __init__(self, text):
# remove punctuation
formattedText = text.replace('.', '').replace('!', '').replace('?', '').replace(',', '')
# make text lowercase
formattedText = formattedText.lower()
self.fmtText = formattedText
def freqAll(self):
wordList = self.fmtText.split(' ')
freqMap = {}
for word in set(wordList):
freqMap[word] = wordList.count(word)
return freqMap
mytexte = str(input())
my_text = analysedText(mytexte)
my_text.freqAll()
freqKeys = freqMap.keys()
freqValues = sorted(freqMap.values())
a = 0
for i in freqValues:
if i == a:
pass
else:
for key in freqKeys:
if freqMap[key] == freqValues[i]:
print(key,": ", freqValues[i])
a = i
Your function freqAll returns a value that you are not catching.
It should be:
counts = my_text.freqAll()
Then you use the counts variable in the rest of your code.
freqAll method of your class does return freqMap which you should store but do not do that, therefore you are in fact processing empty dict freqMap, which was created before class declaration. Try replacing
my_text.freqAll()
using
freqMap = my_text.freqAll()
I'm working on a school project. I made a test version of my program, because I'm new to Python and I only have experience with C#, so I'm still learning te basics. My problem is the following:
Before the function "Fill_Array()" I declared a variable (" max_element_var") that is supposed to store the max number of elements that can be stored in the array ("content_array"). Later in the function I change it's value to the input of the console, which happens, and the function runs as it should, the only problem being is that outside the function the value of " max_element_var" stays "None". What should I do in order to fix this?
#__Test__#
def Test():
class Que:
def __init__(self, content, max_element ,actual_elements):
self.content = content
self.max_element = max_element
self.actual_elements = actual_elements
max_element_var = None
content_array = []
def Fill_array():
print("What should be the max number of elements that can be stored in the array? (Type in an integer!)")
max_element_var = int(input())
if(max_element_var>0):
import random
random_var = random.randrange(0,max_element_var)
for x in range(max_element_var-random_var):
content_array.append(x)
else:
print("It has to be more than 0!")
Fill_array()
Fill_array()
actual_elements_var = len(content_array)
que = Que (content_array, max_element_var, actual_elements_var)
print("Content: ", que.content)
print("Max number of elements: ", que.max_element)
print("Actual number of elements: ", que.actual_elements)
#__Test__#
#__Full__#
def Full():
pass
#__Full__#
#__Version_selector__#
def Version_selector():
print("Which version should be used? (Type in the number!)")
print("1 - Test")
print("2 - Full")
answer = int(input())
if(answer == 1):
Test()
Version_selector()
elif(answer == 2):
Full()
Version_selector()
#__Version_selector__#
Version_selector()
In python variables are automatically created as local, in the scope of the function which used them alone.
To solve your problem you may either
(1) return the variable, passing it from one function the other explicitly.
(2) declare it as global so all functions have access to it.
More about scopes here and here.
Consider the following code. In the code below you persumably change the value of x but in fact there is a big difference between the x inside the function and outside. The x inside the function is a local variable and will "disappear" once the function ends. If you want to save the value of x you must use return x and save the outcome to a variable. For example, See the function a_saving_example(x)
you may also use a global variable though some say it is bad practice and it is better to use return in your function.
def times_two(x):
x = x * 2
x = 5
print(x)
times_two(x)
print(x)
output:
5
5
saving example:
def a_saving_example(x):
x = x * 2
return x
x = 5
print(x)
x = a_saving_example(x)
print(x)
output:
5
10
Modified code to correct some issues.
Import normally done at top of module (not within functions)
Remove nested class definition inside function (obfuscates things in simple code)
Changed recursive calls to a while loop (a better way to repeat execution of a function from beginning in Python since no tail recursion).
Code Refactoring
import random
class Que:
def __init__(self, content, max_element ,actual_elements):
self.content = content
self.max_element = max_element
self.actual_elements = actual_elements
def Fill_array():
" Returns requested size and array "
while True:
prompt = """"What should be the max number of elements that can be stored in the array? Type in an integer!: """
max_element_var = int(input(prompt))
if max_element_var > 0:
random_var = random.randrange(0,max_element_var)
return max_element_var, [x for x in range(max_element_var-random_var)]
else:
print("It has to be more than 0!")
def Test():
max_element_var, content_array = Fill_array()
actual_elements_var = len(content_array)
que = Que (content_array, max_element_var, actual_elements_var)
print("Content: ", que.content)
print("Max number of elements: ", que.max_element)
print("Actual number of elements: ", que.actual_elements)
#__Test__#
#__Full__#
def Full():
pass
#__Full__#
#__Version_selector__#
def Version_selector():
while True:
prompt = """Which version should be used? (Type in the number!)
1 - Test
2 - Full
3 - Quit\n\t"""
answer = int(input(prompt))
if answer == 1:
Test()
elif answer == 2:
Full()
else:
break
#__Version_selector__#
Version_selector()
I come up with a problem about the class and I don't know the reason, does anyone can help me out?
The problem is in def together(), here are my code.
class MarkovGenerator(object):
def __init__(self, n, max):
self.n = n # order (length) of ngrams
self.max = max # maximum number of elements to generate
self.ngrams = dict() # ngrams as keys; next elements as values
beginning = tuple(["That", "is"]) # beginning ngram of every line
beginning2 = tuple(["on", "the"])
self.beginnings = list()
self.beginnings.append(beginning)
self.beginnings.append(beginning2)
self.sentences = list()
def tokenize(self, text):
return text.split(" ")
def feed(self, text):
tokens = self.tokenize(text)
# discard this line if it's too short
if len(tokens) < self.n:
return
# store the first ngram of this line
#beginning = tuple(tokens[:self.n])
#self.beginnings.append(beginning)
for i in range(len(tokens) - self.n):
gram = tuple(tokens[i:i+self.n])
next = tokens[i+self.n] # get the element after the gram
# if we've already seen this ngram, append; otherwise, set the
# value for this key as a new list
if gram in self.ngrams:
self.ngrams[gram].append(next)
else:
self.ngrams[gram] = [next]
# called from generate() to join together generated elements
def concatenate(self, source):
return " ".join(source)
# generate a text from the information in self.ngrams
def generate(self,i):
from random import choice
# get a random line beginning; convert to a list.
#current = choice(self.beginnings)
current = self.beginnings[i]
output = list(current)
for i in range(self.max):
if current in self.ngrams:
possible_next = self.ngrams[current]
next = choice(possible_next)
output.append(next)
# get the last N entries of the output; we'll use this to look up
# an ngram in the next iteration of the loop
current = tuple(output[-self.n:])
else:
break
output_str = self.concatenate(output)
return output_str
def together(self):
return "lalala"
if __name__ == '__main__':
import sys
import random
generator = MarkovGenerator(n=2, max=16)
for line in open("us"):
line = line.strip()
generator.feed(line)
for i in range(2):
print generator.generate(i)
print generator.together()
But I got the error saying:
Traceback (most recent call last):
File "markovoo2.py", line 112, in <module>
print generator.together()
AttributeError: 'MarkovGenerator' object has no attribute 'together'
Does anyone know know the reason?
You have indented the def together() function definition too far, it is part of the def generate() function body.
Un-indent it to match the other functions in the class body.
It looks your def together is indented too deeply. It is inside the generate method. Move it out one indentation level.