I am having troubles getting the list instead of an bound method - python

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

Related

It doesn't give anthing. Can someone help me about dictionaries and objects and classes in python?

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

How to more quickly make a bunch of objects in Python

w_rook_1 = ChessPiece('w_rook_1')
w_knight_1 = ChessPiece('w_knight_1')
w_bishop_1 = ChessPiece('w_bishop_1')
w_king = ChessPiece('w_king')
w_queen = ChessPiece('w_queen')
w_bishop_2 = ChessPiece('w_bishop_2')
w_knight_2 = ChessPiece('w_knight_2')
w_rook_2 = ChessPiece('w_rook_2')
w_pawn_1 = ChessPiece('w_pawn_1')
w_pawn_2 = ChessPiece('w_pawn_2')
w_pawn_3 = ChessPiece('w_pawn_3')
w_pawn_4 = ChessPiece('w_pawn_4')
w_pawn_5 = ChessPiece('w_pawn_5')
w_pawn_6 = ChessPiece('w_pawn_6')
w_pawn_7 = ChessPiece('w_pawn_7')
w_pawn_8 = ChessPiece('w_pawn_8')
Is there an easier way to do this? I would also like to be able to use the objects afterwards.
Here is a simple approach using a dictionary when dealing with this type of challenge.
I added some comments within the code, please read.
instance_names = ['w_rook_1',
'w_knight_1',
'w_bishop_1',
'w_king',
'w_queen',
'w_bishop_2',
'w_knight_2',
'w_knight_2']
class ChessPiece(object):
def __init__(self, name):
self.name = name
self.move = "moving {}".format(name)
chess_objs = {}
for obj in instance_names:
# insert instance names ex. 'w_rook_1' as the key
# the ChessPiece instance is set as the value
chess_objs.setdefault(obj, ChessPiece(obj))
# here just illustrates how to access fields
# bound to each object
print(chess_objs['w_bishop_1'].name)
print(chess_objs['w_bishop_1'].move)
outputs:
w_bishop_1
moving w_bishop_1
If you follow #kaya3's advice and redesign your ChessPiece class, you could use a list comprehension easily, something like this (using abbreviations and ignoring number):
color = 'W'
non_pawns = [ChessPiece(color, c) for c in 'RNBKQBNR']
pawns = [ChessPiece(color, 'P') for _ in range(8)]

In Python, how to set value for one __init__ variable based on another?

def __init__(self):
#self.data = []
self.random_word = random.choice(open("EnglishDictionary.txt").readlines()).strip()
self.length_notice = "The word you're guessing is {} letters long.".format(len(random_word))
This just returns the error: Name 'random_word' is undefined
You set self.random_word, not random_word, so you need to use self.random_word:
self.length_notice = "The word you're guessing is {} letters long.".format(len(self.random_word))
# Add self. ^^^^^
Just use it:
def __init__(self):
#self.data = []
with open("EnglishDictionary.txt") as f:
msg = "The word you're guessing is {} letters long."
self.random_word = random.choice(f).strip()
self.length_notice = msg.format(len(self.random_word))
Ask yourself, though, if self.random_word really needs to be an instance attribute, or if random_word can simply be a local variable inside the function, like msg.

Feedback tester python

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)

'MarkovGenerator' object has no attribute 'together'

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.

Categories

Resources