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.
Related
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
I am working on a function to print the list elements in reverse order using recursion. I came up with the following code
class Solution:
def __init__(self):
self.count=0
def reverseString(self, s):
def helper(s):
"""
Do not return anything, modify s in-place instead.
"""
print(s[:])
if len(s)>1:
s[0],s[len(s)-1]=s[len(s)-1],s[0]
print('s[0]',s[0])
print('s[len(s)-1]',s[len(s)-1])
helper(s[1:len(s)-1])
helper(s)
As you see, I am using print statements to debug the code. I get the following output
['h', 'e', 'l', 'p', 'o']
s[0] o
s[len(s)-1] h
['e', 'l', 'p']
s[0] p
s[len(s)-1] e
['l']
['o', 'e', 'l', 'p', 'h']
I see that my logic is working that there is something fundamental I am missing about variable update at local and global level. Can someone explain to me why I am swapping the first and last list element but my list output is not correct? I expect the output to be ['o', 'p', 'l', 'e', 'h']
On the other hand below modification seems to work fine
class Solution:
def __init__(self):
self.count=0
def reverseString(self, s):
def helper(left,right):
"""
Do not return anything, modify s in-place instead.
"""
print(s[:])
if left<right:
s[left],s[right]=s[right],s[left]
print('s[0]',s[left])
print('s[len(s)-1]',s[right])
helper(left+1,right-1)
helper(0,len(s)-1)
x=Solution()
s=["h","e","l","p","o"]
x.reverseString(s)
print(s)
['h', 'e', 'l', 'p', 'o']
s[0] o
s[len(s)-1] h
['o', 'e', 'l', 'p', 'h']
s[0] p
s[len(s)-1] e
['o', 'p', 'l', 'e', 'h']
['o', 'p', 'l', 'e', 'h']
I looked at the discussion Python inplace update of function arguments? and Immutable vs Mutable types which could possibly be related.
Your code essentially swaps two elements together and in your last line of code, you are swapping only the first and last. Your code should find a way to swap all elements not just the first and last.
I think something like the code below might do the trick.
Notice how the print is done after the recursive call, this is done on purpose, because when the call stack returns it executes all the calls in reverse order, which applies for the prints statements after the recursive calls.
def reverse_print(list):
if list: # As long as the list is not empty proceed with the recursion / print.
reverse_print(list[1:]) # Start from the next list element.
print(list[0]) # The print statement is after the recursive call, on purpose.
else: # The list is been reduced one element at a time until it reaches 0 length.
return
s = ["h", "e", "l", "p", "o"]
reverse_print(s)
When run this prints the list of strings containing a single character in reverse order:
o p l e h
So i'm wondering why this:
'alpha' in 'alphanumeric'
is True, but
list('alpha') in list('alphanumeric')
is False.
Why does x in s succeed when x is a substring of s, but x in l doesn't when x is a sublist of l?
When you use list function with any iterable, a new list object will be created with all the elements from the iterable as individual elements in the list.
In your case, strings are valid Python iterables, so
>>> list('alpha')
['a', 'l', 'p', 'h', 'a']
>>> list('alphanumeric')
['a', 'l', 'p', 'h', 'a', 'n', 'u', 'm', 'e', 'r', 'i', 'c']
So, you are effectively checking if one list is a sublist of another list.
In Python only Strings have the in operator to check if one string is part of another string. For all other collections, you can only use individual members. Quoting the documentation,
The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.
For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.
For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
For the second one you are asking if
['a', 'l', 'p', 'h', 'a'] in ['a', 'l', 'p', 'h', 'a', 'n', 'u', 'm', 'e', 'r', 'i', 'c']
and there is no sub-list in the second list only characters.
['a', 'l', 'p', 'h', 'a'] in [['a', 'l', 'p', 'h', 'a'], ['b', 'e', 't', 'a']]
would be true
lists determine membership if an item is equal to one of the list members.
strs determine whether string a is in string b if a substring of b is equal to a.
I suppose you are looking for the fact that string and list has different implementations of __contains__ magic method.
https://docs.python.org/2/reference/datamodel.html#object.contains
This is why 'alpha' in 'alphanumeric' is True, but
list('alpha') in list('alphanumeric') is False
maybe you should try issubset method.
>>> set('alpha').issubset(set('alphanumeric'))
True
although set('alpha') returns set(['a', 'p', 'l', 'h']), and set('alphanumeric'), set(['a', 'c', 'e', 'i', 'h', 'm', 'l', 'n', 'p', 'r', 'u']).
set method makes a list ignoring repetetive elements.
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.
def make_str_from_row(board, row_index):
''' (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'
'''
for i in range(len(board)):
i = row_index
print(board[i])
This prints ['A', 'N', 'T', 'T']
How do I print it like this 'ANTT' instead?
Well, you got what you told to print!
board is a list of list of strs, so board[i] must be a list of strs, and when you write print(board[i]), you get a list!
You may need to write this:
print(''.join(board[i]))
You could simplify that a whole lot by using
>>> def make_str_from_row(board, row_index):
... print repr(''.join(board[row_index]))
...
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
The reason you get that output is because you print a list since the elements of board are lists. By using join, you get a string.
Also, I don't understand why you use a loop if are going to change the index you loop over.
I think this was what you were trying to do:
def make_str_from_row(board, row_index):
''' (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'
'''
for cell in board[row_index]:
print cell,