Last active
August 29, 2015 14:14
-
-
Save cshjin/0872f806ee937750aa04 to your computer and use it in GitHub Desktop.
Temp solutions to theReq problems solving in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If you have access to a function that returns a random integer from one to five, | |
# write another function which returns a random integer from one to seven. | |
import random | |
class Solution(): | |
def rand5(self): | |
return random.randint(1, 5) | |
def rand7(self): | |
while True: | |
r = 5 * (self.rand5() - 1) + self.rand5() | |
if r <= 21: | |
break | |
return r % 7 + 1 | |
s = Solution() | |
print s.rand7() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Write an iterative function to reverse a string. | |
# Do the same thing as a recursive function. | |
class Solution(object): | |
def s_reverse(self, s): | |
length = len(s) | |
tmp = [] | |
for i in range(length - 1, -1, -1): | |
tmp.append(s[i]) | |
return "".join(tmp) | |
def r_reverse(self, s): | |
if len(s) == 0: | |
return "" | |
else: | |
return s[-1] + self.r_reverse(s[:-1]) | |
s = Solution() | |
print s.s_reverse("Hello!") | |
print s.r_reverse("Hello!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment