Thursday, January 25, 2024

Triangle formation from three sides (A problem on sorting technique)

Triangle

Determine whether a triangle can be built from a given set of edges.

Complexity: Easy

Problem

An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:

A[P] + A[Q] > A[R],

A[Q] + A[R] > A[P],

A[R] + A[P] > A[Q].

Write a function:

def solution(A)

that, given an array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [0..100,000];

each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

Example

For example, consider array A such that:

A[0] = 10 A[1] = 2 A[2] = 5

A[3] = 1 A[4] = 8 A[5] = 20

Triplet (0, 2, 4) is triangular.

For example, given array A such that:

A[0] = 10 A[1] = 2 A[2] = 5

A[3] = 1 A[4] = 8 A[5] = 20

the function should return 1, as explained above.

Given array A such that:

A[0] = 10 A[1] = 50 A[2] = 5, A[3] = 1

the function should return 0.

Code

def solution(A):
    N = len(A)
    # If the array has less than 3 elements, no triangular triplet is possible
    if N < 3:
        return 0
    # Sort the array in ascending order
    A.sort()
    # Iterate through the sorted array
    for i in range(N - 2):
        # Check if the triplet conditions are satisfied
        if A[i] + A[i + 1] > A[i + 2]:
            return 1
    # No triangular triplet found
    return 0

Detected time complexity:

O(N*log(N))

Tests

Performance tests

Large1: chaotic sequence with values from [0..100K], length=10K

Large2: 1 followed by an ascending sequence of ~50K elements from [0..100K], length=~50K

large_random: chaotic sequence of values from [0..1M], length=100K

large_negative: chaotic sequence of negative values from [-1M..-1], length=100K

large_negative2: chaotic sequence of negative values from [-10..-1], length=100K

large_negative3: sequence of -1 value, length=100K

Correctness tests

extreme_empty: empty sequence

extreme_single: 1-element sequence

extreme_two_elems: 2-element sequence

extreme_negative1: three equal negative numbers

extreme_arith_overflow1: overflow test, 3 MAXINTs

extreme_arith_overflow2: overflow test, 10 and 2 MININTs

extreme_arith_overflow3: overflow test, 0 and 2 MAXINTs

Medium1: chaotic sequence of values from [0..100K], length=30

Medium2: chaotic sequence of values from [0..1K], length=50

Medium3: chaotic sequence of values from [0..1K], length=100

Why this solution works?

# Check if the triplet conditions are satisfied. Given that A is sorted.

if A[i] + A[i + 1] > A[i + 2]:
    return 1

If you look at this condition, given that A is sorted:

The other two conditions, viz:

A[i+2] + A[i] > A[i+1]

And A[i+2] + A[i+1] > A[i]

Would be satisfied automatically since A[i+2] > A[i+1] and then for second one: A[i+1] (or A[i+2]) > A[i]

Now, what if A[x] and A[y] are supposed to be far apart. Even then:

If let’s say we have this condition met A[3] + A[10] > A[11], then this condition would be met by all the numbers larger than 3.

Thinking Traps

Read what is being asked in the question: Existence of three numbers that can form sides of a triangle.

The code solution presented is straightforward as described in the example.

But if you just twist your thinking a little bit:

Trap 1:

Instead of looking for three numbers that are close, you start looking at the extremes where numbers are on the extremes, you end up with border cases of the solution.

As in: Two large numbers (roughly equal) and one small : Case of triangle

This number that is small could take values large enough to be just smaller than the other two large numbers.

And two very small numbers and one large number: Not a case of triangle

Trap 2:

Instead of starting with the condition P+Q > R, P+R > Q and R+Q > P, you start looking at modifications of these conditions as in P > abs(Q-R).

What if a triplet exists but numbers are far apart?

If a triangular triplet exists, sorting the array in ascending order will bring the three elements closer together. This is because sorting the array ensures that the values are in non-decreasing order, and if a triplet exists, the smallest and middle values of the triplet will be adjacent after sorting.

Let's consider an example:

Original array: [10, 2, 5, 1, 8, 20]

After sorting: [1, 2, 5, 8, 10, 20]

If there exists a triangular triplet, say (P, Q, R), where P < Q < R, after sorting, the values A[P], A[Q], and A[R] will be adjacent in the sorted array. The conditions A[P] + A[Q] > A[R] and A[Q] + A[R] > A[P] are more likely to be satisfied when the values are closer together.

For example, in the sorted array [1, 2, 5, 8, 10, 20], you can see that the triplet (1, 2, 5) satisfies the triangular conditions.

Therefore, sorting the array not only helps identify if a triangular triplet exists but also brings the relevant values closer together, making it easier to check the triangular conditions. If a triplet exists but the values are far apart in the original array, sorting will still reveal the existence of a triplet.

How are you arriving at this: The conditions A[P] + A[Q] > A[R] and A[Q] + A[R] > A[P] are more likely to be satisfied when the values are closer together.

Let me clarify:

The conditions A[P] + A[Q] > A[R] and A[Q] + A[R] > A[P] are requirements for any valid triangle, and they are not affected by the proximity of values in a sorted array. These conditions are fundamental to the triangle inequality theorem.

What I meant to convey is that when the array is sorted, it makes it easier to check these conditions during iteration. Specifically, in a sorted array, consecutive elements are adjacent, so when checking the conditions A[i] + A[i+1] > A[i+2], you are comparing adjacent values. This simplifies the process of checking the triangular conditions as you move through the sorted array.

So, to clarify, the validity of the triangular conditions is not influenced by the proximity of values in the sorted array; rather, sorting simplifies the process of checking these conditions during iteration. I appreciate your understanding, and I hope this clarifies the point.

Tags: Technology,Algorithms,Python

Max Product of Three (A problem on sorting technique)

MaxProductOfThree

Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).

Complexity: Easy

Problem

A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).

Your goal is to find the maximal product of any triplet.

Write a function:

def solution(A)

that, given a non-empty array A, returns the value of the maximal product of any triplet.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [3..100,000];

each element of array A is an integer within the range [−1,000..1,000].

Example

For example, array A such that:

A[0] = -3

A[1] = 1

A[2] = 2

A[3] = -2

A[4] = 5

A[5] = 6

contains the following example triplets:

(0, 1, 2), product is −3 * 1 * 2 = −6

(1, 2, 4), product is 1 * 2 * 5 = 10

(2, 4, 5), product is 2 * 5 * 6 = 60

The function should return 60, as the product of triplet (2, 4, 5) is maximal.

Code

def solution(A):
    A.sort()
    # multiplication two large negative numbers with a positive number
    p = A[0] * A[1] * A[-1]
    
    # multiplication of three positive numbers 
    q = A[-1] * A[-2] * A[-3]
    return max(p, q)

Detected time complexity:
O(N * log(N))

Tests

Correctness tests

one_triple

three elements

simple1

simple tests

simple2

simple tests

small_random

random small, length = 100

Performance tests

medium_range

-1000, -999, ... 1000, length = ~1,000

medium_random

random medium, length = ~10,000

large_random

random large, length = ~100,000

large_range

2000 * (-10..10) + [-1000, 500, -1]

extreme_large

(-2, .., -2, 1, .., 1) and (MAX_INT)..(MAX_INT), length = ~100,000

Tags: Technology,Algorithms,Python

Count distinct elements in an array (A problem on sorting technique)

Problem

Write a function

def solution(A)

that, given an array A consisting of N integers, returns the number of distinct values in array A.

For example, given array A consisting of six elements such that:

A[0] = 2 A[1] = 1 A[2] = 1

A[3] = 2 A[4] = 3 A[5] = 1

the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [0..100,000];

each element of array A is an integer within the range [−1,000,000..1,000,000].

Solution (1) using set()

def solution(A):

    s = set(A)
    return len(s)

Detected time complexity:

O(N*log(N)) or O(N)

Test Cases

Correctness tests

extreme_empty: empty sequence

extreme_single: sequence of one element

extreme_two_elems: sequence of three distinct elements

extreme_one_value: sequence of 10 equal elements

extreme_negative: sequence of negative elements, length=5

extreme_big_values: sequence with big values, length=5

Medium1: chaotic sequence of value sfrom [0..1K], length=100

Medium2: chaotic sequence of value sfrom [0..1K], length=200

Medium3: chaotic sequence of values from [0..10], length=200

Performance tests

chaotic sequence of values from [0..100K], length=10K

large_random1

chaotic sequence of values from [-1M..1M], length=100K

large_random2

another chaotic sequence of values from [-1M..1M], length=100K

Sol (2) using dict() and then keys().len(): Straightforward to implement
Sol (3) without using set() or dict()

In this slide we discuss “Sol (3) without using set() or dict()”:

In this solution, we would use the sort() method of the array object.

def solution(A):
    A.sort()

    rtn = 1

    if len(A) == 0:
        return 0
    else:
        for i in range(1, len(A)):
            if A[i] != A[i-1]:
                rtn += 1

        return rtn
Tags: Technology,Algorithms,Python

Wednesday, January 24, 2024

Books on Goal-Setting (Jan 2024)

Download Books
Countless books have been written, but not all are created equal. Some offer inspirational ideas, while others focus more on the psychological aspects of meeting goals. Here is our list of books we believe are the best for goal setting:

1. Atomic Habits by James Clear

One of the bestsellers in the self-help genre, Atomic Habits is a fantastic read for anyone hoping to improve their lives through goal setting. The book offers practical strategies and techniques to form good habits and break bad ones, making it easier to achieve your goals. With real-life examples and actionable advice, Clear helps you understand the science behind habit formation and how small changes can lead to significant results. He discusses the four laws of behavior change essential in creating long-lasting habits—make it obvious, attractive, easy, and satisfying. He also emphasizes the importance of focusing on systems rather than goals, a crucial concept in your success journey. This book will give you the tools to build a better version of yourself.

2. The One Thing by Gary Keller

Based on the premise that focusing on one thing can make all the difference, this book offers valuable insights on prioritizing your goals and eliminating distractions. It highlights the importance of time management and staying focused on your most important tasks. The authors argue that multitasking is a myth and that it's better to focus on one thing at a time, giving it your undivided attention. They also provide practical tools and techniques to help you identify your “one thing” and work towards attaining it. This book is perfect for individuals struggling with juggling multiple goals and feeling overwhelmed. With the guidance provided, you can learn to streamline your efforts and achieve more with less.

3. The 7 Habits of Highly Effective People by Stephen Covey

Considered a classic in the self-help genre, this book has sold over 25 million copies worldwide. It presents a holistic approach to personal and professional effectiveness through developing 7 fundamental habits. Covey emphasizes the importance of being proactive, prioritizing tasks, and seeking win-win solutions in relationships. He also delves into “sharpening the saw,” which is about caring for oneself physically, mentally, emotionally, and spiritually. This book offers valuable insights on how to align your actions with your core values and principles. It will help you understand that true success goes beyond external achievements but also encompasses inner growth.

4. Goals! by Brian Tracy

As the title suggests, Goals! is about setting and achieving goals. Tracy explains how to create a clear vision of what you want and stay motivated throughout the process. He also discusses the power of visualization in manifesting your goals. What makes this book stand out is its practical exercises that help you apply the concepts to your own life. It covers topics like time management, dealing with setbacks, and overcoming procrastination. Tracy's writing style is engaging and easy to follow, making it an excellent read for anyone looking to improve their goal-setting skills. This read will inspire you to dream big and provide the strategies to turn those dreams into reality.

5. Think and Grow Rich by Napoleon Hill

Initially published in 1937, this book has stood the test of time and is still relevant today. It presents a step-by-step guide to reaching financial success through setting clear goals, developing a positive mindset, and taking action. Hill shares insights from over 500 successful millionaires, including Thomas Edison and Henry Ford, making it a fascinating read. Moreover, he highlights the power of persistence, faith, and visualization in achieving your desires. The book is not just about attaining wealth but also teaches valuable lessons on life and success. It could inspire you to believe in yourself and take charge of your destiny.

6. Hard Goals by Mark Murphy

In this book, Mark Murphy challenges the conventional approach to goal setting and introduces the concept of “hard goals.” These are goals that are heartfelt, animated, required, and difficult. Murphy presents this new goal-setting framework, including several drivers of success—personal alignment, focus, effort allocation, visualizing success, and grit. You'll learn to set hard goals that push you out of your comfort zone. The book is based on extensive research and case studies, making it a valuable resource for anyone looking to set and reach challenging goals. It's a refreshing take on traditional goal-setting methods.

7. Mindset by Carol S. Dweck

This book dives into mindset and how it can impact our success. Dweck introduces the idea of a fixed mindset versus a growth mindset and how our beliefs about intelligence and abilities can shape our behaviors. She argues that individuals with a growth mindset, who believe their skills can be developed through hard work, are more likely to meet their goals. Whereas those with a fixed mindset, who believe their talents are innate and unchangeable, often give up when faced with challenges. Dweck gives practical strategies for developing a growth mindset and its benefits in various aspects of our lives, including relationships, education, and careers.

8. Getting Things Done by David Allen

If you struggle with organization and productivity, this book is a must-read. Allen presents a method for managing tasks called “Getting Things Done” (GTD). It involves capturing all your commitments and ideas into an external system, reviewing them regularly, and taking action. The GTD method helps individuals clear their minds of clutter and focus on the most critical tasks. It also emphasizes the importance of breaking down large projects into smaller, manageable steps. This book is a game changer for those looking to increase their productivity and reduce stress by staying organized and on top of their tasks.

9. The Book of Mistakes by Skip Prichard

Ever feel like you're making the same mistakes over and over again? This book provides a unique goal-setting perspective by focusing on what not to do. Prichard shares 9 common mistakes that hold people back from achieving their goals and excellent advice on overcoming them. He also emphasizes the importance of self-awareness and learning from our mistakes. This is a relatively easy read, with relatable anecdotes and actionable steps to help you avoid common mistakes and achieve your ideal results.

10. The Compound Effect by Darren Hardy

How often have you started a goal only to give up after a few weeks? The Compound Effort explores the power of small, consistent actions and how they can lead to significant results over time. Darren Hardy explains that our daily habits and choices compound over time, leading us closer or further away from our objectives. One of the key takeaways is that success is not an overnight phenomenon; it's the result of daily, deliberate actions. Of course, the same applies to failure. Small, negative habits can also compound and keep us from reaching our goals. That's why it's crucial to pay attention to our daily choices and align them with our desired outcomes.

11. "The Power of Habit"
Why We Do What We Do in Life and Business
by Charles Duhigg

The book talks about: The Habit Loop (Cue, Routine, Reward): Duhigg explains that habits operate in a loop. A cue (trigger) initiates a routine (the behavior itself), which leads to a reward (the outcome you crave). Understanding and modifying each element of this loop can help you reshape existing habits or build new, healthier ones. Keystone Habits: Some habits carry extra weight and can trigger positive changes in multiple areas of your life. For example, regular exercise or consistent family dinners can improve not only physical health or relationships but also promote better discipline, stress management, or work performance. Belief Fuels Change: Changing a habit often requires believing that change is possible. This belief can come from social support, a group context, or personal conviction. When individuals (or organizations) share a belief in their ability to transform, they’re far more likely to succeed in replacing bad habits with better ones.

Final Thoughts

Whether you strive to boost productivity, change your mindset, or attain financial success, there's a goal-setting book for you. Each book offers a unique perspective and tips to reach your dreams and nurture a fulfilling life. Recognize that setting goals is just the first step; it takes determination and consistent action to make them a reality. Go ahead and pick up one (or more) of these books, and take the first step towards a better future. The path may be tough, but the rewards are worthwhile. Happy reading!

Tuesday, January 23, 2024

Ex 1.10 - On mean and variance of two variables (Pattern Recognition and ML by Christopher Bishop)

Question:

Answer:

From the solutions to book

Using ChatGPT

If x and y are two independent continuous variables, can you derive the expression for E[x+y]

Certainly! If xx and yy are two independent continuous random variables, you can find the expected value of their sum E[x+y]E[x + y] by using the property that for independent random variables, the expected value of the sum is the sum of the expected values. Mathematically:

E[x+y]=E[x]+E[y]E[x + y] = E[x] + E[y]

So, the expected value of the sum of two independent continuous random variables is simply the sum of their individual expected values.

If you have specific probability density functions (PDFs) for xx and yy, you can also find E[x+y]E[x + y] by integrating over all possible values of xx and yy:

E[x+y]=(x+y)f(x)g(y)dxdyE[x + y] = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} (x + y) \cdot f(x) \cdot g(y) \,dx \,dy

Here, f(x)f(x) and g(y)g(y) are the probability density functions of xx and yy respectively.

If xx and yy have known probability density functions, you can substitute them into the above expressions to find the expected value of their sum.

Please integrate the last expression and show how for i.i.d. x and y, E[x+y] = E[x] + E[y]

Certainly! Let's integrate the last expression and show that for independent and identically distributed (iid) random variables xx and yy, E[x+y]=E[x]+E[y]E[x + y] = E[x] + E[y].

Assuming f(x)f(x) and g(y)g(y) are the probability density functions (PDFs) of xx and yy respectively, and xx and yy are iid, the expression for E[x+y]E[x + y] is:

E[x+y]=(x+y)f(x)g(y)dxdyE[x + y] = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} (x + y) \cdot f(x) \cdot g(y) \,dx \,dy

Now, let's perform the integration:

E[x+y]=(x+y)f(x)g(y)dxdyE[x + y] = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} (x + y) \cdot f(x) \cdot g(y) \,dx \,dy

=xf(x)g(y)dxdy+yf(x)g(y)dxdy= \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} x \cdot f(x) \cdot g(y) \,dx \,dy + \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} y \cdot f(x) \cdot g(y) \,dx \,dy

Now, by the independence of xx and yy, the joint PDF f(x,y)f(x, y) can be expressed as the product of the individual PDFs:

f(x,y)=f(x)g(y)f(x, y) = f(x) \cdot g(y)

So, we can simplify the above expression:

=xf(x)(g(y)dy)dx+y(f(x)dx)g(y)dy= \int_{-\infty}^{\infty} x \cdot f(x) \left(\int_{-\infty}^{\infty} g(y) \,dy\right) \,dx + \int_{-\infty}^{\infty} y \left(\int_{-\infty}^{\infty} f(x) \,dx\right) \cdot g(y) \,dy

The integrals inside the parentheses evaluate to 1 because f(x)f(x) and g(y)g(y) are probability density functions, which integrate to 1 over their respective ranges. Therefore:

=xf(x)dx+yg(y)dy= \int_{-\infty}^{\infty} x \cdot f(x) \,dx + \int_{-\infty}^{\infty} y \cdot g(y) \,dy

This is equivalent to E[x]+E[y]E[x] + E[y], showing that for iid xx and yy, E[x+y]=E[x]+E[y]E[x + y] = E[x] + E[y].

How Can We Get Ready To Write? (Chapter 2)

Translate this page:


What Should You Write?

  • Write about what keeps you awake at night.
  • Write to learn where you need to go.

Trust where your writing takes you. You may start with a trauma / emotional upheaval but soon begin writing about other topics. As long as these other topics are emotionally important, follow them. If, however, you find yourself writing about what you would like for dinner — or some other distracting topic — then force yourself back to the trauma / emotional upheaval.

# Write about issues relevant to the here and now.

# Write only about traumas that are present in your mind.

Write only about traumas that are present in your mind.

A remarkable amount of literature deals with repressed memories. The repressed memory literature explores the idea that people have had horrible childhood experiences that they don’t remember — many of which involved childhood sexual abuse. The writing you are doing here focuses on what you are aware of now. If you have no memory of a given childhood experience, why not go with the working assumption that it never happened? After all, you wouldn’t know the difference anyway. Write only about conscious traumas and upheavals. It will save you thousands of dollars in therapy and legal bills.

How Much Time Should You Write?

How frequently to write.

While there is some debate about whether it is better to write for four consecutive days or to separate your writing days, there is nothing conclusive either way.

How long for each session.

In most large-scale studies, people wrote for around twenty minutes on three to four occasions.

How many days to write.

What if you find that you enjoy writing and want to continue past four days? Do it.

Booster-writing sessions

Think of expressive writing as a tool always be at your disposal, or like having medicine in your medicine cabinet. No need to take the medicine when you are healthy, but when you are under the weather, you can always turn to it. Once you have tried writing as a healing agent, try it again when you need to. Also, you might find that in the future, you won’t need to write for four days, twenty minutes a day. Merely writing occasionally when something bothers you might be sufficient.

Writing prescription: To Journal or Not to Journal?

Sometimes a healthcare provider may tell a patient, “You should write about that in a journal,” but that’s as far as the prescription goes. You may wonder, is keeping a daily journal a good idea? Ironically, there is no clear evidence that keeping a daily journal or diary is good for your health, perhaps in part because once people get in the habit of writing every day, they devote less and less time to dealing with important psychological issues. Sometimes a journal can become a worn path with little benefit.

Writing in a journal about the same trauma, using the same words, expressing the same feelings over and over is a bit like the grandmother in Eudora Welty’s story, A Worn Path. The woman in this story travels the same path every year at the same time, seeking medicine for a child who died years before. No medicine will bring back the grandmother’s dead child. Writing in a journal every day about that same issue with the same words in the same way will probably not bring the relief you seek and may actually do more harm than good.

My own experience is that journal writing works best on an as-needed basis as a life-course correction. If your life is going well, you are happy, and are not obsessing about things in the past, why over analyze yourself?

Let it go and enjoy life as it comes. It is safe to say that some future miseries will visit you again. When they happen, do some expressive writing to deal with them.

When Should You Write?

How soon after a Trauma / Emotional Upheaval?

# Recent trauma / emotional upheaval

# Present trauma / emotional upheaval

# Past trauma / emotional upheaval

# Future trauma / emotional upheaval: Is it helpful to write about the eventual death of a loved one? Or a divorce that you know is coming? Or something else in the future? Sure, why not? It’s free. But in your writing, explore why you are having the feelings and how these feelings relate to other issues in your life. Remember that the point of this writing is how we make sense of a troubling experience or event and how we incorporate that experience into the entire story of our lives.

Some Questions To Ponder Over

  • Is This a Good Time in Your Life to Write?
  • What’s the Best Time of Day to Write?
  • Where Should You Write?
  • What Technology Do You Need to Write?

Think about:

# Creating a unique environment.

# Creating a ritual for writing.

And Finally, The Flip-Out Rule

I hereby declare you ready to begin your expressive writing experience.

But before you start, it is important to review The Flip-Out Rule.

If you feel that writing about a particular topic is too much for you to handle, then do not write about it. If you know that you aren’t ready to address a particularly painful topic, then write about something else. When you are ready, then tackle the other topic. If you feel that you will flip out by writing, don’t write.

What could be simpler?

Enjoy your writing.

Tags: Book Summary,Psychology,