Python function - Global variable not defined - python

I joined a course to learn programming with Python. For a certain assignment we had to write the code which I have pasted below.
This part of the code consist of two functions, the first one being make_str_from_row and the second one being contains_word_in_row. As you might have noticed the second function reuses the first function. I already have passed the first function but I cannot pass the second one because when it has to reuse it gives an error about the first function, which is confusing because I did not get any errors for my first function. It says that global variable row_index is not defined.
By the way the second function has been given in a starter code so it cannot be wrong. I don't know what's wrong, especially because I have passed the code which presumable has to be wrong.
I tried asking the team for some feedback in case it might be some error in the grader but it has been a week and I have had no reply while the deadline is 2 days away. I am not asking for answers here I only would like to ask somebody for an explanation about the given error so I can figure out a solution myself. I would really appreciate the help.
def makestrfromrow(board, rowindex):
""" (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
"""
string = ''
for i in board[row_index]:
string = string + i
return string
def boardcontainswordinrow(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the rows of the board contains
word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB')
True
"""
for row_index in range(len(board)):
if word in make_str_from_row(board, row_index):
return True
return False

You named the argument rowindex but use the name row_index in the function body.
Fix one or the other.
Demo, fixing the name used in the body of the function to match the argument:
>>> def makestrfromrow(board, rowindex):
... string = ''
... for i in board[rowindex]:
... string = string + i
... return string
...
>>> makestrfromrow([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
Do note that both this function and boardcontainswordinrow are not consistent with the docstring; there they are named as make_str_from_row and board_contains_word_in_row. Your boardcontainswordinrow function uses make_str_from_row, not makestrfromrow, so you'll have to correct that as well; one direction or the other.

Related

get a character select if its int or str or a symbol

hi im having this problem this is my code rn but it wont do anything or just say its a int or a str
b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
c=['&','!','#','#','$','%']
a = input("Enter here :")
if type(a) ==int:
print("number")
if a==b:
print("word")
if a ==c:
print("symbol")
I tried putting a int or a str behind a input thing but that didn't solve the prob
i wanna write a code as clean as possible and not with list cuz they are long and hard to make.
There are couple things you need to know.
First of all, output of input function is always a string. So even though you enter a number like 523, python will see it as a string: "523".
You can use isnumeric to check if it can be converted into numbers like:
if(a.isnumeric()):print("number")
Secondly, if b is an array and you check equality of an array and a string which is a. In this case result will always be False.
So you should check like this
if(a in b):
...
and it's also same for c
The question is worded a little strangely but i'll give it a go. B is a list, so saying a==b will not be true if it is a word. you may be looking to see if the charater passed in (a) is IN list b. for that you will want to do if a in b. Also i believe all of the inputs a will come in as a string, so the first line if type(a) == int will never be true.
I would most likely use the is numeric function on the string input
if a.isnumeric():
you have some more work to do, I hope this was helpful and wish you luck

How do i do the checksum for Singapore Car License Plate Recognition with Python

I am able to do recognition of car license plate and extract the plate values. Sometimes, the results are inaccurate as i am using OCR to do the recognition. I uses a checksum to ensure only the correct results are being printed and viewed. After the calculation for the checksum, I need to use another formula to get the last letter of the plate. match with these 19 letter, A=0, Z=1, Y=2, X=3, U=4, T=5, S=6, R=7, P=8, M=9, L=10, K=11, J=12, H=13, G=14, E=15, D=16, C=17, B=18. Is there any way i can use a loop to like declare the values of this letters instead of doing it one by one manually? Please help out. Thank you.
You can use a list and perform the lookups according to your needs.
The list looks like this:
plate_letter_list = ['A', 'Z', 'Y', 'X', 'U', 'T', 'S', 'R', 'P', 'M', 'L', 'K', 'J', 'H', 'G', 'E', 'D', 'C', 'B']
Case 1: Lookup value from letter
If you need to find the numeric value associated with a letter, use the index method:
letter = 'T'
print(plate_letter_list.index(letter))
>> 5
Case 2: Lookup letter from value
If you need to find the letter associated with a numeric value, use it as index:
value = 13
print(plate_letter_list[value])
>> H
There are two ways to search for these values. One of it is to use the List datatype like #sal provided. The other way is to use Dictionary datatype
**
Solution using List Datatype
**
pl_vals_list = ['A', 'Z', 'Y', 'X', 'U', 'T', 'S', 'R', 'P', 'M', 'L', 'K', 'J', 'H', 'G', 'E', 'D', 'C', 'B']
You can then do a lookup either by position or by value
To search by position, will provide you the value you assigned to the alphabet.
print(pl_vals_list[0]). This will result in A.
Alternatively, you can search by the alphabet itself. In this case, you have to use the index() function.
print(pl_vals_list.index('A')). This will result in the assigned number you gave to the alphabet. The result will be 0
This provides you a means to look-up based on alphabet or value.
You can also check if the alphabet is inside the list using:
if 'A' in pl_vals_list:
#then do something for value A
elif 'B' in pl_vals_list:
#then do something for value B
else:
#then do something
You can also iterate through the list using a for loop and enumerate. However, I don't know if that will be of value to you.
for i, v in enumerate(pl_vals_list):
#do something with each value in the list
#here i will store the index, and v will have the value - A, B, C, etc
You can get the value of each of these and determine what you want to do.
**
Solution using Dictionary Datatype
**
Similarly, you can do the same using a dictionary.
pl_vals_dict = {'A':0, 'Z':1, 'Y':2, 'X':3, 'U':4, 'T':5, 'S':6, 'R':7, 'P':8, 'M':9, 'L':10, 'K':11, 'J':12, 'H':13, 'G':14, 'E':15, 'D':16, 'C':17, 'B':18}
To look for alphabets within a dictionary, you can use
if 'A' in pl_vals_dict.keys():
#then do something for value A
elif 'A' in pl_vals_dict.keys():
#then do something for value B
else:
#do something else
An alternate way to check for something would be:
x = True if 'F' in pl_vals_dict.keys() else False
In this case x will have a value of False
You can also use the get() function to get the value.
x = pl_vals_dict.get('A') # OR
print (pl_vals_dict.get('A')
The simplest way to look up a dictionary value is:
print (pl_vals_dict['A'])
which will result in 0
However, you have to be careful if you try to print value of 'F', it will throw an error as 'F' is not part of the key value pair within the dictionary.
print (pl_vals_dict['F'])
this will give you the following error:
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
pl_vals_dict['F']
KeyError: 'F'
Similar to list, you can also iterate through the dictionary for keys and values. Not sure if you will need to use this but here's an example for you.
for k, v in pl_vals_dict.items():
#do something with each pair of key and value
#here k will have the keys A Z Y X ....
#and v will have the values 1, 2, 3, 4, ....

(In Python) What's the difference between list(string).reverse() and list(string)[::-1]?

I can execute both expressions in Python shell without error:
string = 'this is a string'
list(string)[::-1]
(output) ['g', 'n', 'i', 'r', 't', 's', ' ', 'a', ' ', 's', 'i', ' ', 's', 'i', 'h', 't']
list(string).reverse()
I can do:
string = ''.join(list(string)[::-1])
which effectively reverse the string in place. However when I do:
string = ''.join(list(string).reverse()
I got an error:
TypeError: can only join an iterable
So list(string).reverse() does not return an iterable but list(string)[::-1] does. Can someone help me understand the underlying differences?
list(string).reverse() modifies the list in place and returns None
So you are are doing:
"".join(None)
Hence the error.
list.reverse() mutates the list it is called from so the list is altered after the call, while sequence[::-1] creates a new list and returns it, so the original list is unaffected.
list.reverse is returning None so you don't need to assign it back, but, seq[::-1] needs to be assigned back, Example:
l=[1,2,3]
print(l.reverse())
print(l)
Output:
None
[3,2,1]
Example 2:
l=['a','b','c']
print(l[::-1])
print(l)
Output:
['c','b','a']
['a','b','c']
Example 2 needs to be assigned back

looking for unique elements in chemical species

Determining unique elements: Write a function which, when given a list of species,
will return an alphabetized list of the unique elements contained in the set of species.
Make use of the parser from the previous step. Example: calling your function with
an input of ['CO', 'H2O', 'CO2', 'CH4'] should return an output of ['C', 'H',
'O']
This is part of a larger project that I am doing.
The problem I am having is how to look at the individual characters of each element. Once I have this I should be able to check if its unique or not. I know this is not right, its just a rough idea of something I am thinking.
def unique_elements(x):
if x in y
else
y.append(x)
return y
>>> def sanitize(compound):
return compound.translate(None,string.digits)
>>> def elementazie(compoud):
return re.findall("([A-Z][a-z]*)",compoud)
>>> sorted(set(chain(*(elementazie(sanitize(s)) for s in species))))
['Au', 'C', 'H', 'O']

How do i get words from rows and columns having letters?

doing an assignment and struck to this problem
def board_contains_word(board, word):
'''(list of list of str, str) -> bool
Return True if and only if word appears in board.
Precondition: board has at least one row and one column.
>>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
True
'''
return word in board
but i am getting FALSE
Thanks in advance
The python in operator works a bit differently from how you're using it. Here are some examples:
>>> 'laughter' in 'slaughter'
True
>>> 1 in [1,6,5]
True
>>> 'eta' in ['e','t','a']
False
>>> 'asd' in ['asdf','jkl;']
False
>>>
As you can see, it's got two major uses: testing to see if a string can be found in another string, and testing to see if an element can be found in an array. Also note that the two uses can't be combined.
Now, about solving your problem. You'll need some sort of loop for going through all of the rows one by one. Once you've picked out a single row, you'll need some way to join all of the array elements together. After that, you can figure out if the word is in the board.
Note: this only solves the problem of searching horizontally. Dunno if that's the whole assignment. You can adapt this method to searching vertically using the zip function.
Here's something to get you unstuck:
def board_contains_word(board, word):
# check accross
for row in board:
return word in ''.join(row):
# try with board's rows and columns transposed
for row in zip(*board):
return word in ''.join(row):
return False
print board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
print board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'TO')
Hint: You could simplify things by using the any() function.

Categories