First of all, what is a string “splosion”. Let’s consider a non-empty string, “hello” for example. You will need to return a string like “hhehelhellhello”.
def stringSplosion(initial_string): resulted_string = "" for s in range(len(initial_string)): resulted_string = resulted_string + initial_string[:s+1] return resulted_string
So, we declare a function called
stringSplosion which takes in an argument, the string
Within the function we create an empty string which is going to be our result.
Now, we start iterating over the initial string. Every time we iterate we add the characters from the beginning of the string up to the s plus 1.
Let’s try it in the terminal:
>>> def stringSplosion(initial_strig): ... resulted_string = "" ... for s in range(len(initial_string)): ... resulted_string = resulted_string + initial_string[:s+1] ... return resulted_string ... >>> initial_string = "hello" >>> stringSplosion(initial_string) 'hhehelhellhello'
The idea is:
- We want to iterate as many times as the length of the
initial_stringis. For that we use the line
for s in range(len(initial_string)):.
resulted_stringis empty initially. With every iteration we add something to it. At the first iteration the
sis 0 (Which is the index of the first element of the string).
- At the second iteration the
resulted_stringwon’t be empty, it will be “h” and this time we add to it the “he”.
- The same procedure continues as many times as the length of the initial string is
This kind of problems can come up in a job interview and they are definitely something you have to know if you want to find a job in this field.