This repository was archived by the owner on Jan 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.py
More file actions
66 lines (50 loc) · 1.86 KB
/
strings.py
File metadata and controls
66 lines (50 loc) · 1.86 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
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""Collection of answers to string questions."""
__author__ = 'Hwasung Lee'
def is_unique(string):
"""Check whether a string has unique characters."""
return len(string) == len(set(string))
def is_unique_without_extra(string):
"""Check whether a string has unique chars without an additional data structure."""
sorted_string = sorted(string)
for i in range(len(sorted_string), -1):
if sorted_string[i] == sorted_string[i+1]:
return False
return True
def reverse_c_string(string, result_so_far):
"""Reverse a C-style null terminating string."""
if string == '\0':
return result_so_far + '\0'
else:
return reverse_c_string(string[1:], string[0] + result_so_far)
def is_permutation(first, second):
"""Given two strings decide if they are permutations."""
return sorted(first) == sorted(second)
def replace_whitespace(string):
"""Replace whitespace with %20."""
return string.replace(' ', "%20")
def basic_string_compression_recur(string):
"""Given string do basic compression."""
def impl(current, count, remaining):
if not remaining:
return "%s%s" % (current, count)
elif current == remaining[0]:
return impl(current, count + 1, remaining[1:])
else:
return "%s%s" % (current, count) + impl(remaining[0], 1, remaining[1:])
return impl(string[0], 1, string[1:])
def basic_string_compression_for(string):
"""Given a string do basic compression using a for loop."""
current = string[0]
counter = 1
so_far = []
for i in string[1:]:
if i == current:
counter += 1
else:
so_far.append("%s%s" % (current, counter))
current = i
counter = 1
so_far.append("%s%s" % (current, counter))
return ''.join(so_far)