how can I make it better? is there any algorithm/method to make it better and shorter?
def sub_string_finder(string):
given_string = string.upper()
substring_of = []
length = len(given_string)
# find all substring and put it in substring array
for i in range(length):
for j in range(i + 1, length + 1):
substring_of.append(given_string[i:j])
return substring_of
s = input("Enter a string: ")
print(f"Number of substring: {len(sub_string_finder(s))}")
print(sub_string_finder(s))
Output for "developer":
Number of substring: 45
['D', 'DE', 'DEV', 'DEVE', 'DEVEL', 'DEVELO', 'DEVELOP', 'DEVELOPE', 'DEVELOPER', 'E', 'EV', 'EVE', 'EVEL', 'EVELO', 'EVELOP', 'EVELOPE', 'EVELOPER', 'V', 'VE', 'VEL', 'VELO', 'VELOP', 'VELOPE', 'VELOPER', 'E', 'EL', 'ELO', 'ELOP', 'ELOPE', 'ELOPER', 'L', 'LO', 'LOP', 'LOPE', 'LOPER', 'O', 'OP', 'OPE', 'OPER', 'P', 'PE', 'PER', 'E', 'ER', 'R']
Update
This is the final answer until now using itertools
and combinations
, Thanks to the respondents. To increase readability we can use line break. Remember that Python allows line breaks between brackets and braces.
from itertools import combinations
def sub_string_finder(string):
substring_of = [
string.upper()[i:j]
for i, j in combinations(range(len(string) + 1), r=2)
]
return substring_of
If you are interested in learning about Python List Comprehensions, you can chek this.