Skip to content

Commit 3d161ad

Browse files
authored
python compress and decompress string solution (bregman-arie#309)
* compress string solution * decompress string solution * style fix
1 parent 066a273 commit 3d161ad

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

scripts/random_question.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import optparse
33
import os
44

5+
56
def main():
67
"""Reads through README.md for question/answer pairs and adds them to a
78
list to randomly select from and quiz yourself.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
## Compress String Solution
2+
3+
1. Write a function that gets a string and compresses it
4+
- 'aaaabbccc' -> 'a4b2c3'
5+
- 'abbbc' -> 'a1b3c1'
6+
7+
```
8+
def compress_str(mystr: str) -> str:
9+
10+
result = ''
11+
12+
if mystr:
13+
prevchar = mystr[0]
14+
else:
15+
return result
16+
17+
count = 1
18+
for nextchar in mystr[1:]:
19+
if nextchar == prevchar:
20+
count += 1
21+
else:
22+
result += prevchar + str(count)
23+
count = 1
24+
prevchar = nextchar
25+
26+
result += prevchar + str(count)
27+
return result
28+
```
29+
30+
31+
2. Write a function that decompresses a given string
32+
- 'a4b2c3' -> 'aaaabbccc'
33+
- 'a1b3c1' -> 'abbbc'
34+
35+
```
36+
def decompress_str(mystr: str) -> str:
37+
result = ''
38+
for index in range(0, len(mystr), 2):
39+
result += mystr[index] * int(mystr[index + 1])
40+
return result
41+
```

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy