Skip to content

Commit fdf4e94

Browse files
Create len_nth_word_from_end.py
1 parent 5a7df75 commit fdf4e94

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# checks the length of the nth word from the end
2+
def len_nth_word_from_end_1(str, num):
3+
plc = -1
4+
5+
while num != 0 and plc >= -1 * len(str):
6+
# accounts for the case of no space at the end of the string after the last word
7+
if str[plc] != ' ':
8+
while plc >= -1 * len(str) and str[plc] != ' ':
9+
plc -= 1
10+
else:
11+
start = plc +1
12+
# accounts for the case of at least one space at the end of the string after the last word
13+
else:
14+
while plc >= -1 * len(str) and str[plc] == ' ':
15+
plc -= 1
16+
else:
17+
end = plc
18+
while plc >= -1 * len(str) and str[plc] != ' ':
19+
plc -= 1
20+
else:
21+
start = plc +1
22+
plc = start - 1
23+
num -= 1
24+
25+
else:
26+
if num != 0:
27+
return -1
28+
return len(str[start: end + 1])
29+
30+
# checks the length of the nth word from the end using split
31+
def len_nth_word_from_end_2(str, num):
32+
ls = str.split(" ")
33+
print(ls)
34+
plc = -1
35+
word_num = 0
36+
while plc >= -1 * len(ls):
37+
# accounts for a variable number of whitespaces between words
38+
if ls[plc] != '':
39+
word_num += 1
40+
if word_num == num:
41+
return len(ls[plc])
42+
else:
43+
plc -= 1
44+
else:
45+
return -1
46+
47+
s = "fly me to the moon "
48+
49+
print(len_nth_word_from_end_len_1(s, 5))
50+
print(len_nth_word_from_end_len_2(s, 3))

0 commit comments

Comments
 (0)