Under which circumstances filter can refuse to work in Python? - python-3.x

I get the following line
db_dir_content = os.listdir(db_path)
db_states = filter(is_state, db_dir_content)
returning empty iterator, while the following
db_dir_content = os.listdir(db_path)
db_states = [state for state in db_dir_content if is_state(state)]
returning non empty an correct list.
is_state is following
def is_state(name):
return _STATE_NAME_PATTERN.match(name) is not None
How can it be and how to fix?

Related

create a function that adds to a list

I have en assignment about lists that goes like this,
Create a global variable called myUniqueList. It should be an empty list to start.
Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniqueList, unless its value already exists in myUniqueList. If the value doesn't exist already, it should be added and the function should return True. If the value does exist, it should not be added, and the function should return False;
Finally, add some code below your function that tests it out. It should add a few different elements, showcasing the different scenarios, and then finally it should print the value of myUniqueList to show that it worked.
Add another function that pushes all the rejected inputs into a separate global array called myLeftovers. If someone tries to add a value to myUniqueList but it's rejected (for non-uniqueness), it should get added to myLeftovers instead."
This is the code I have wrote to create the lists and add value to the list but I dont get the output I want from this code, can someone help me explain what I do wrong how do I write so my list get filled with elements? The Output I get from the code now, you can see below.
myUniqueList = []
myLeftovers = []
def addList(newThing):
if newThing in myUniqueList:
myLeftovers.append(newThing)
return False
else:
myUniqueList.append(newThing)
return True
print(myUniqueList) # []
print(addList("Meliodas")) # returns 'True' since it's a new item
print(addList("Escanor")) # returns 'True' since it's a new item
print(addList("Meliodas")) # returns 'False' since it's already been added
print(myUniqueList) # This includes the new entries
print(myLeftovers) # This includes any repeated entries
I get
[]
False
False
False
[]
[]
Can you explain why the list dont get the words added and why I get Syntax Error on the else statement
According to your question, you were asked to create a global variable called myUniqueList. Since myUniqueList is a global list, in other to use it in a function, we have to tell the function we are using a global list by adding "global" before myUniqueList; hence your code will be as follows:
myUniqueList = []
myLeftovers = []
def add(newValue):
global myUniqueList
if newValue in myUniqueList:
addToLeftovers(newValue)
return False
else:
myUniqueList.append(newValue)
return True
def addToLeftovers(newValue):
myLeftovers.append(newValue)
# Testing the code:
print(add("Hello"))
print (myUniqueList)
print(add("Hello"))
print(myUniqueList)
print(myLeftovers)
Your Result will be as follows:
True
['Hello']
False
['Hello']
['Hello']
The first "Hello" came out TRUE while the second "Hello" came out FALSE. Then the third "Hello" was from the second hello which was rejected and now, pushed to the "myLeftovers" as stated in your question.

Python Try Except when a list is null

I've been searching for my problem here, but i can't find the exact answer to my problem.
I call a sympy function ( solve() ). This function can return a full list or an empty list.
I call this piece of code inside a while:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
What i want is:
if the solve() returns an empty list, just pass. And if the solve() returns a full list, keep with the execution. The solve will be returning empty list until i find the right value.
This can be reached by checking sol[0][0], if there's a non-empty list this will work, but if the list is empty, this will throw an error (null pointer) i want try to flag it and pass.
What i'm having now is that when sol is empty, it tries to get sol[0][0], and ofc this throws an error that's not being catched by the try, and the whole code stops.
Anyone knows a solution for that? I'm not using try correctly?
Set sol in the beginning of each loop to some value and check it in the except clause
about else
try/except has an else which will be run the try block did not raise an Exception
and for has an else clause for when it was not broken out of!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")

Applying the change of list at the start of a function

I have been trying to create a word search generator by using list within list. However, one of the things that I've been trying to do is that the list must preserve the word that it append before rather than start a blank list. The method that I did was to simply call on a previous function for this.
initial= list()
def board ():
inital = add()
test = list()
for a in range(5):
test.append(a)
initial = test.copy()
return initial
def add():
initial = board()
for a in range(5,10):
initial.append(a)
initial = initial.copy()
return initial
initial = add()
inital = board()
print(initial)
When I tried running it in the terminal, an error message appeared saying that the maximum recursion depth has exceeded. What does this means and how do I achieve the goal (having a list that prints 5,6,7,8,9,0,1,2,3,4)?

Multiprocessing pool not taking list of strings to create individual process

I am trying to write a multiprocessing application where i have list of companies for which individual processes needs to be triggered from a process pool.
I have a function which takes 3 args out of which 1 being self, and the second being a list and third being a company code.
I am trying to process the function as a process for each company code.
I initially had problem with the self variable, which gives 'pickle' error, which for now i am overcoming by passing None.
I have used 'Partial' to multiple arguments problem in multiprocessing, after which i am getting an error "TypeError: can only concatenate str (not "list") to str" when adding a company_list as iterable to my map.
def processing_saved_search_per_company(self, saved_search_list, each_cpy):
print("Company Key : " + each_cpy)
print("Saved Search List : " + saved_search_list)
def process(self):
saved_search_list =[]
company_list = APICall.fetch_onboarded_companies_from_customer_csv(self)
saved_search_list_file = os.path.join(code_dir_path, "resources\\saved_search_template.txt")
try:
with open(saved_search_list_file, "r") as ss_file_pointer:
saved_search_list = ss_file_pointer.readlines()
except IOError as ie:
print(f"Error Occurred while accessing the Saved Search file reason being :-: {ie}")
final_ss_list = []
p=Pool(processes=4)
#for each_cpy in company_list:
print("Company List : "+str(company_list))
func = partial(APICall.processing_saved_search_per_company,None,saved_search_list)
p.map(func, company_list)
p.close()
I need the creation of a pool of process which runs like,
p1= processing_saved_search_per_company(self,saved_search_list,"company 1")
p2 = processing_saved_search_per_company(self,saved_search_list,"company 2")
p3 = processing_saved_search_per_company(self,saved_search_list,"company 3")
but getting an error as,
TypeError: can only concatenate str (not "list") to str
Requesting help on this issue.
Thanks,
Shahid
Found an workaround to this problem, like passing the Company list as well as part of the partial function and then the array of numbers to the length of Company list to my below function, which would now take index as a new parameter at the end.
processing_saved_search_per_company(self, saved_search_list, companies_list,index):
With the index now coming from the below map, I am able to run the above function for the specific company, without any hassle.
func = partial(APICall.processing_saved_search_per_company,None,saved_search_list, company_list)
Index_values =[X for X in range(0,len(companies_list))]
p.map(func, index_values)
p.close()
p.join()
Thanks

haystack SearchQueryResult object returns multiple objects

I don't get why get() with pk=1 would result in multiple objects returned below..
sqs = SearchQuerySet().more_like_this(self)
for obj in sqs:
do something with obj.object # obj.object results in error
get() returned more than one MyModel -- it returned 4! Lookup parameters were {'pk': u'1'}
I don't know why but I was having the same problem, the following gave me MultipleObjectReturned error:
context['object_list'] = [result.object for result in results]
lib/python2.7/site-packages/haystack/models.py", line 80, in _get_object
self._object = self.searchindex.read_queryset().get(pk=self.pk)
instead of referencing the obj.object directly, I worked around with using pk
context['object_list'] = Entry.objects.filter(pk__in=[result.pk for result in results])

Resources