I am new to python and I want to make the first character from the first string, followed by the last character from the second string like this
>>>String("aceg", "kjihfdb")
abcdefghijk
I am new to python and I want to make the first character from the first string, followed by the last character from the second string like this
>>>String("aceg", "kjihfdb")
abcdefghijk
First, let me make it clear that it's always best practice to provide a rundown of what attempts you have made to tackle the problem. This way, it makes it easier for other people to point out where you might have gone wrong and lead you to the right direction.
This point notwithstanding, here's one way to approach the problem using basic recursion.
def String(str1, str2):
if len(str1) == 0:
return str2[::-1]
elif len(str2) == 0:
return str1
else:
return str1[0] + str2[-1] + String(str1[1:], str2[:-1])
As with any recursion problem, we establish a base case. In the context of this question, the base case would be if any of the arguments of the String
function are empty. If the first argument is empty, we have to reverse the second string; conversely, if the second string is of length 0, we simply return the first string as it is. If neither of them are empty, we invoke a recursive call on the function, as shown in the last else
statement. Specifically, we concatenate the first character of the first string and the last character of the last string with the returned result of the recursive call.
If anything is unclear, I'd be happy to answer any additional questions you might have.
def weave_words(first, second):
...
Let's do this by hand.
first = "aceg"
second = "kjihfdb"
First, you want to reverse the second word (and keep the first word as is):
first = "aceg"
second = "bdfhijk"
Then, you want to weave them together, picking one element from each word in turn, until one of them (the shorter word) runs out of elements, then you just tack the remaining elements in the other (the longer word) onto the result.
You can start by trimming the longer one so that it is equal in length to the shorter one.
first = "aceg"
second = "bdfh"
remainder = "ijk"
Then you weave the equal length arms like so:
weave = "abcdefgh"
remainder = "ijk"
Then tack the remainder onto it:
weave = "abcdefgh"
Try to work with this logic to get a solution for yourself. If you don't eventually reach a satisfactory solution, feel free to reach out in the comment section under this answer. I'll provide you with code and explanation.
But first, you'll have to show me your own attempt.
Funny oneline solution :
def String(a, b):
return ''.join(''.join((a[index], b[-index - 1])) for index in range(min(len(a), len(b)))) + (b[-len(a) - 1::-1] if len(a) < len(b) else a[len(b) or 1 - 1:])
print(String(a, b))
With some itertools
...
>>> ''.join(chain(*zip_longest(s, reversed(t), fillvalue='')))
'abcdefghijk'