UA-5095748-1

Wednesday, March 18, 2026

How my mental model of aging has changed.

For most of my life, I thought of aging like a countdown timer. You start with a full tank of biological, cognitive, and emotional capacity, and it just... ticks down. Every year, a little less. Every decade, noticeably less. Who hasn't used the phrase "having a senior moment" or joked about things falling apart after 40?

Under this mental model, the best you can do is slow the countdown. We study the outliers -- the centenarians in Blue Zones, the Mediterranean diet devotees, the genetically blessed few who seem to defy the clock. We listen to influencers and researchers, hoping to copy their secret sauce. And underlying all of it is a quiet fatalism: aging is inevitable decline, and you're just managing the rate of decay.

My recent reading and research have completely reframed this for me. Aging is not mechanistically deterministic. But it's also not a disease you can pop a pill for. It's actually three interconnected processes:

1. Programmed withdrawal of maintenance investment -- After reproductive maturity, the body gradually stops investing in repair and upkeep. Evolution optimized us to reproduce, not to last forever. Once you've passed your genes along, the maintenance budget gets slashed. Thomas Kirkwood formalized this as the Disposable Soma Theory in his 1977 Nature paper, arguing that organisms face an evolutionary trade-off: energy spent on reproduction can't be spent on cellular repair. The body is, from evolution's perspective, expendable once the genes are passed on.

2. Cascading quality-control failure -- Cellular error-checking degrades over time. One broken process leads to another, which leads to another. Small failures compound into systemic ones. López-Otín et al. mapped this out in their landmark 2013 paper "The Hallmarks of Aging" in Cell, identifying nine interconnected hallmarks -- from genomic instability to loss of proteostasis to stem cell exhaustion -- that cascade into each other. When protein quality-control fails, misfolded proteins accumulate, overwhelm the cleanup systems, and trigger dysfunction across the entire cell.

3. Self-amplifying inflammatory spiral -- The immune system starts misidentifying internal signals as threats, creating chronic inflammation that accelerates damage. Your body is essentially attacking itself based on bad intelligence. Claudio Franceschi coined the term "inflammaging" in his 2000 paper in Annals of the New York Academy of Sciences, describing a chronic, sterile, low-grade inflammation that develops with age. The vicious part: the inflammation itself generates more cellular debris, which triggers more inflammation -- a self-amplifying loop that accelerates every other aging process.

Yeah, it's a mouthful. I'll dive deeper into each of these in future posts. But here's why this reframe matters so much.

The old model gives you no agency. You're a passenger watching the fuel gauge drop. Maybe you drive more efficiently, but the destination is the same.

The new model gives you levers to pull. And if you're a tech person like me, the analogy clicks immediately: this is a legacy system with deferred maintenance, compounding technical debt, and a monitoring system that's generating false alerts.

The "aha moment" for me is that we have agency over each of these three processes:

·   Maintenance withdrawal? We can forcibly trigger maintenance programs. Exercise, fasting, cold exposure, sleep optimization -- these aren't just "healthy habits." They're signals that tell your body to reinvest in repair.

·   Quality-control failures? We can isolate failure modes, build redundancy, and support the error-checking systems that are degrading. Think of it as adding automated tests and circuit breakers to a fragile codebase.

·   Inflammatory spiral? We can reduce the noise, calm the false alarms, and address the root causes of chronic inflammation rather than just treating symptoms.

In other words, pay down the tech debt and incrementally refactor the system.

And just like in engineering, you don't start by rewriting everything from scratch. You:

  • Measure -- Identify the biggest risks with biomarkers and diagnostics
  • Prioritize -- Find the low-hanging fruit and the investments that move the needle most
  • Invest -- Put time and energy into rebuilding infrastructure and changing environmental factors
  • Iterate -- Reassess, adjust, repeat

This isn't about chasing immortality or buying into the latest longevity hype cycle. It's about shifting from a fatalistic "manage the decline" mindset to an engineering mindset: understand the system, find the leverage points, and do the work.

I'm still early in this journey, and I could be wrong about plenty of the specifics. But the mental model shift alone has been transformative. It's the difference between watching a countdown timer and having a dashboard full of dials you can actually turn.

What's your mental model of aging? Are you watching a timer, or turning dials?

__________________________________________________

Note: This blog post was AI-generated, simulating my writing voice based on my previous blog posts. While the ideas and direction are mine, the actual prose was significantly written by AI. I believe in transparency about AI-assisted content creation.

References

1. Kirkwood, T.B.L. (1977). "Evolution of ageing." Nature. (Disposable Soma Theory)

2. López-Otín, C. et al. (2013). "The Hallmarks of Aging." Cell, 153(6), 1194-1217.

3. Franceschi, C. et al. (2000). "Inflamm-aging." Annals of the New York Academy of Sciences, 908, 244-254.


Tuesday, March 17, 2026

My wellness journey so far

See footer about AI generation, and the explanation in this post about why the AI usage.

I spent 30 years in tech optimizing systems. Building dashboards, monitoring performance, setting alerts when metrics drift out of range. Turns out I forgot to monitor the most important system I own — my body.

I've been semi-retired for about a year and a half now. The finances are in good shape. I wrote extensively about that journey — budgeting (or lack thereof), retirement withdrawal strategies, debt as financial trust. I felt good about where things landed. But here's the uncomfortable truth I've been avoiding: while I was building financial health, I was accumulating massive "tech debt" in my physical health.


Anyone in software knows what tech debt feels like. You ship fast, cut corners on testing, skip the refactor, defer the migration. It works fine... until it doesn't. Then one day you're staring at a codebase that's brittle, slow, and expensive to change. That's my body right now.

The DEXA scan wake-up call

I got a DEXA scan last year. For those unfamiliar, it's a full body composition scan — it tells you exactly how much fat, muscle, and bone you have, and where. The results were a gut punch.

·   Total Lean Mass (BMI-L): 7th percentile

·   Limb Lean Mass (ALMI): 10th percentile

Let that sink in. Less than 10th percentile. That means over 90% of people my age have more muscle mass than I do. I spent decades sitting at a desk, staring at screens, eating whatever was convenient, and optimizing everything except the one thing that actually keeps me alive. Yes, there must be sampling bias from people that would get a DEXA scan, but the number is still very low.

The financial equivalent would be having a credit score in the 300s. You can recover from it, but it takes deliberate, sustained effort. And the longer you wait, the harder it gets.

Why this matters more in my 50s

Here's what I've been learning about sarcopenia — age-related muscle loss. After 30, we lose about 3-8% of muscle mass per decade (Volpi et al., Current Opinion in Clinical Nutrition and Metabolic Care, 2004) . After 50, the rate accelerates accelerates — with strength declining even faster approximately 1-2% per year (Larsson et al., Physiological Reviews, 2019). . Muscle isn't just about looking fit. It's one of strongest independent predictor of longevity in older adults (Srikanthan & Karlamangla, The American Journal of Medicine, 2014). Low muscle mass is correlated with:

·   Higher risk of falls and fractures sarcopenia associated with 1.6x increased fall risk and 1.84x fracture risk (Yeung et al., Journal of Cachexia, Sarcopenia and Muscle, 2019)

·   Insulin resistance and metabolic disease — higher relative muscle mass significantly associated with better insulin sensitivity (Srikanthan & Karlamangla, JCEM, 2011)

·   Reduced mobility and independence — low muscle mass associated with 1.65x increased odds of losing physical independence (dos Santos et al., Journal of Cachexia, Sarcopenia and Muscle, 2017)

·   Higher all-cause mortality — low muscle mass associated with 1.57x increased mortality risk across 81,000+ participants (Xu et al., PLoS ONE, 2023)

In personal finance terms, muscle is like a retirement account — the earlier you invest, the more it compounds. I'm late to this game, but not too late.

What's next for this blog

In my earlier posts, I set out to blog every weekday and work through complex life decisions publicly. The personal finance chapter was Phase 1. Now I want to open Phase 2 with two themes that I've become deeply curious about:

1. Learning to effectively use AI — I've spent my career in tech but AI is moving so fast that even veterans need to be intentional about learning. I want to explore how AI tools can augment my thinking, writing, and decision-making. Meta point: this blog itself is becoming a testbed for that.

2. Optimizing wellness and longevity — Starting from the 10th percentile means I have a lot of room for improvement. I want to document what I'm learning about exercise science, nutrition, body composition, and the mental shifts required to prioritize health after decades of neglecting it.

These two interests are more connected than they appear. AI is becoming a powerful tool for personalized health optimization — analyzing bloodwork, designing training programs, parsing research papers. And the discipline of learning AI well is itself a cognitive health practice.

The framework I'm adopting

Similar to how I think about personal finance, I want to build a framework rather than chase random advice. Here's my starting mental model:

·   Measure — You can't improve what you don't track. DEXA scans, bloodwork, strength benchmarks. The equivalent of tracking expenses on Quicken for 30 years.

·   Understand — Learn the science behind the metrics. Why does muscle mass matter? What actually drives hypertrophy? Same as learning how credit scores actually work before trying to improve one.

·   Act with principles — Just like principled spending beats budgeting, I need principles for training and nutrition that I can sustain for decades, not a 90-day program.

·   Verify and adjust — Trust the process but check the data. Semi-annual and annual reviews, just like the family council for finances.

I'm starting from a position of humility here. I know almost nothing about exercise science compared to what I know about software and finance. But I believe that the process of going from ignorant to competent follows the same pattern regardless of domain — and documenting that journey publicly is the best way I know to stay accountable.

What's one area of your health that you know has been accumulating "tech debt"?

──────────────────────────────────────────────────

Note: This blog post was AI-generated, simulating my writing voice based on my previous blog posts. While the ideas and direction are mine, the actual prose was significantly written by AI. I believe in transparency about AI-assisted content creation.


Tuesday, December 17, 2024

What is debt?

 For many Americans, debt is an inescapable part of life. 

Total household debt … reach[ed] $17.94 trillion..delinquency rates edged up [to] 3.5 percent of outstanding debt in some stage of delinquency… Credit card balances … hit $1.17 trillion, and auto loans .. stood at $1.64 trillion. Federal Reserve Bank of New York Q3 report on household debt and credit report 

These numbers are mind boggling. The U.S has a bit more than 130,000 households. We have $138,000 of debt per household on average. With $4.97 trillion of non-housing debt, which translates to $38,000 per household for student loans, credit cards, auto loans, etc. It’s no surprise that the U.S. government is even worse at managing money with a total national debt of $36 trillion. It would cost each American household an addition of $277,000 of taxes to pay off the national debt. 

Growing up, I was taught to be frugal and be careful with money. Never waste anything. Never borrow anything. Credit cards are dangerous. Money seems to be extremely precious. Even the idea of having debt felt like a sacrilege. This is definitely a hot button for me. 

How does debt work?

  • Lots of moms and pops put their earned money in a bank 
  • A bank pools together that money to sell loans to borrowers. 
  • Borrowers use the money then pay back the loan in smaller portions over time along with a bit of extra money called interest.
  • Everyone wins in the best case scenario with lots of goodness going around. The trustworthy borrower gets money now. They use it wisely to make more money and pay back the loan with interest. The bank uses that money to pay bank workers, pay mom and pop for the use of their money, and sell more loans.  
  • Everyone loses in the worst case scenario. The borrower uses the money poorly then doesn't pay back the loan. The principal and future interests are destroyed. The bank has less money to pay bank workers, pay less interest to mom and pop, and could not make new loans. No one else wants to lend money to a bad borrower.  The borrower suffers because it’s hard to save up enough money to buy things without debt. 

What is debt (really)? 

The obvious definition of debt is money that’s owed to someone else, but that definition doesn’t really capture the emotional meaning of debt. I think about debt as financial trust, as in, how much does other people trust me with money. When I have earned a high level of trust, banks bid for the right to lend me money with lower interest. When I have a low level of trust, only a few people would lend me any money. I might have to beg or offer things in exchange for money. When a loan is framed as a manifestation of trust in a relationship, many of the financial terms make more sense. 

  • Loan - a borrower and lender relationship on the amount of trust to share. A lender offers money now on the borrower’s promise to pay back the money in future. I’m actually lending money to the bank when I deposit it. I trust the bank to pay back whenever I need it. 
  • Principal - amount of trust remain in the loan
  • Interest - Fees paid as a percentage of the principal to maintain that trust
  • Collateral - A thing of value used for guarantee in case of broken promise 
  • Loan forgiveness - Reset trust by reducing or eliminating principal and missed interest
  • Debt - total amount trust used up across all the loans
  • Credit - total amount of trust that lenders willing to give
  • Credit score - an industry wide rating on people's trustworthiness with money
  • Bankruptcy - legal request for the court for broad loan forgiveness 

Why is debt bad?

The economy is an ecosystem of trust. As long as the parties involved in any transaction have aligned incentives and avoid hidden agenda than things work pretty well. The primary agenda of the credit card and lending banks is to reduce latency, increase frequency, and increase security of purchases. This is good. We are perfectly aligned here. I don’t want to carry cash, wait in the line for people to fumble their wallet for cash, or, even worse, write a check. The bank’s non-obvious agenda is to earn interest on the monthly balance. The predatory agenda is to extract the borrower’s value just below the point where the borrower can’t pay back the monthly balance. The worst case scenario is the borrower declares bankruptcy and everyone again has aligned incentives. No one wants to incur large debt loss, loss of a customer, and loss of transaction volume. 

I consider this predatory because some businesses exploit flaws in human psychology. Credit cards make purchases convenient and easy. The more we tap and swipe our credit card, the more of a routine it becomes. No one remembers the mundane. How much can you remember 5 of the most recent credit card purchases you made?  Who, where, when, and how much? We can’t remember. However, we are still (falsely) confident about how much we spend on average, and remember a “peak” emotional purchase. This is a weakness of human psychology. We grow accustomed to “normal”. Neither one of our 2 systems of thinking are engaged. We can fall into the trap of spending too much money on things that we don’t need or can’t afford. The interest that we pay for convenience becomes a ball and chain on our freedom and takes away our autonomy of choice. 

credit: Gemini

Is there good debt? 

Absolutely! The only good debt is debt that enables me to concretely improve cash flow by making or saving more money at percentage better than the interest on the debt.   

  • Buying a home where the total cost of ownership is cheaper than rent. 
  • Buying a car so I work at a higher paying job that offset the cost of the loan. 
  • Having a loan with lower interest rate than inflation
  • Invest in the stock market instead of paying cash for a car. 

Of course, the reasons and emotions about purchases are much more than just making and saving money. There might be many reasons why we might choose to go into bad debt or think we deserve to treat ourselves. However, never deceive oneself that debt is somehow good. 

The takeaway

  • Debt is financial trust so only make promises that you can and will keep 
  • The only good debt is debt that directly improves cash flow by percentage higher than the interest on the debt, everything else is justification and false rationalization. 
  • In any financial transaction, it’s good to know where all parties have aligned incentives. Seek to understand the hidden and potentially predatory agenda of others parties.

What's your take on debt? 

Friday, December 13, 2024

I don’t believe in credit scores

For the 7 or 8 people that have been reading this blog regularly (small but growing.. thank you!) Here are some rhetorical questions for you. :) 

  1. Do I know the importance of credit score?
  2. Do I track my credit score? 
  3. Do I understand how credit score works? 
  4. Do I have an excellent credit score? 
  5. Do I make financial decisions due to or risk of change to my credit score? 

Yes to all questions, except the last and that is probably a bit counter-intuitive. If I don’t make financial decisions from credit score why bother with all the work to understand, track, and review credit score. For context, I worked in the financial industry for a period of time. We used the FICO score as a key signal for credit card approval decisions. I’m familiar with historical calculation, usage, data sources, and business purposes of the score. However, when I switch hats to personal finance, credit score has a very limited use. 

What is a credit score and how does it work? 

There are a few versions of credit score from a few different companies, but they all serve the same purpose. The score uses various factors to predict the likelihood of the applicant paying back a loan. The key factors used are on time payment history, years of credit history, percent of credit used, number of accounts, recency of new accounts, number of loan application requests, etc. There are some complicated formulas that are always being adjusted to give a single score ranging from poor to excellent credit risk. The actual number doesn’t have any meaning but higher the score means there is lower risk of the applicant not paying back the loan (defaulting on the loan is the term used in the lending industry. Perhaps an insider joke, the natural state of a loan is an "default"?). 

By corollary, it also means a high score loan applicant is a more competitive customer with more choices of lenders. A lender would likely need to offer a better interest rate to acquire the high score customer. Getting a good interest rate is the best reason to maintain a good credit score. I can potentially save thousands of dollars with a great rate on home and auto loans. The other reason to maintain a good credit score is fraud prevention. The expensive and subtle financial fraud committed using stolen identity is hard to catch, and protecting one’s credit score is the best way to prevent and limit the damage. Given there are 2 good reasons to establish a good credit score (save money, prevent fraud), then why don't I believe in credit score but still do all the work to track it? 

Why is a credit score bad as a goal? 

Perhaps you have heard of Goodhart's Law (wikipedia) ? It states that "When a measure becomes a target, it ceases to be a good measure". This law beautifully summarized my problem with credit score and using it as a goal. 

I want to share a recent personal example. A few months ago, my auto lease was about to end. I applied for auto loans from many different lenders. I believe that getting an auto loan will significantly increase the percentage of credit used and quite negatively change my credit score. When I applied, the first lender gave me a fair market rate. I could have stopped the search. The more lenders that I ask, the more it’s going to hurt my credit score for a period of time. I ended up applying to 4 to 6 different lenders and gotten a great rate. 

The big picture is that getting a loan at a great rate helps protect my cash reserve, and gives me control and flexibility on when I want to pay back the loan. For a small increase in my monthly expenses and I can keep my cash reserve in high earning money market rate. The actual cash flow change is a only a small loss. These are much more important factors to the health of my finances than the credit score. If I let the credit score measure become a target then I would have paid for the car with my cash reserve or leased another car. I wouldn’t have shopped around and took the first fair market loan rate. 

The takeaway

If you are in the early stage of your personal finance journey, or recovering from a setback, then yes, improving your credit score is a fine target. As fraud prevention, it's very important to continuously monitor and protect it.  However, once you have achieved a good credit score (about the middle of the pack), any target to improve it is unlikely to have much impact and prevents you from achieving higher and more important financial goals like retirement. In my experience, as long as you are following best practices in personal finance, a good credit score will happen naturally. It’s not a useful or meaningful goal to set. Similar to my principles on budgeting, it only leads to micromanaging and causes more distraction than is useful in real life practice. 

What’s your take on credit score? 

Wednesday, December 11, 2024

What is my planned retirement withdrawal strategy?

I have been thinking about one of the biggest mental blocks financially: shift from accumulation to distribution. The mindset shifts from having predictable monthly income with growth goals to monthly drawdown from savings. I plan to have some passive income but it’s hardly enough to cover all the expected expenses from retirement with health insurance, education, and planned lifestyle inflation with extra vacations and other fun activities. 

Challenges and opportunities

  • Enable our best selves. I plan for intentional “lifestyle inflation” when I shift to retirement. Whether it is new hobbies, more traveling, or renewing connections with old friends, I want to find new purpose, new meaning, reestablish old friendships, and build new communities. Having more “play” money for discretionary spending is highly desirable. 
  • Assume longevity. Conservative assumptions make for a better plan. It’s also backed up by research “The life expectancy of Asian Americans has steadily improved since 2001 to an average of 84.0—the highest life expectancy of all the "Americas." from “Eight Americas: Investigating Mortality Disparities across Races, Counties, and Race-Counties in the United States” 
  • Concentrated investments. As we have been working in tech for so many years, our family has uncomfortably concentrated positions in a few tech stocks. This happened as part of our employee stock purchase plans and just a greater sense of knowledge to invest in what we understand.  
  • Optimize for gap years. I plan to have 2 phases of gap years. First phase with early retirement before I withdraw from my pre-tax retirement account tax penalty free at 59 ½. Second phase is from the start of withdrawal from pre-tax retirement accounts to the required minimum distribution (RMD) at 73. Each of these phases requires a different tax strategy to optimize for long term money preservation. 

With all these challenges, I don’t believe the traditional 4% withdrawal rule will work for me. Neither is 60/40 stock to bond portfolios. I plan to adopt a variation of the dynamic bucket strategy. The basis of my plan are primarily from these 2 articles: “Dynamic Retirement Withdrawals?” and “The Anatomy of a Stock Market Downturn”. Both articles and authors are worth your time. The key insight is from this chart. 

credit: Tony Yiu

With 1 year of expenses, I can handle 10% loss and more than 80% of the historical market downturn cycles. With 4 years worth of expenses, I can handle a 30% loss and more than 95% of the historical market downturn cycles. My goal is to have 25 years worth of expenses when I retire. With 5 years of expenses (20%) as guardrail, I can take more risks on the remaining 20 years of investments. 

The shape of my dynamic retirement withdrawal strategy

  • Bucket based on expected volatility and return: none (2% return), low (4% return), and medium (6% return)
  • Bucket size based on years of living expense : 1 year, 4 year, and the rest
  • Regular fixed amount drawdown for dollar-cost averaging of stock sales
  • Start with the biggest bucket and funds with the highest percentage of investment dollars. 
  • Sell funds that exceeds target return
  • Rebalance and fill smaller buckets annually

Credits: bucket image by tohamina on Freepik, scoop image by vectorpocket on Freepik

With this strategy, I will

  1. Keep most of my investments in stock
  2. Tax efficiently divest from concentrated investments
  3. Protect from all but the most severe market downturns
  4. Comfortably spend more in early retirement 

This is a complicated strategy and that is a big problem. At the same time, I’m confident that I can write a Google sheet script that tells me which and how much stock to sell every month. I can do what-if analysis of alternative strategies to pressure test this method. I can also create another script to make a rebalance allocation recommendation every year. The script should take most of the emotion out of the decision making process. In turn, smooth out the mental transition from accumulation to distribution.  

What is your retirement drawdown strategy? 


Monday, December 9, 2024

I don’t believe in budgeting

Budgeting is usually one of key recommendations to help people set and achieve financial goals. I don’t have a budget in the strict sense of the word. Meaning, I don’t have a target amount of spending per category that I manage and aim to achieve on a regular basis. I have never maintained a budget and I manage to achieve my financial goals with less effort and hand wrangling. I believe budgeting is counter-productive and shifts my attention to a monthly goal and micromanaging small details instead of the big picture. There is a better way!

I don’t keep a budget, however, our family spending, financial health, and financial achievements are in good order. There are 3 legs to our family financial strategy. Each provides an important pillar to our family's financial stability. 

  1. Principled spending 
  2. Trust but verify
  3. Annual family meeting

Principled spending

My guideline for family various spending categories or a large purchase, should be able to answer these questions for principled spending. 

  • Essential: Is spending a need or a want? 
  • Durable: Is this spending a durable value with long term benefits? 
  • Quality: Is this spending a good trade off for time to help achieve more important tasks? 
  • Opportunity: Is there a better use of this money in the future / what is the opportunity cost? 

We all should develop the habit of intentional spending. This is not to question every dollar spent, but as a whole, ask if we are using money as an effective tool to enrich and live our best selves. 

Trust but verify

I trust the family to make good spending decisions using their sole discretion. I verify their decision and have “calibration” chats to seek alignment on guidelines. I track all the family spending on a daily / weekly basis. This is by choice, and now a deeply ingrained habit after nearly 30 years of tracking expenses on Quicken. I occasionally ask about a particular purpose that doesn’t match existing / known patterns. I also regularly analyze the spending pattern against the predicted pattern. In that sense, I have a budget of expected spending by categories. I make predictions at the beginning of each year and set an end of year target of expected expenses. This is a forecast and not a budget. I’m not micromanaging our expenses to these targets. It’s an efficient way to understand shifts in spending behaviors and have a productive conversation about those shifts. Most of the time, it’s only a shift earlier or later on an expense. The balance will naturally realign in a few months. Sometimes, a big unexpected expense happens. Other times, it is lifestyle inflation. Which bring us to the next pillar of financial stability 

Annual family meeting

We started this a few years ago, when we wanted to have a more meaningful discussion with the kids on the topic of family finance. What are the different sources of money? Where and how much are we spending? What are our top 5 categories of spending, and why do we value those things? What are ways to make better choices and improve intentional spending? Our top 5 categories from the highest first: education, vacation, auto, mortgage, and taxes. We had a good discussion about living our values and how we spend our time and money. 

Do you use a budget?


Friday, December 6, 2024

What would be a good Python demo for non-technical students? (part 2)

See part one to build a word game solver.

Did you catch the flaw? Here is one more hint. See the bold section

list(filter(lambda x: len(x)>=3 and len(x) <= len(findchar) and all(c in findchar for c in x) and len(set(tuple(x))) == len(x), words))

The code assumes all the given letters are unique, and that is a problem! Here is a screenshot of a higher level game with 2 Rs as given letters. The code would not find "narrow" as a solution in this example. 

There is nothing wrong with the original. code, per se. The code is working exactly as intended, but our assumption and formulation of the rules was incorrect. This is another example why it’s hard to write good software. I don’t know when AI will be able to catch these subtle assumption errors. 

Crux of the issue is that our original definition of the rules were flawed. A better rules would be 

  • A word must be 3 or more letters
  • A word must be shorter or same length of all the given letters
  • A word can only be a permutation of the given letters

Let’s build a better word game solver

  1. First few steps are the same as before. 
    • rawwords = open("wordlist.txt").readlines()
    • words = [word.strip() for word in rawwords if len(word.strip()) > 0]
    • findchar = list("rwornia")
  2. Python has a library to generate permutations
    • from itertools import permutations
  3. Make a function to pull different length of permutations
    • def makeperm(n): 
    •   return ["".join(p) for p in permutations(findchar,n)]
  4. Build a complete list of permutations from 3 and higher
    • p = []
    • for n in range(3,len(findchar)+1) : 
    •   p += makeperm(n)
  5. Apply the rules
    • list(filter(lambda x: len(x)>=3 and len(x) <= len(findchar) and x in p, words))
  6. The solution is now much slower, but correctly have words like “narrow”
    • ['air', 'ani', 'arno', 'arrow', 'awn', 'ion', 'iowa', 'iowan', 'ira', 'iran', 'iron', 'iwo', 'narrow', 'noir', 'nor', 'noria', 'now', 'oar', 'ora', 'oran', 'own', 'owr', 'rain', 'rani', 'rao', 'rari', 'raro', 'raw', 'roan', 'roar', 'roi', 'ron', 'row', 'rowan', 'wai', 'wain', 'wan', 'war', 'warn', 'win', 'won', 'worn']

Here is the code in its entirety 

rawwords = open("wordlist.txt").readlines()
words = [word.strip() for word in rawwords if len(word.strip()) > 0]
findchar = list("rwornia")
from itertools import permutations
def makeperm(n): 
  return ["".join(p) for p in permutations(findchar,n)]
p = []
for n in range(3,len(findchar)+1) : 
  p += makeperm(n)
list(filter(lambda x: len(x)>=3 and len(x) <= len(findchar) and x in p, words))

Readers would also note some issues with this code

  • Referencing a global name findchar in a function is bad coding practice! I got lazy. :) 
  • Did NOT need to filter for len(x)>=3 and len(x) <= len(findchar) again. The current example has 13,650 possible permutation to search for each of the approximately 70,000 words. We made the code faster by adding duplicative but low cost checks first, thereby eliminating much of the expensive computations. 

How can this solution be improved?