'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
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
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
Solution 5:[5]
def contains_char(string,character):
if character in string:
return True
return False
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Karim Tabet |
| Solution 3 | yotamolenik |
| Solution 4 | |
| Solution 5 | keineahnung2345 |
