create account

Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions by steempytutorials

View this thread on: hive.blogpeakd.comecency.com
· @steempytutorials · (edited)
$23.19
Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions
![banner.png](https://www.digifloor.com/wp-content/uploads/2016/07/python-banner.jpg)

---

#### Repository
https://github.com/python

#### What will I learn

- ASCII values of characters
- Converting a string into a unique set of lowercase characters
- Remove characters from a string

#### Requirements

- Python 3.7.2
- [Pipenv](https://pypi.org/project/pipenv/)
- git

#### Difficulty

- basic

---

### Tutorial

#### Preface

This tutorial is part of a course where solutions to puzzles from [Advent of Code 2018](https://adventofcode.com/2018/) are discussed to explain programming techniques using Python. Each puzzle contains two parts and comes with user specific inputs. It is recommended to try out the puzzle first before going over the tutorial. Puzzles are a great and fun way to learn about programming.

While the puzzles start of relatively easy and get more difficult over time. Basic programming understanding is required. Such as the different type of variables, lists, dicts, functions and loops etc. A course like [Learn Python2 from Codeacademy](https://www.codecademy.com/learn/learn-python) should be sufficient. Even though the course is for Python two, while Python 3 is used.

This tutorial will look at [puzzle 4](https://adventofcode.com/2018/day/4)

The code for this tutorial can be found on [Github](https://github.com/Juless89/tutorials-aoc)!

#### Puzzle 4

This puzzle is about chemical reactions that are mapped inside a string. Characters react with each other and disappear when they are the same pair, but opposite polarity. Polarity is distinguished by capital and non capital characters. For example aA, bB and cC are pairs with opposite polarity.  

#### Part one

> How many units remain after fully reacting the polymer you scanned? 

A long strong is given, calculating the final length of the string after all pairs have reacted can be done by going over each character and comparing that to the next one. 

```
# read input file and convert to string
with open('input.txt', 'r') as file:
    string = str([x.strip() for x in file][0])
```

#### ASCII values of characters

Every character has a ASCII values, this is how characters can be recognised across operating systems. Characters can be checked to be equal based on their ASCII value. In addition arithmetic can be performed on the ASCII value to transfers the character. For example from a lowercase to an uppercase.

In python `ord()` is used to convert a character into their ASCII value, while `chr()` is used to convert an ASCII values into a character.

`A` has the value of 65 and `a` has a value of 97. There is a 32 difference. Converting an uppercase to a lowercase is done by adding 32 to ASCII value, while converting to a lowercase is done by subtracting 32. A full list can be found [here](https://www.ascii-code.com/)


<center>![Apr-12-2019 19-18-48.gif](https://cdn.steemitimages.com/DQmU4R5ZtcioieTak6hmU51mU1MHVuLq8bsNU6KW42gHf3E/Apr-12-2019%2019-18-48.gif)</center>

```
def part_1(string):
    # filtered characters
    filtered = ['']

    # loop over each character inside the string
    # if the next character is the opposite case 
    # discard both characters, else append to result
    for c in string:
        c2 = filtered[-1]
        # check by ASCII values
        if c2 != '' and (abs(ord(c) - ord(c2))) == 32:
            filtered.pop()
        else:
            filtered.append(c)

    # return length of string
    return len(filtered)
```
<br>
`filtered` contains all the characters that could not immediately be reacted. For each character `c` in the string, `c2` is the last filtered character `filtered[-1]`. `c2` is checked to not be empty, then the ASCII value is taken from both `c` and `c2` and the difference is checked to be equal to 32. This is done by using `abs()` which return the absolute value.

When the difference is 32, the last filtered character gets removed with `pop()`. If there is no match `c` get added to `filtered`. In the end the string of list is returned, which is the answer to the first part of the puzzle.

Instead of doing the ASCII arithmetic by hand Python has a function `swapcase()` which does the same thing. This leads to the following code:

```
before
if c2 != '' and (abs(ord(c) - ord(c2))) == 32:

after
if c == c2.swapcase():
```

#### Part two

> What is the length of the shortest polymer you can produce by removing all units of exactly one type and fully reacting the result?

Solving this part of the puzzle can be done by reusing the code from the previous part but making one change to the string beforehand. That is, removing all units of exactly one type.

#### Converting a string into a unique set of lowercase characters

Each type consists of a lower and uppercase character. To create a set of all types it is easier to either go for all lowercase or all uppercase. This can be done with `.lower()` or `.upper()`. `Set()` can then be used to take out all the unique characters.

```
def part_2(string):
    # return set off all unique lower case units
    types = set(string.lower())
```

This results in:
```
{'v', 'q', 'z', 'a', 'p', 'k', 'r', 'n', 's', 'j', 'e', 'u', 'h', 'f', 'c', 'm', 'y', 'o', 'g', 'w', 'b', 'x', 'i', 'd', 'l', 't'}
```

This set can now be used to remove all upper and lowercase variants form the input string.

#### Remove characters from a string

Removing characters can be done by using `.replace()` which takes two arguments. The character to be replaced and what to replace the character with. To remove something replacing the character with the empty string `''` does the job.


```
# return min for filtered string where lower and upper case of unit are removed
return (min([part_1(string.replace(t, '').replace(t.upper(), '')) for t in types]))
```

Each character is taken from the set `types` and used to replace that character inside the string for the empty string. To remove the upper case variants `t` is also casted to an uppercase. This is done in a list comprehension that calls the function for `part_1`, which returns the length of the output string. `min()` is taken from this list to return the lowest number.

#### Running the code

Run the code with: `python main.py`. This returns both answers for the first and second part of the puzzle. 

```
if __name__ == "__main__":
    # read input file and convert to string
    with open('input.txt', 'r') as file:
        string = str([x.strip() for x in file][0])

    print(f'Part 1 Answer: {part_1(string)}')
    print(f'Part 2 Answer: {part_2(string)}')
```
<br>
<center>![Screenshot 2019-04-12 at 20.07.42.png](https://cdn.steemitimages.com/DQmUot6Z9JTeFY5D9XRqyijXW7nLnhhyq1Nk4mVjt3xxWXz/Screenshot%202019-04-12%20at%2020.07.42.png)</center>

#### Curriculum
[Part 1](https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-1---solving-puzzles-from-advent-of-code-2018), [Part 2](https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-2---solving-puzzles-from-advent-of-code-2018), [Part 3](https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-3---solving-puzzles-from-advent-of-code-2018), [Part 4](https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018)

---

The code for this tutorial can be found on [Github](https://github.com/Juless89/tutorials-aoc)!

This tutorial was written by @juliank.
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 74 others
properties (23)
authorsteempytutorials
permlink-learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","python","course","programming"],"app":"steemit/0.1","users":["juliank"],"image":["https://www.digifloor.com/wp-content/uploads/2016/07/python-banner.jpg","https://cdn.steemitimages.com/DQmU4R5ZtcioieTak6hmU51mU1MHVuLq8bsNU6KW42gHf3E/Apr-12-2019%2019-18-48.gif","https://cdn.steemitimages.com/DQmUot6Z9JTeFY5D9XRqyijXW7nLnhhyq1Nk4mVjt3xxWXz/Screenshot%202019-04-12%20at%2020.07.42.png"],"links":["https://github.com/python","https://pypi.org/project/pipenv/","https://adventofcode.com/2018/","https://www.codecademy.com/learn/learn-python","https://adventofcode.com/2018/day/4","https://github.com/Juless89/tutorials-aoc","https://www.ascii-code.com/","https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-1---solving-puzzles-from-advent-of-code-2018","https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-2---solving-puzzles-from-advent-of-code-2018","https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-3---solving-puzzles-from-advent-of-code-2018","https://steemit.com/utopian-io/@steempytutorials/learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018"],"format":"markdown"}
created2019-04-12 18:10:54
last_update2019-04-12 18:40:15
depth0
children6
last_payout2019-04-19 18:10:54
cashout_time1969-12-31 23:59:59
total_payout_value17.442 HBD
curator_payout_value5.750 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,454
author_reputation31,094,047,689,691
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries
0.
accountsteemplus-pay
weight100
1.
accountutopian.pay
weight500
max_accepted_payout100,000.000 HBD
percent_hbd10,000
post_id82,973,554
net_rshares40,149,151,323,630
author_curate_reward""
vote details (138)
@portugalcoin ·
$6.61
Thank you for your contribution @steempytutorials.
After reviewing your tutorial we suggest the following points listed below:

- Again a very well structured and explained tutorial, with GIFs demonstrating the results of what you are explaining. Your tutorials are very intuitive and easy to read. Good job!

Your tutorials are excellent, thank you for your good work in developing your contribution. We are waiting for more tutorials.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/3-1-1-1-1-2-1-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorportugalcoin
permlinkre-steempytutorials--learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018-20190413t093937102z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["steempytutorials"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/3-1-1-1-1-2-1-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-04-13 09:39:36
last_update2019-04-13 09:39:36
depth1
children1
last_payout2019-04-20 09:39:36
cashout_time1969-12-31 23:59:59
total_payout_value5.052 HBD
curator_payout_value1.562 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length888
author_reputation598,828,312,571,988
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id83,009,776
net_rshares10,711,072,157,358
author_curate_reward""
vote details (23)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-steempytutorials--learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018-20190413t093937102z-20190415t190135z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-04-15 19:01:36
last_update2019-04-15 19:01:36
depth2
children0
last_payout2019-04-22 19:01:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length64
author_reputation152,955,367,999,756
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id83,155,804
net_rshares0
@steem-plus ·
SteemPlus upvote
Hi, @steempytutorials!

You just got a **0.71%** upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in [here](https://steemit.com/@steem-plus) to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.
properties (22)
authorsteem-plus
permlink-learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018---vote-steemplus
categoryutopian-io
json_metadata{}
created2019-04-12 21:26:48
last_update2019-04-12 21:26:48
depth1
children0
last_payout2019-04-19 21:26:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length443
author_reputation247,952,188,232,400
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id82,983,643
net_rshares0
@steem-ua ·
$0.03
#### Hi @steempytutorials!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
πŸ‘  
properties (23)
authorsteem-ua
permlinkre--learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018-20190413t135048z
categoryutopian-io
json_metadata"{"app": "beem/0.20.19"}"
created2019-04-13 13:50:48
last_update2019-04-13 13:50:48
depth1
children0
last_payout2019-04-20 13:50:48
cashout_time1969-12-31 23:59:59
total_payout_value0.022 HBD
curator_payout_value0.007 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length295
author_reputation23,214,230,978,060
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id83,021,695
net_rshares48,048,322,748
author_curate_reward""
vote details (1)
@steemitboard ·
Congratulations @steempytutorials! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@steempytutorials/voted.png?201904131021</td><td>You received more than 5000 upvotes. Your next target is to reach 6000 upvotes.</td></tr>
</table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@steempytutorials) and compare to others on the [Steem Ranking](http://steemitboard.com/ranking/index.php?name=steempytutorials)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-steempytutorials-20190413t115838000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-04-13 11:58:36
last_update2019-04-13 11:58:36
depth1
children0
last_payout2019-04-20 11:58:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length864
author_reputation38,975,615,169,260
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id83,016,275
net_rshares0
@utopian-io ·
Hey, @steempytutorials!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre--learn-how-to-program-with-python-4---solving-puzzles-from-advent-of-code-2018-20190413t213942z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-04-13 21:39:45
last_update2019-04-13 21:39:45
depth1
children0
last_payout2019-04-20 21:39:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length598
author_reputation152,955,367,999,756
root_title"Python #5 - Solving Puzzles from Advent of Code 2018 - String/character functions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id83,042,149
net_rshares0