niese niese - 6 months ago 19
Python Question

Reads a word and prints all substrings, sorted by length in Python

I have code a program to reads a word and prints all substrings, sorted by length. For example, if the user provides the input "rum" , the program prints

r

u

m

ru

um

rum


Code below is what I have done and manage to print:

r

u

m

ru

um

m


The problem that I'm not understand, how to make the loop print the correct output for the last word from 'm' to 'rum' .. what did I miss?

If anyone able to point the way to correct my loop in my code, I would really appreciated. Many thanks!

word = input("\nPlease enter a word : ")
length = 1
pos = 0

for i in range(length, len(word)):
for j in range(pos, len(word)):
print(word[j:i+j])

Answer

I just put print() to see what is j and i+j every time your for loop processed. Here is the problem;

word = input("\nPlease enter a word : ")
length = 1
pos = 0

for i in range(length, len(word)):
    for j in range(pos, len(word)):
        print (j)
        print (i+j)
        print(word[j:i+j])
        print ("------------")

Output:

>>> 

Please enter a word : rum
0
1 #word[0:1]
r
------------
1
2 #word[1:2]
u
------------
2
3 #word[2:3]
m
------------
0
2  #word[0:2]
ru
------------
1
3  #word[1:3]
um
------------
2
4 #word[2:4] which is only m.
m
------------
>>>

Your codes trying to print word[2:4] at the last part which is only m.That's the problem, that's why it only prints m instead of whole word.

Use combinations() it's better.

from itertools import combinations

word = "rum"
for x in range(len(word)+1):
    for c in combinations(word,x):
        print ("".join(c))

Output:

>>> 
r
u
m
ru
rm
um
rum
>>>