I am new to python and I have a requirement to print python keyword in the below format in right pyramid fashion.
p
py
pyt
pyth
pytho
python
pytho
pyth
pyt
py
p
I have done some trials and I have come up with a code as below. Could any one kindly suggest if there is any alternative ways of doing the same please.
string = 'python'
for i in range(0, len(string)):
print(string[:i 1])
for i in range(len(string)):
print(string[:-(i 1)])
I am curious to know if there is any other way of doing it. Any leads will help learn alternate ways. Thanks
CodePudding user response:
There are many alternatives. The code shown in the question will be efficient due to the lack of comparisons. The code shown in this answer is more concise but is likely to be less efficient (I haven't timed it)
s = 'python'
for i in range(1, len(s)*2):
print(s[:i] if i <= len(s) else s[:len(s)-i])