File tree Expand file tree Collapse file tree 1 file changed +3
-33
lines changed
Data Structures and Algorithms Expand file tree Collapse file tree 1 file changed +3
-33
lines changed Original file line number Diff line number Diff line change 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
1
# checks the length of the nth word from the end using split
31
- def len_nth_word_from_end_2 (str , num ):
2
+ def len_nth_word_from_end (str , num ):
32
3
ls = str .split (" " )
33
4
plc = - 1
34
5
word_num = 0
@@ -44,6 +15,5 @@ def len_nth_word_from_end_2(str, num):
44
15
return - 1
45
16
46
17
s = "fly me to the moon "
47
-
48
- print (len_nth_word_from_end_1 (s , 5 ))
49
- print (len_nth_word_from_end_2 (s , 3 ))
18
+ print (len_nth_word_from_end (s , 3 ))
19
+ print (len_nth_word_from_end (s , 6 ))
You can’t perform that action at this time.
0 commit comments