Two versions, return opposite answers, but always one comes out wrong. I'm not sure where I've gone wrong. I've tried a series of other options, but this seems to get the closest. EDIT: Needs to be in a loop
goals: identify element in list, identify when element is not in list, identify when list is [], return strings accordingly.
def search_for_string(a_list, search_term):
i=0
for search_term in a_list:
i += 1
if a_list[i] == search_term:
return 'string found!'
elif a_list[i] != search_term:
return 'string not found2'
if len(a_list) == 0:
return 'string not found'
apple = search_for_string(['a', 'b', 'c'], 'd')
print(apple)
def search_for_string(a_list, search_term):
i=0
for search_term in a_list:
if a_list[i] == search_term:
return 'string found!'
elif a_list[i] != search_term:
return 'string not found2'
i += 1
if len(a_list) == 0:
return 'string not found'
apple = search_for_string(['a', 'b', 'c'], 'd')
print(apple)
other tests:
apple = search_for_string(['a', 'b', 'c'], 'b')
apple = search_for_string([], 'b')
Python makes your life super easy for this sort of thing:
def search_for_string(a_list, search_term):
if search_term in a_list:
return 'string found!'
return 'string not found'
There are few things wrong and Non-Pythonic in your code:
def search_for_string2(a_list, search_term):
i=0 # <----- Not Pythonic! If you want to get index we use enumerate(a_list)
for search_term in a_list: # <--- search_term passed to function is lost and gets overwritten by elements in a_list.
i += 1 # <--- Not Pythonic in this context
if a_list[i] == search_term: #<--- a_list[index+1] == a_list[index]. True if consecutive elements are same else False!
return 'string found!' #<--- No WRONG!, You didn't find the string, Consecutive elements are same!
elif a_list[i] != search_term:
return 'string not found2' #<-- Consecutive elements are not same!
if len(a_list) == 0:
return 'string not found'
According to the goals you have defined you can implement it like so:
def search_for_string(alist, search_term):
if not alist:
return "List is empty"
if search_term in alist:
return "First occurence of string Found at index position: " + str(alist.index(search_term))
else:
return "String not found"
print(search_for_string(['a', 'b', 'c'], 'd'))
print(search_for_string(['a', 'b', 'c'], 'b'))
print(search_for_string([], 'b'))
Output:
String not found
First occurence of string Found at index position: 1
List is empty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With