I wanted to implement the code by using recursive function without for loop or while loop.
And I wanted to implement function called go_through() and take two parameters as a list(list1) and an integer(letters) so that if the element of each length of string has bigger or equal to integer , I replace it using the other function called replace_it()
def go_through(list1, letters):
get_list = list1[:]
num =len(list1)
index = 0
if index != num:
if len(get_list[0]) >= letters:
get_list += replace_it(get_list[0])
index += 1
print(get_list, 'True')
return go_through(get_list[1:], letters)
else:
get_list += [get_list[0]]
index += 1
print(get_list, 'False')
return go_through(get_list[1:], letters)
else:
print(get_list)
def replace_it(string):
if string == 'pineapple':
return ['peach', 'and', 'pear']
if string== 'delicious':
return ['really', 'gross']
go_through(['pineapple','is','delicious','I', 'want', 'it'],7)
should be looking like
peach and pear is really gross I want it
So I have a problem for this codes It doesn't allow me to stop print as what I want to print is one line
The result would be looking like the picture I attached But I want to stop where I highlighted and return it as it is the same output what I wrote above.
How can I fix this problem?
The list is not reducing at any point. get_list += [get_list[0]]
in the else
block keeps the list the same size when followed by return go_through(get_list[1:], letters)
, while get_list += replace_it(get_list[0])
in the if
will always extend the list.
Maybe you meant something like
else:
# this isn't needed
# get_list += [get_list[0]]
return go_through(get_list[1:], letters)
Also, it seems that you're getting the list order mixed up in the first bit maybe.
if len(get_list[0]) >= letters:
# this is adding the new list at the end, not replacing the word
# get_list += replace_it(get_list[0])
# you can send the shortened list to the function again,
# and stick the replacement words at the start
return replace_it(get_list[0]) + go_through(get_list[1:], letters)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.