Skip to content

Commit 3702a6b

Browse files
authored
Merge pull request larymak#262 from Sonia-Sandler/main
Add len_nth_word_from_end
2 parents 653804d + 299bd1b commit 3702a6b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# checks the length of the nth word from the end using split
2+
def len_nth_word_from_end(str, num):
3+
ls = str.split(" ")
4+
plc = -1
5+
word_num = 0
6+
while plc >= -1 * len(ls):
7+
# accounts for a variable number of whitespaces between words
8+
if ls[plc] != '':
9+
word_num += 1
10+
if word_num == num:
11+
return len(ls[plc])
12+
else:
13+
plc -= 1
14+
else:
15+
return -1
16+
17+
s = "fly me to the moon "
18+
print(len_nth_word_from_end(s, 3))
19+
print(len_nth_word_from_end(s, 6))

0 commit comments

Comments
 (0)