Reputation: 129
I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.
This is what i have so far:
name = input("Put in a name: ")
name_length = len(name)
for counter in range(name_length,0, -1):
print(counter)
Below Is what it is supposed to end like
Upvotes: 1
Views: 253
Reputation: 1495
I think it will work:
name = input("Put in a name: ")
for i in range(len(name)): # for 1st half
print(name[i:])
for i in range(len(name)-2,-1,-1): # for 2nd half
print(name[i:])
Input:
stack
Output:
stack
tack
ack
ck
k
ck
ack
tack
stack
I Split output into two halfs:
1st half:
stack
tack
ack
ck
k
Which will be achieved by 1st for
loop using Slice (check to understand more Explain Python's slice notation)
And 2nd half:
ck
ack
tack
stack
Note: You can print single character in this example k
in 1st for
loop like i do or in 2nd for
loop, it up to you.
Hope this helps.
Although I think you should use solution suggested by @Andrew it's pretty cool if you print a
in his solution you get the sequence [0, 1, 2, 3, 4, 3, 2, 1, 0]
for slice the string so can be done in single for
loop
Upvotes: 1
Reputation: 1082
This is an approach that just uses a single loop and slicing to achieve the same end. It creates a list of the indices at which the slice should begin, and then steps through that list printing as it goes.
name = "Bilbo"
a = range(len(name))
a = a[:-1] + a[::-1]
for idx in a:
print name[idx:]
Upvotes: 0
Reputation: 191844
Recursive answer
Essentially, print the same string twice, but in-between call the function again, but with the first character removed. When the start index is greater than the length of the string - 1, then you have one character left.
def printer(str, start=0):
s = str[start:]
if len(str) - 1 <= start:
print s
return
print s
printer(str, start + 1)
print s
Output
Put in a name: cricket_007
cricket_007
ricket_007
icket_007
cket_007
ket_007
et_007
t_007
_007
007
07
7
07
007
_007
t_007
et_007
ket_007
cket_007
icket_007
ricket_007
cricket_007
Upvotes: 0