I'm trying to do a script that choose a string and update a current field, but for some reason the code doesn't update the last value when calling my changerandom function in the Greeting class.
...[snip]...
class Greeting(Packet):
fields = OrderedDict([
("Morning", "Hi"),
("Afternoon", "Good Afternoon!"),
("Evening", "Good Evening!"),
])
def change(self):
self.fields["Morning"] = "Good morning!"
def changerandom(self, n = 1):
function=[
{self.fields["Morning"]: "Hello!"},
{self.fields["Morning"]: "Bonjorno!"},
{self.fields["Morning"]: "Hola!"},
]
result = {}
for i in range(n):
result.update(choice(function))
print "Updated string:",result
return result
text = Greeting()
print text
text.change()
print text
text.changerandom()
print text
My code return the following:
Hi
Good morning!
Updated string: {'Good morning!': 'Hola!'}
Good morning!
While it should have returned:
Hi
Good morning!
Hola!
I'm not sure what i'm missing here, I don't see why I cannot update the last field.
Any help would be greatly appreciated!
The problem is that you're returning a result, without assigning it anywhere.
You also use the value of fields, rather than the key. So, your code should be something like
def changerandom(self, n = 1):
function=[
{"Morning": "Hello!"},
{"Morning": "Bonjorno!"},
{"Morning": "Hola!"},
]
for i in range(n):
result = choice(function)
self.fields.update(result)
print "Updated string:",result
return result
Note that we're using self.fields.update, and we're no longer returning anything.
Generally, it's good practice for your functions and methods to return something, or change something, but never both.
Related
I made the string function in pythonbelow to summarize a block of text. I'm not getting any final answer when I run the function. Can someone help figure out what I did wrong? Thanks.
def summary(data):
category = data.get("category", "")
article_date = data.get("date", "")
headline = data.get("headline", "")
return summary(data)
pass
You are recursively calling the summary function. Assuming that the code provided is the entire function, if you want to get any output, you'd need to use something like this rather than calling the function again. You would also have to print the return value of the function
def summary(data):
category = data.get("category", "")
article_date = data.get("date", "")
headline = data.get("headline", "")
return f"Category: {category}\nArticle Date: {article_date}\nHeadline: {headline}\n"
pass
I'm stuck on a probably simple issue:
when using choice with functions, it seems like all of them gets executed while only one should.
Example:
from ordereddict import OrderedDict
from random import choice
def PrintStrings():
Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
print "Chosen Text is:", Text
return Text
class Greeting():
fields = OrderedDict([
("Morning", "Hi"),
("Afternoon", "Good Afternoon!"),
("Evening", "Good Evening!"),
])
def change(self):
self.fields["Morning"] = "Good morning!"
def changerandom(self, n = 1):
function=[
{self.fields["Morning"]: PrintStrings()},
{self.fields["Afternoon"]: PrintStrings()},
{self.fields["Evening"]: PrintStrings()},
]
result = {}
for i in range(n):
result.update(choice(function))
print "Updated string:",result
return result
text = Greeting()
text.change()
text.changerandom()
When running this script, I get all 3
{self.fields["Morning"]: PrintStrings()},
{self.fields["Afternoon"]: PrintStrings()},
{self.fields["Evening"]: PrintStrings()},
executed, while it shouldn't.
This script returns:
Chosen Text is: Ni hao!
Chosen Text is: Gutentag!
Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}
Expected result is:
Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}
Putting aside some strange data structures choices, you are calling a function in function. Remove the parenthesis' to just pass the function as an object.
PrintStrings() -> PrintStrings
Here's a possible solution to get the required output:
def changerandom(self, n = 1):
result = {}
for i in range(n):
key_choice = Greeting.fields[choice(Greeting.fields.keys())]
result[key_choice] = PrintStrings()
print "Updated string:", result
return result
With this approach, we grab our random key, and call PrintStrings() all in the same iteration.
An object will give you a means to run code only on serialization, not on instantiation:
class PrintStrings(object):
def __init__(self):
self.text = None
def __str__(self):
if self.text is None:
text = choice(["Gutentag!", "Ni hao!", "Hola!"])
print "Chosen Text is:", text
return text
def __repr__(self):
return str(self)
The rest of your code can be used as-is, with this class replacing your PrintStrings function.
I created a program that reads a couchDB to list followers and friends ids of a single twitter user. Friends are identified under the group “friend_edges” and followers under “follower_edges”.
I use the intersection operation between sets -set1.intersection(set.2)- in order to obtain the list of those who are both friends and followers.
When I use print to see the outputs, the results are correct. But when I change to return to process the results, it only processes friends, not followers.
Can somebody give me a clue of what I'm doing wrong and how to improve the code?.... thanks in advance.
from twitter_login import oauth_login
from twitter_DB import load_from_DB
from sets import Set
def friends_and_followers(doc):
if 'friend_edges' in doc.keys():
flist = []
for x in doc['friend_edges']:
flist.append(x)
#print "Number of friends: ", len(flist) <-- shows the right number of items
return flist
else:
return []
if 'follower_edges' in doc.keys():
followlist = []
for x in doc['follower_edges']:
followlist.append(x)
#print "Number of followers: ", len(followlist) <-- shows the right number of items
return followlist
else:
return []
flist = Set(flist)
followlist = Set(followlist)
return flist.intersection(followlist)
if __name__ == '__main__':
twitter_api = oauth_login()
DBname = 'users-aguy-+-only'
ff_results = load_from_DB(DBname)
print 'number loaded', len(ff_results)
for doc in ff_results:
together = friends_and_followers(doc)
print "Friends and followers of a guy: ", together
A return statement stops execution of that method and returns to the calling method, so by adding a return statement you are saying, "Stop here and go back to where you came from"
You need to store both the values you want returned in variables and return them at the same time at the end of your method:
return value1, value2
You will call this with something like this:
val1, val2 = get_value1_and_value2(input)
It might make more sense to just break that up into two separate methods that each return the correct value though.
I have a problem with dumping testsets list from HP QC. I'm using TestSetFactory object and simple SQL query and I receive > object (I'd love to receive dictionary filled base dump. What is wrong with this code? If you have a questions about implementation some function, write.
def create(self):
self._report_connector.connect()
self.qc_test_set_factory = self._report_connector._get_factory(self._path)
test_sets = self.qc_test_set_factory.NewList("SELECT * FROM CYCLE ")
if test_sets == None:
print " no results"
for test in test_sets:
pprint.pprint(test) #<---- it print me <COMOBject <unknow>>
print len(test_sets) #<---- it print me 1
Not certain about the accuracy of the rest of the code, but you do not pass a SQL query to the TestSetFactory.NewList method. If you want everything, pass an empty string.
test_sets = self.qc_test_set_factory.NewList("")
Just a quick question. I've tried Googling this but every time you add "class" to a Python search it gives you classes on Python. D:
I've found threads like this: How can you dynamically create variables via a while loop?
But I don't think that's exactly what I'm looking for since concatenation is also part of the variable.
Here's my while loop:
def main():
counter = 1
while counter <= 3:
print "Name: ",employee[counter].name
print "ID Number: ",employee[counter].id_number
print "Department: ",employee[counter].department
print "Job Title: ",employee[counter].job_title
print #LB
counter = counter + 1
main()
I have my objects set up as:
employee1 = Employee("Susan Meyers", 47899, "Accounting", "Vice President")
employee2 = Employee("Mark Jones", 39119, "IT", "Programmer")
employee3 = Employee("Joy Rogers", 81774, "Manufacturing", "Engineer")
This is the error I receive:
print "Name: ",employee[counter].name
NameError: global name 'employee' is not defined
Obviously I have a class set up as well, but I don't think I need to paste that for this. What I want it to do is go through the loop and change the counter from 1 to 2 to 3. That way it'll loop through all three employees.
Is it possible to do that? I've only ever done this with arrays so I'm not 100% sure I'm on the right track.
Any tips would be great. <3
Chelsea
I think what you are looking for is a list
employees = []
for i in xrange(1,10):
employees.append(employee("some name %s" % i))
employees[4].name