Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Data Structures and Algorithms/len_nth_word_from_end.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# checks the length of the nth word from the end using split
def len_nth_word_from_end(str, num):
ls = str.split(" ")
plc = -1
word_num = 0
while plc >= -1 * len(ls):
# accounts for a variable number of whitespaces between words
if ls[plc] != '':
word_num += 1
if word_num == num:
return len(ls[plc])
else:
plc -= 1
else:
return -1

s = "fly me to the moon "
print(len_nth_word_from_end(s, 3))
print(len_nth_word_from_end(s, 6))