def function producing incorrect output - python

My task is to:
Write a function, starts_with(word, chs) that returns whether or not the string word begins with one of the characters in the list chs.
If word is an empty string, return False.
If chs is an empty list, return False.
I'm passing 6/7 test cases except for one which shows an Assertion error, however, I don't know what input is being used in each test case so I can't figure out the issue. What could the issue be?
def starts_with(word, chs):
x = 0
if (len(chs)== 0) or (word == ""):
return (False)
while x < len(chs):
s = word[0]
if s == chs[x]: {
}
x += 1
return (True)
word = ()
chs = ()

Try approaching this task using the proper Python builtin functions rather than apply C/Java-style programming. It is way more readable.
Using string.startswith():
def starts_with(word, chs):
for c in chs:
if word.startswith(c):
return True
return False #you can avoid this line, it will return None by default
Another way would be to check if the first letter of word is in chs:
def f(word, chs):
if word and chs and word[0] in chs:
return True
return False

Try this:
def starts_with(word, chs):
if (len(chs)== 0) or (word == ""):
return False
elif word[0] in chs:
return True
an update:
def starts_with(word, chs):
if not word: return False
elif word[0] in chs:
return True

Related

Find one character in a string of any number of characters and return True or False

I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.
def contains_char(any_length: str, single_character: str) -> bool:
"""A way to find one character in a word of any length."""
assert len(single_character) == 1
any_length = ""
single_character = ""
check_character: bool = False
i: int = 0
while i < len(any_length):
if any_length[i] == single_character[0]:
check_character is True
else:
i += 1
alternative_char: int = 0
while check_character is not True and i < len(any_length):
if any_length[alternative_char] == single_character[0]:
check_character == True
else:
alternative_char += 1
if check_character is not False:
return False
else:
return True
in keyword uses linear search and returns boolean value O(n).
def contains_char(any_length: str, single_character: str) -> bool:
return single_character in str
Linear search follows
def contains_char(any_length: str, single_character: str) -> bool:
# For each loop iterates through each character in string
for char in str:
if char == str:
return True
return False
Maybe I'm missing something but Python's in operator does this out the box.
if single_character in any_length:
return True
else:
return False
you are making another mistake in the start of the function:
any_length = ""
after you change the value of any_length your function will never work
in Does this for you:
def char_in_word(word, char):
return char in word
However if you don't want to use builtin, use this:
def char_in(word, char):
for i in word:
if i == char:
return True
return False
def contains_char(string,character):
if character in string:
return True
return False

nested if python executed in one case but not in another similar condition

Hi please find my code below:
def isIn(char, aStr):
#char: a single character
#aStr: an alphabetized string
#returns: True if char is in aStr; False otherwise
length=len(aStr)
print(length, aStr) #check
if length == 0:
return False
elif length == 1:
if char == aStr:
return True
else:
return False
elif char==aStr[int(length/2)]:
return True
elif char<aStr[int(length/2)]:
print("checked")
aStr=aStr[0:int(length/2)]
isIn(char,aStr)
elif char>aStr[int(length/2)]:
isIn(char,aStr[int(length/2):-1])
if i run with
a='b'
s='b'
v=isIn(a,s)
print(v)
prints out True at the last line
if i run with
a='b'
s='bcd'
v=isIn(a,s)
print(v)
prints out None when it should print True. Any ideas?
you don't need to write a lot of code, you can just do:
def isIn(char, aStr):
return char in aStr
the 'in' keyword will return True if char is in aStr and False otherwise

Trying to write a can it construct function getting a ValueError: substring not found error

def canConstruct(target, wordBank):
if target == '': #if there are no words in wordBank
return True
for word in wordBank:
if target.index(word) == 0: #checks if current word is current targets prefix
suffix = target.removeprefix(word)
if canConstruct(suffix, wordBank) == True:
return True
return False
print(canConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeef",["e","ee","eee","eeee","eeeee","eeeeee","eeeeeee"] ))
i dont get why it is throwing this error
ValueError: substring not found
Note that: removesuffix() is only available after Python v3.9. Doc
So if you are on earlier version, I think you can simply adjust your code as below:
def canConstruct(target, wordBank):
if (target == ''): return True
for word in wordBank:
if (target.startswith(word)):
suffix = target[len(word):]
if (canConstruct(suffix, wordBank) == 0):
return True
return False
You're getting that error because of this line:
if target.index(word) == 0:
If you pass a substring into the index method, and that substring doesn't exist within the superstring, than this error would occur.
For instance, if:
target = 'test string'
word = 'z'
When we try to index() target for word, the index() method won't be able to find word within target and will raise the exception you are having.
It's possible you simply have this line reversed, and are instead wanting to find target within word.
In that case you'll want to do this instead:
if word.index(target) == 0:
def canConstruct(target, wordBank):
if target == '':
return True
for word in wordBank:
if target.startswith(word):
suffix = target.removeprefix(word)
if canConstruct(suffix, wordBank) == True:
return True
return False
print(canConstruct("abcdef", ["ab", "abc", "cd", "def", "abcd", ]))

trying to do a python for code without using the "in" operator and it's not working

Simple assignment from uni, supposed to find a word in a list and print if true without using the "in" operator. I've instead used = and it's just not printing anything. Is there something wrong with the code or is there an alternative I'm missing?
wordlist = ["hi", "many","way","photo","mobile"]
def word_in_list_for(words,word):
for word = wordlist:
if word == wordlist:
return True
else:
continue
print(word_in_list_for(wordlist,"bild"))
def word_in_wordlist(words, word):
i = 0
while i < len(words):
if words[i] == word:
return True
i += 1
return False
Testing:
In [221]: wordlist = ["hi", "many","way","photo","mobile"]
In [222]: print(word_in_wordlist(wordlist,"bild"))
False
In [223]: print(word_in_wordlist(wordlist,"photo"))
True
Do this:
wordlist = ["hi", "many","way","photo","mobile"]
def word_in_list_for(words,word):
i = 0
while wordlist[i]:
if word == wordlist[i]:
return True
else:
i += 1
print(word_in_list_for(wordlist,"bild"))
Tell me if this works
You can use set
wordlist = ["hi", "many","way","photo","mobile"]
def word_in_list_for(words,word):
words_set = set(words)
return {word}.issubset(words_set)
print(word_in_list_for(wordlist,"bild"))
False
You should use the indexing. I have written an working example from your code. You can find the explanation as comments in script.
Code:
wordlist = ["hi", "many", "way", "photo", "mobile"]
def word_in_list_for(words, word):
for index in range(len(words)): # Get the indexes of your list.
if word == words[index]: # If the value of the index is the same as word
return True # Return True
return False # The the elem is not is the list return False
print(word_in_list_for(wordlist, "bild"))
Successful test (word_in_list_for(wordlist, "mobile")) :
>>> python3 test.py
True
Unsuccessful test (word_in_list_for(wordlist, "bild")) :
>>> python3 test.py
False

Accounting spaces in palindrome program

This is a program that accepts a string of words and checks if the words are palindromes and if it is one, it prints it. However if a string has a space in it, my program won't count it as a palindrome (Example: nurses run). What should I be adding to make the program exclude the space, when it's accounting for palindromes?
Palindrome: a word, phrase, or sequence that reads the same backwards as forwards, e.g. 'madam' or 'nurses run'
import sys
strings = []
for s in sys.argv[1:]:
strings += [s]
def is_palindrome(word):
if len(word) <= 2 and word[0] == word[-1]:
return True
elif word[0] == word[-1]:
is_palindrome(word[1:-1])
return True
else:
return False
def printpalindromes(strings):
for s in strings:
if is_palindrome(s) == True:
print(s)
printpalindromes(strings)
Try stripping out the whitespaces before doing the palindrome check
>>> x = "nurses run"
>>> x.replace(" ", "")
'nursesrun'
You can use reversed:
def palindrome(word):
if ' ' in word:
word = word.replace(' ', '')
palindrome = reversed(word)
for letter, rev_letter in zip(word, palindrome):
if letter != rev_letter:
return 'Not Palindrome'
return 'Palindrome'
Your code is still incorrect in the elif statement. You've added return True when you should actually be returning the response from your recursive call as previously mentioned.
def is_palindrome(word):
if len(word) <= 2 and word[0] == word[-1]:
return True
elif word[0] == word[-1]:
return is_palindrome(word[1:-1])
else:
return False
Here's a simpler solution of your problem:
import sys
sys.argv = [" nurses ", " run "]
word = "".join([s.strip() for s in sys.argv])
print("{} {} palindrome".format(word, "is" if word == word[::-1] else "is not"))
or you can just create the word out of sys.argv like this:
word = "".join(sys.argv).replace(" ","")

Categories

Resources