Python tuple not populating - python

I must be missing something here when I try to populate a tuple in a for loop.
...more code above...
colItems = objSWbemServices.ExecQuery(queryString)
#print type(colItems)
Is the above line needed?
# print the results
for item in colItems:
logTuple = (item.SourceName, item.Type, item.TimeGenerated, item.Message)
logTuple.sort(sortByTime)
return logTuple
Would the above code enter those fields into a tuple?
Below is the code to sort, I haven't been able to test it yet though.
def sortByTime(t1, t2):
if t1[2] < t2[2]:
return -1
elif t1[2] > t2[2]:
return 1
else:
return 0
Thanks for the help.

I'm not familiar with ExecQuery or the structures you're using, but I do know that in your for loop you're rewriting logTuple each time the body of the loop is executed. This should do the trick:
logTuples = []
for item in colItems:
logTuples.append( (item.SourceName, item.Type, item.TimeGenerated, item.Message) )
logTuples.sort(key=operator.itemgetter(2)) #credit: Thomas Jung
return logTuples

What you probably meant was to add the tuple to the list (and not to set logTuple to the last created tuple in the for loop):
for item in colItems:
log = (item.SourceName, item.Type, item.TimeGenerated, item.Message)
logTuple.append(log)
The sorting can be done with:
logTuples.sort(key=operator.itemgetter(2))

Related

Anybody know how to use pyresttest's 'fixed_sequence' generator?

I'm trying to use pyresttest's benchmarking framework to generate a sequence of entries in my flask_sqlalchemy-based database. I would like to read input values from a pre-defined list as advertised by this framework's benchmarking generator type 'fixed_sequence', but it's only picking up the first element of the list.
Here is the issue that explains my problem in detail, with an example: https://github.com/svanoort/pyresttest/issues/264
Any pointer in the right direction will be greatly appreciated
I looked into the code, it is jsut a bug, this feature was never used by anyone.
https://github.com/svanoort/pyresttest/blob/master/pyresttest/generators.py#L100
instead of:
```
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
if i == len(my_list):
i = 0
return seq_generator
It should be:
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
i += 1
if i == len(my_list):
i = 0
return seq_generator
```
The i += 1 is missing

Recursively Generating a List of n choose k combinations in Python - BUT return a list

I'm attempting to generate all n choose k combinations of a list (not checking for uniqueness) recursively by following the strategy of either include or not include an element for each recursive call. I can definitely print out the combinations but I for the life of me cannot figure out how to return the correct list in Python. Here are some attempts below:
class getCombinationsClass:
def __init__(self,array,k):
#initialize empty array
self.new_array = []
for i in xrange(k):
self.new_array.append(0)
self.final = []
self.combinationUtil(array,0,self.new_array,0,k)
def combinationUtil(self,array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
self.final.append(current_combo)
return
if array_index >= len(array):
return
current_combo[current_combo_index] = array[array_index]
#if current item included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index+1,k)
#if current item not included
self.combinationUtil(array,array_index+1,current_combo,current_combo_index,k)
In the above example I tried to append the result to an external list which didn't seem to work. I also tried implementing this by recursively constructing a list which is finally returned:
def getCombinations(array,k):
#initialize empty array
new_array = []
for i in xrange(k):
new_array.append(0)
return getCombinationsUtil(array,0,new_array,0,k)
def getCombinationsUtil(array,array_index,current_combo, current_combo_index,k):
if current_combo_index == k:
return [current_combo]
if array_index >= len(array):
return []
current_combo[current_combo_index] = array[array_index]
#if current item included & not included
return getCombinationsUtil(array,array_index+1,current_combo,current_combo_index+1,k) + getCombinationsUtil(array,array_index+1,current_combo,current_combo_index,k)
When I tested this out for the list [1,2,3] and k = 2, for both implementations, I kept getting back the result [[3,3],[3,3],[3,3]]. However, if I actually print out the 'current_combo' variable within the inner (current_combo_index == k) if statement, the correct combinations print out. What gives? I am misunderstanding something to do with variable scope or Python lists?
The second method goes wrong because the line
return [current_combo]
returns a reference to current_combo. At the end of the program, all the combinations returned are references to the same current_combo.
You can fix this by making a copy of the current_combo by changing the line to:
return [current_combo[:]]
The first method fails for the same reason, you need to change:
self.final.append(current_combo)
to
self.final.append(current_combo[:])
Check this out: itertools.combinations. You can take a look at the implementation as well.

python : no output or only an empty list was produced

index1 = 0
singlechar = []
def SINGLE_CHAR_VAR(filename):
firdict = vars_indents(filename)[0]
firtup_keys = firdict.keys()
firtup_val = firdict.values()
for keys in firtup_keys:
for values in firtup_val:
index = 0
for index in range(len(values)):
firvallist = firtup_val[index]
for item in firvallist:
if len(item[0]) == 1:
singlechar.append({'ERROR_TYPE': 'SINGLE_CHAR_VAR', 'LINE_NUMBER': str(keys),'COLUMN': str(item[1]),'INFO': str(item[0]),'SOURCE_LINE': str(lines[keys - 1])})
else:
continue
return singlechar
this is my code but there is no output produced or when i move around the return statement an empty list was produced. i was hoping it to give me a list of dictionaries as the output.
can somebody teach me how to fix this?
thank you
You should call the function at first to get the output.
SINGLE_CHAR_VAR(filename)
How can you expect a function to run without being called?
return != print. You need to do `print SINGLE_CHAR_VAR(filename)
return will send the value to whatever is calling that function. In this case the value/string is being returned, but you need to do something with it, hence the need for print. Alternatively, you can replace return with print if you want the function itself to print the output. However, in this case the value will not be passed along, and you won't be able to store it. It really just comes down to what works for you/what you want.
`
I think the problem is in the return statement. You should indent the return statement right below the outer for loop but not below the inner for loop. This is shown below:
def SINGLE_CHAR_VAR(filename):
firdict = vars_indents(filename)[0]
firtup_keys = firdict.keys()
firtup_val = firdict.values()
for keys in firtup_keys:
for values in firtup_val:
index = 0
for index in range(len(values)):
firvallist = firtup_val[index]
for item in firvallist:
if len(item[0]) == 1:
singlechar.append({'ERROR_TYPE': 'SINGLE_CHAR_VAR', 'LINE_NUMBER': str(keys),'COLUMN': str(item[1]),'INFO': str(item[0]),'SOURCE_LINE': str(lines[keys - 1])})
else:
continue
return singlechar # indent of return changed

How do I keep a list of numbers I have already enountered?

I am currently working on a BASIC simulator in Python, as the title suggests. Here is my code for this problem:
def getBASIC():
l = []
x = 1
while x == 1:
i = input()
l.append(i)
if len(i.split()) != 3:
x = 0
return l
def findLine(prog, target):
for l in range(0, len(prog)):
progX = prog[l].split()
if progX[0] == target:
return l
def execute(prog):
location = 0
visited = [False] * len(prog)
while True:
T = prog[location].split()[2]
location = findLine(prog, T)
visited[location] = True
if visited[len(visited)-1] == False:
return "infinite loop"
else:
return "success"
The first function does what it is intended to do -- convert input of BASIC code into a list. The second function, findLine also does what it is intended to do, in that it finds the item which contains the string equal to the input. The last function, however, I cannot get to work. I know what I have to do, and that is to check whether or not a part of it has been visited twice. I cannot figure out how to do this, due to the existence of the while loop. As a result of this, the second half of that function is just placeholder. If you could help me figure out how to solve this, it would be greatly appreciated. Thanks.
You keep a list of places that have been visited (you already do this) and then when you encounter a goto, you check if it does to a line that already have been visited, and if it has been visited, you exit.
One mistake right now is that you make a list that is as long as the program is. That's pretty pointless. Just keep a list of the visited line numbers instead, and check with
if current_line in visited:
Try adding an if statement declaring a line in the visited list to be true when it is encountered in the loop. This is my solution:
def execute(prog):
location = 0
visited=[False]*len(prog)
while True:
if location==len(prog)-1:
return "success"
if visited[location]==True:
return "infinite loop"
if visited[location]==False:
visited[location]=True
line2strings=prog[location].split()
T=line2strings[-1]
location=findLine(prog, T)

Removing things from Python list during for loop

Here is my code:
toBe =[]
#Check if there is any get request
if request.GET.items() != []:
for x in DB:
try:
#This is removing the PMT that is spcific to the name
if request.GET['pmtName'] != "None":
if not request.GET['pmtName'] in x['tags']:
print x['title'], x['tags']
toBe.append(x)
continue
#This is removing the peak stuff
if int(request.GET['peakMin']):
if int(request.GET['peakMin']) < int(x['charge_peak']):
toBe.append(x)
continue
if int(request.GET['peakMax']):
if int(request.GET['peakMax']) > int(x['charge_peak']):
toBe.append(x)
continue
if int(request.GET['widthMin']):
if int(request.GET['widthMin']) < int(x['charge_width']):
toBe.append(x)
continue
if int(request.GET['widthMax']):
if int(request.GET['widthMax']) > int(x['charge_width']):
toBe.append(x)
continue
except:
pass
#TODO: Stupid hack, this needs to be fixed
for x in toBe:
DB.remove(x)
del toBe
Essentially I want to remove the item and then skip to the next one. The problem with this is that when that happens, it messes up the order of the list and skips some. Anyone know a work around for this? Or maybe just a different way of doing this?
thanks
for x in DB[:]: makes a copy of the list DB, so you can iterate over it while modifying the original. Care -- memory-intensive and slow.
A nicer way would be to make another layer over the list which yields only some of the values, and then iterate over that when you need it later. You can do that with a generator:
def db_view( DB ):
for x in DB:
#This is removing the PMT that is spcific to the name
if request.GET.get( 'pmtName', None ) not in x['tags']:
print x['title'], x['tags']
continue
#This is removing the peak stuff
if int(request.GET['peakMin']):
if int(request.GET['peakMin']) < int(x['charge_peak']):
continue
if int(request.GET['peakMax']):
if int(request.GET['peakMax']) > int(x['charge_peak']):
continue
if int(request.GET['widthMin']):
if int(request.GET['widthMin']) < int(x['charge_width']):
continue
if int(request.GET['widthMax']):
if int(request.GET['widthMax']) > int(x['charge_width']):
continue
yield x
which you would use like
for x in db_view( DB ):
# Do stuff
The answer I usually see for questions of this sort if to loop over the list backwards. Here's how I do it in one of my programs:
for i in range(len(my_list)-1,-1,-1):
# do something
This works even if I add items to the list. On http://desk.stinkpot.org:8080/tricks/index.php/2006/08/read-a-list-backwards-in-python/ they say you can use the syntax "for i in list[::-1]:" instead. I have not tried doing it that way.
You're running over the same interpolation of request.GET for each value of x. Instead you could build a reusable list of filtering functions once.
For example something like:
if request.GET:
filters = []
if 'pmtName' in request.GET:
n = request.GET['pmtName']
filters.append(lambda x: n not in x['tags'])
if 'peakMin' in request.GET and request.GET['peakMin'].isdigit():
n = int(request.GET['peakMin'])
filters.append(lambda x: n < int(x['charge_peak']))
if 'peakMax' in request.GET and request.GET['peakMax'].isdigit():
n = int(request.GET['peakMax'])
filters.append(lambda x: n > int(x['charge_peak']))
if 'widthMin' in request.GET and request.GET['widthMin'].isdigit():
n = int(request.GET['widthMin'])
filters.append(lambda x: n < int(x['charge_width']))
if 'widthMax' in request.GET and request.GET['widthMax'].isdigit():
n = int(request.GET['widthMax'])
filters.append(lambda x: n > int(x['charge_width']))
Then you can apply this list of functions to select the members of DB to remove:
remove_these = [ x for x in DB if any(f(x) for f in filters)]
for item in remove_these:
DB.remove(item)
Or create a generator that will return the values of DB that all of the filters fail on:
filtered_DB = ( x for x in DB if all(not f(x) for f in filters))

Categories