I set out to write a small Python script to tell me cheapest domains. I manually scraped for data from iwantmyname.com into a plain text file as follows:
.COM
Commercial
$14.90
The most registered domain extension on the planet.
.CO 48% off!
Colombia
$19.90
then $39.00/year
It's .com without the m.
.APP
Generic
$29.00
Your app needs a new home
.NET
Network
$17.10
Think garage startups, beards before they were cool, and hobbyist tinkering.
This file has about 2050 lines.
First I wrote a script to get the domains and prices by reading lines that start with a .
for domain and a $
for the associated price.
from operator import itemgetter
domain_prices_raw = []
with open(r'domain_prices.txt') as f:
domain_prices_raw = f.readlines()
domain_prices_raw = [x.strip() for x in domain_prices_raw]
domains = []
prices = []
for line in domain_prices_raw:
if line.startswith('.'):
domains.append(line.split(' ')[0])
if line.startswith('$'):
prices.append(float(line.replace('$', '')))
sorted_domain_prices = sorted(
list(zip(domains, prices)), key=itemgetter(1))
with open('sorted_domain_prices.txt', 'w') as f:
for domain, price in sorted_domain_prices:
f.write("{0}\t{1}\n".format(domain, price))
A bit later I realized that some domains have a low price only for the first year and subsequently have higher price per year. So I updated the script to read the lines that start with then
.
Example from the file:
.CO 48% off!
Colombia
$19.90
then $39.00/year
Updated script is as follows:
from operator import itemgetter
domain_prices_raw = []
with open(r'domain_prices.txt') as f:
domain_prices_raw = f.readlines()
domain_prices_raw = [x.strip() for x in domain_prices_raw]
domains = []
prices = []
prices_after_first_year = []
for line in domain_prices_raw:
if line.startswith('.'):
domains.append(line.split(' ')[0])
if line.startswith('$'):
prices.append(float(line.replace('$', '')))
prices_after_first_year.append(float(line.split(' ')[1].split(
'/')[0].replace('$', '')) if line.startswith('then') else 0)
sorted_domain_prices = sorted(
list(zip(domains, prices, prices_after_first_year)), key=itemgetter(1))
with open('sorted_domain_prices.txt', 'w') as f:
for domain, price, after in sorted_domain_prices:
f.write("{0}\t{1}\t{2}\n".format(domain, price, after))
The script ran quickly enough and I was happy that I could get a working solution, if only for a few minutes.
I know I used zip
to associate adjacent items and that took care of most of the logic that I would have had to write if I weren't aware the existence of something like zip from the knowledge of other programming languages.
Could the script be improved other ways to be more pythonic, more performance oriented and if nothing else, just a more expressive and or OO way to solve the problem?
Bonus question: Could a CS degree have guided me to arrive at a proper solution?