-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathps5_recursion.py
More file actions
82 lines (65 loc) · 1.93 KB
/
ps5_recursion.py
File metadata and controls
82 lines (65 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# 6.00x Problem Set 5
#
# Part 2 - RECURSION
#
# Problem 3: Recursive String Reversal
#
def reverseString(aStr):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are allowed to use are indexing,
slicing, and concatenation.
aStr: a string
returns: a reversed string
"""
if aStr == '':
return aStr
else:
return aStr[-1] + reverseString(aStr[:-1])
#
# Problem 4: Erician
#
def x_ian(x, word):
"""
Given a string x, returns True if all the letters in x are
contained in word in the same order as they appear in x.
>>> x_ian('eric', 'meritocracy')
True
>>> x_ian('eric', 'cerium')
False
>>> x_ian('john', 'mahjong')
False
x: a string
word: a string
returns: True if word is x_ian, False otherwise
"""
if len(x) == 0:
return True
elif len(word) == 0:
return False
elif x[0] == word[0]:
return x_ian(x[1:], word[1:])
else:
return x_ian(x, word[1:])
#
# Problem 5: Typewriter
#
def insertNewlines(text, lineLength):
"""
Given text and a desired line length, wrap the text as a typewriter would.
Insert a newline character ("\n") after each word that reaches or exceeds
the desired line length.
text: a string containing the text to wrap.
line_length: the number of characters to include on a line before wrapping
the next word.
returns: a string, with newline characters inserted appropriately.
"""
return insertNewlinesRec(text, lineLength, lineLength-1)
def insertNewlinesRec(text, lineLength, remLength):
if text == '':
return ''
elif text[0] == ' ' and remLength <= 0:
return '\n' + insertNewlinesRec(text[1:], lineLength, lineLength-1)
else:
return text[0] + insertNewlinesRec(text[1:], lineLength, remLength-1)