How to check if a shelf is open? - shelve

Lets say I have a shelf.
subject_name = shelve.open ("subject_file", "c")
and in my program I would like to make sure that I have opened the shelf and it is ready for me to write new data in, to avoid an error.
if subject_name == open:
definition = subject_name["term"]
print( definition)
else:
subject_name = shelve.open("subject_file". "c")
definition = subject_name["term"]
print( definition)
I am wondering is my if statement Namely [if subject_name == open:] would evaluate to either true or false. If it wouldn't How would i rewrite it such that it would evaluate to either true or false.

Related

State name spellcheck code not working with two word state names

I am working on vetting someone else's state spellchecker. The test data they ran seemed to work fine, but trying a different data set, it doesn't seem to be able to get past the first word "North" in a state name.
I need the code to be able to work with state names with two words.
This is the code:
import sys
!pip install pyspellchecker
from spellchecker import SpellChecker
#from google.colab import files
import pandas as pd
import io
#Implement spellcheck.
spell=SpellChecker()
for ind in newDF.index:
stateWordList = newDF['State'][ind].split()
if len(stateWordList) == 1:
#print(True)
if stateWordList[0] in spell:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
else:
misspelledState = False in (stateWord in spell for stateWord in stateWordList)
if misspelledState == True:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
Instead, it isn't seeing North WhateverState as valid, and returns:
'North' is not a valid state, please enter a correct spelling:
Does it need a condition specifically for two word names?
In your else statement, you have a logic error
else:
misspelledState = False in (stateWord in spell for stateWord in stateWordList)
if misspelledState == True:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
Let's see misspelledState = False in (stateWord in spell for stateWord in stateWordList), if all the words in stateWordList is well spelled, you are checking with misspelledState = False in (True, True, ...), the result will be False.
Then go to the if-else condition, it will go to else condition where outputs the correction message:
if misspelledState == True:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
You can use
misspelledState = all([stateWord in spell for stateWord in stateWordList])

My vip variable does not take False as a value and always defaults to True

Below is the code to return either a VIP customer or an ordinary customer, the list does not take vip as a False value and always takes True.
Class DonutQueue():
def arrive(self,name,VIP):
self.name = name
self.vip = VIP
if self.vip==True:
self.queue2.append(self.name)
return self.queue2
else:
self.queue.append(self.name)
return self.queue
def next_customer(self):
while not self.queue2== []:
if not self.queue2==[]:
return self.queue
else:
return self.queue2
def main():
n = int(input("Enter the number of customers you want to add"))
for i in range(0,n):
name = input("Enter their name")
vip= bool(input("Are they a VIP"))
DonutQueue.arrive(name,VIP)
print (DonutQueue().next_customer())
Below is the output:
Enter the number of customers you want to add2
Enter their name John
Are they a VIP False
Enter their name Wick
Are they a VIP True
None
Why am I getting None as the output and my value always takes True when I input False.
Below is the debugger values:
i:0
n:2
name: John
vip: True
The Python input() method reads user input and returns it as string.
Python bool() will always return a True value for a non-empty string and False only if a string is empty.
In order to get correct the value for vip as a bool you have to manually check the input string
vipString = input("Are they a VIP")
vip = True if vipString == 'yes' else False
Variables in Python are case sensitive. Therefore, when you assign the input to vip, it is never used and VIP is used instead.
vip= bool(input("Are they a VIP"))
DonutQueue.arrive(name, vip) #instead of VIP

Using loops to call recursive function

I am trying to create a recursive function that takes three parameters: name of the dictionary, name of the original (This will be the key in the dict), and name of the final (trying to determine if it is possible to reach the final from the original)
My code functions well and enters the correct if statements and everything (tested using print statements) however, instead of the function returning True or False, it returns None every time.
I determined that this is because rather than calling my recursive function with "return" I only call the name of the function. However, if I include return in my code, the function only runs with the first value from the dictionary's key.
Any and all help on this would be appreciated.
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
elif babyname in dictname.keys():
if dictname[babyname]:
for i in dictname[babyname]:
evolve(dictname,i,evolvedname)
else:
return False
else:
return False
Collect all recursive call's results, and return True if any of them is true.
Something like:
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
elif babyname in dictname.keys():
if dictname[babyname]:
results = [] #To collect results
for i in dictname[babyname]:
results.append(evolve(dictname,i,evolvedname))
#Check if any of them is True
for res in results:
if res==True: return True
return False #No true among childs
else:
return False
else:
return False
But I think this code can be simplified to just:
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
return any(evolve(dictname,i,evolvedname) for i in dictname.get(babyname,[]))
Lastly, although I don't know what you are trying to do, you might get an infinite loop, this is like doing dfs but without marking any node as already explored(black) or currently exploring(gray).

Scopes within while loops

from random import randint
isRunning =True
while isRunning:
dice1 = randint(1,7)
dice2 = randint(1,7)
print("The first die landed on ℅d and the second landed on ℅d." ℅ (dice1,dice2))
user_input = input("Contiue? Yes or No?\n>")
if user_input == "Yes" or "yes":
print("="*16)
elif user_input == "No" or "no":
isRunning = False
I feel like I'm making such a simple mistake and when I decided to look into global variables and what not it still doesn't help. Could anyone explain why the while loop doesn't terminate, although the variable was set to false.
if user_input== "Yes" or "yes" should be
if user_input== "Yes" or user_input =="yes", alternatively it's equivalent to if any(user_input==keyword for keyword in["Yes", "yes"]):
your original if clause is splitting to
if user_input=="Yes" or if "yes" and if "yes" always true, therefore your if-elseif clause always go to if clause.

How to null out exceptions in an htmlChecker

While this is a project assignment for class I am trying to understand how to do a specific part of the project.
I need to go through an html file and check if all the opening statements are matched to closing statements. Further, they must be in the correct order and this must be checked using a stack I've implemented. As of right now I am working on extracting each tag from the file. The tough part seems to be the two exceptions that I am working on here. The and the . I need these tags to be removed so the program doesn't read them as an opening or closing statement.
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items[-1]
def getTag(file):
EXCEPTIONS = ['br/', 'meta']
s = Stack()
balanced = True
i = 0
isCopying = False
currentTag = ''
isClosing = False
while i < len(file) and balanced:
if symbol == "<":
if i < (len(file) - 1) and file[i + 1] == "/":
i = i + 1
isClosing == True
isCopying == True
if symbol == ">":
if isClosing == True:
top = s.pop()
if not matches(top, symbol):
balanced = False
else:
**strong text**
s.push(currentTag)
currentTag = ''
isCopying == False
if isCopying == True:
currentTag += symbol
The code reads in the file and goes letter by letter to search for <string>. If it exists it pushes it on to the stack. The matches functions checks to see if the closing statement equals the opening statement. The exceptions list is the ones I have to check for that will screw up the placing of the strings on the stack. I am having a tough time trying to incorporate them into my code. Any ideas? Before I push on to the stack I should go through a filter system to see whether that statement is valid or not valid. A basic if statement should suffice.
If I read your requirements correctly, you're going about this very awkwardly. What you're really looking to do is tokenize your file, and so the first thing you should do is get all the tokens in your file, and then check to see if it is a valid ordering of tokens.
Tokenization means you parse through your file and find all valid tokens and put them in an ordered list. A valid token in your case is any string length that starts with a < and ends with a >. You can safely discard the rest of the information I think? It would be easiest if you had a Token class to contain your token types.
Once you have that ordered list of tokens it is much easier to determine if they are a 'correct ordering' using your stack:
is_correct_ordering algorithm:
For each element in the list
if the element is an open-token, put it on the stack
if the element is a close-token
if the stack is empty return false
if the top element of the stack is a matching close token
pop the top element of the stack
else return false
discard any other token
If the stack is NOT empty, return false
Else return true
Naturally, having a reasonable Token class structure makes things easy:
class Token:
def matches(t: Token) -> bool:
pass # TODO Implement
#classmethod
def tokenize(token_string: str) -> Token:
pass # TODO Implement to return the proper subclass instantiation of the given string
class OpenToken:
pass
class CloseToken:
pass
class OtherToken:
pass
This breaks the challenge into two parts: first parsing the file for all valid tokens (easy to validate because you can hand-compare your ordered list with what you see in the file) and then validating that the ordered list is correct. Note that here, too, you can simplify what you're working on by delegating work to a sub-routine:
def tokenize_file(file) -> list:
token_list = []
while i < len(file):
token_string, token_end = get_token(file[i:])
token_list.append = Token.tokenize(token_string)
i = i + token_end # Skip to the end of this token
return token_list
def get_token(file) -> tuple:
# Note this is a naive implementation. Consider the edge case:
# <img src="Valid string with >">
token_string = ""
for x in range(len(file)):
token_string.append(file[x])
if file[x] == '>':
return token_string, x
# Note that this function will fail if the file terminates before you find a closing tag!
The above should turn something like this:
<html>Blah<meta src="lala"/><body><br/></body></html>
Into:
[OpenToken('<html>'),
OtherToken('<meta src="lala"/>'),
OpenToken('<body>'),
OtherToken('<br/>'),
CloseToken('</body>'),
CloseToken('</html>')]
Which can be much more easily handled to determine correctness.
Obviously this isn't a complete implementation of your problem, but hopefully it will help straighten out the awkwardness you've chosen with your current direction.

Resources