I challenged you ๐Ÿ†...

You delivered ๐Ÿ’ช!

I asked you to implement the sign function in Python ๐Ÿ.

Now I'll go over some alternatives and tell you what I like โœ… and dislike โŒ about them.

I'll also tell you which one I think is the best, most Pythonic โœจ one.

๐Ÿ‘‡๐Ÿงต
By the way, for reference, here is the original challenge:

Let's start with the โ€œbasicโ€ `if: ... elif: ... else: ...` approach first.

Gets the job done, is simple, and is easy to ready.

Funnily enough, the only one to share that solution was a _very_ seasoned Python ๐Ÿ programmer, author and trainer, @dabeaz ๐Ÿ™ƒ

Now, a couple of notes:
For the arg name, we don't need something VERY long like `number`, but don't shorten it to `n`.

`n` has a connotation for positive whole numbers, and `sign` accepts other numbers.

I also prefer to have the `else:` return the `0`, and that's to preserve the symmetry of 1 and -1.
We can use this as the cornerstone for many interesting implementations.

For such a simple function, it might look like a bummer that we have to spend 6 lines implementing it.

Can we shorten it a bit, perhaps?

Using conditional expressions, we can ๐Ÿ‘‡
We can also get rid of the `else`, which may reinforce the sense of โ€œ0 is just an edge-caseโ€...

Depending on how you usually read Python code.

Here it is:
Now, you might be thinking...

Instead of returning the conditional expression...

Can I compute ๐Ÿงฎ the 1 or -1?

Well, you can!

And many of you submitted things like this ๐Ÿ‘‡

But that gives rise to another issue...
Do we really need the `int`?

Well, depends on what you want your function to return, because `abs(x) // x` returns a float if `x` is a float.

And what about floating point inaccuracies? Does `int(abs(x) // x)` always return 1?
To be honest with you, I am not entirely sure!

I couldn't find a value of `x` for which `abs(x) // x` evaluated to 0.99999(something).

However, to be extra safe, you could replace `int` with `round`.

Ok, and are there โ€œsaferโ€ alternatives?
There are!

Have you heard about the Truthy and Falsy values of things in Python?

That makes it so that all objects can be interpreted as Booleans when needed.

But did you know that Booleans (`True` and `False`) can be handled as integers??

Hence, you can write this ๐Ÿ‘‡

Whatโ‰
I like the fact that it looks like a face:

(x > 0) - (x < 0)

The `-` is the nose, and the `(...)` are the eyes!

And there's even the added benefit that you can drop the `if` statement:
In my opinion, this is very cool!

BUT it's not the โ€œway to goโ€ in Python, generally.

This looks more like a thing you'd do in an array-oriented language, like APL.

So, we steered away from Pythonic solutions.

Can we get back on track?
Yes!

But let's not, for now ๐Ÿ˜‚

I just wanna show you another interesting one, making use of the integer value of Boolean values ๐Ÿ‘‡

It looks interesting, and it is useful to _understand_ how it works.

But I'm sure the majority won't feel this is Pythonic.
I think the conditional expression wasn't that bad, right?

Maybe we could improve on it?

Well, we can try!

What if we nest two conditional expressions to handle the three cases?

Again, just a quick remark about this one:
I like to have 0 at the end, because I like the symmetry between

๐Ÿ‘‰ x > 0 โ†’ 1
๐Ÿ‘‰ x < 0 โ†’ -1

This might sound silly to you, but these symmetries and patterns really make my life easier!

That's why I prefer this ordering over, say, this one ๐Ÿ‘‡
But we can still be friends if you order things your way ๐Ÿ˜

Another thing to notice is that all the `if`s with `if x == 0` could be replaced by `if not x`.

Some might prefer it, some might not.

I have no strong feelings for neither ๐Ÿคทโ€โ™‚๏ธ
Is there any other way to emulate the โ€œchoose one of -1, 0, or 1โ€ behaviour without using long `if`s..?

Someone submitted this, and I gotta say:

It looks odd, but it is incredibly easy to read.

Is it Pythonic? I don't think so ๐Ÿ˜ข
Instead of accessing a dictionary, we can also try to index into a list.

Now, close your eyes and skip this if you don't want to be horrified ๐Ÿ‘‡

It's not that bad ๐Ÿ˜‚

Again, not recommended style, but _understanding_ how it works gives insights into how Python works.
This can be taken one step further.

Should you?

Nah.

Will I do it nonetheless?

Absolutely!

Here it goes ๐Ÿ‘‡ Can you understand how it works?
Hmmm, 'kay.

That's all nice and fine.

What if I don't want to use `if`s, but also no weird Boolean computations?

Then, maybe you could try new pattern matching feature from Python 3.10!

In case you need to learn it:
Can we use `match` to solve this?

Well, not directly.

Which shows that `match` really isn't the tool for this job.

But we can use guards and get away with it ๐Ÿ‘‡

But if you look closely, the `case` statements aren't doing anything!

So, can we get rid of them..?
Absolutely, and you end up with this ๐Ÿ‘‡

Equivalent to the `if` from the beginning, but condensed.

Canned `if`-blocks, everyone!

Ok!

So, we used `match` and ended up getting away from it?

Unacceptable!

One more try:
`match` is supposed to be useful for structural pattern matching.

Can we match patterns, then?

Of course. Here's a solution no one submitted, but that I came up with ๐Ÿ‘‡

What do you make of it?
All in all, there are plenty of interesting solutions in this thread.

So, which ones do I prefer?

Well, *personally*, I love weird snippets of code ๐Ÿ˜‚ But I don't write them in production.

So, that means I end up with a split preference, between ๐Ÿ‘‡

and the slightly condensed `if: ... elif: ... else: ...` block ๐Ÿ‘‡

I don't know why, but it *really* bothers me that such a simple function takes 6 lines of code as a โ€œfullโ€ `if: ... elif: ... else: ...` block!

(Does anyone else feel like that?)

Thanks for making it so far!

I'd love if you read your thoughts on these solutions!

Here's a quick link to the beginning of the thread. Leave your comments there ๐Ÿ’ฌ and retweet ๐Ÿ” it if you found value in this thread!

Finally, if you have ideas for future challenges, feel free to send them to me!

Write them down in the comments, or send me a DM!

Then, if you want to keep learning a lot about Python ๐Ÿ, follow me @mathsppblog.

I'll see you soon! ๐Ÿ‘‹
P.S. I should give credit to everyone who contributed to this thread by sending their solutions.

Many people replied, so I don't think I should mention all of them..? You can find all of them in the original challenge, linked at the beginning.

Thanks a lot for participating!

โ€ข โ€ข โ€ข

Missing some Tweet in this thread? You can try to force a refresh
ใ€€

Keep Current with Rodrigo ๐Ÿ๐Ÿ“

Rodrigo ๐Ÿ๐Ÿ“ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

28 Sep
Interested in improving your Python ๐Ÿ skills?

๐Ÿค” If you are, have you learned about conditional expressions?

Here is a MEGA thread ๐Ÿ‘‡๐Ÿงต teaching you almost everything there is to know about conditional expressions!

I will include a bunch of examples ๐Ÿ–ผ, so don't worry!
This is the follow-up to my experiment from earlier today.

I tried teaching you about conditional expressions without words ๐Ÿ˜ถ.

Here is the original thread:

Alright, so conditional expressions aren't that hard, really.

It is just an expression: a piece of code that evaluates to a result.

But then, it is tied to a condition: depending on whether the condition is truthy or falsy, the final result changes.

Check the function below:
Read 30 tweets
28 Sep
๐Ÿค” If you are learning Python ๐Ÿ, I want to do an experiment:

Here's a thread ๐Ÿ‘‡๐Ÿงต teaching you conditional expressions.

BUT, I will teach you with NO words ๐Ÿ˜ถ

I will only show code snippets and examples.

Check the thread out carefully ๐Ÿ” and then give me your feedback!
By the way, if you want to learn something from this thread...

I'm not going to lie, you'll have to focus ๐Ÿ”.

Also, what's the rationale for this crazy ๐Ÿคช thread?

By reading code and examples, you see first-hand how the feature is used and where it comes in handy.

Let's go:
Read 17 tweets
26 Sep
Have you heard that Python ๐Ÿ 3.10 will be released soon?

Are you ready for when it drops ๐Ÿ’ฃ๐Ÿ”ฅ?

Python 3.10 will ship with the new โœจ match statement, and I created a cheatsheet just for that.

This is also a thread ๐Ÿ‘‡๐Ÿงต that breaks it down and explains everything:
The cheatsheet is free and teaches you 12+ things about the new `match` statement.

From the basics, to object destructuring, to wildcards, among other things.

Get it from the link ๐Ÿ‘‡, and keep reading below to learn all about the `match` statement.

mathspp.gumroad.com/l/cheatsheet_mโ€ฆ
In its most basic form, a `match` statement kind of resembles an `if` statement.

That's what most of the โ€œswitchโ€ or โ€œmatchโ€ statements in other languages do: a series of `if` / `elif` / `else` statements.

Even a basic `case` is powerful: use `|` to separate multiple options. Image
Read 23 tweets
25 Sep
What's the BEST way to learn Python ๐Ÿ?

I've been writing Python for 10 years and taught 100s of people.

Here is a FAQ with actionable advice ๐Ÿ‘‡๐Ÿงต

But everyone is different, so share your thoughts as well ๐Ÿ‘‡๐Ÿ’ฌ to help as many as possible!
๐Ÿ โ€œHow do I start learning Python?โ€

Well, I think the answer to this question greatly depends on whether you have (considerable) programming experience with another language or not.

That's because โ€œlearning Pythonโ€ can mean โ€learn the syntax of the languageโ€, but...
... it can also mean โ€learn how to think like a programmerโ€.

And, in my opinion, this is something very fundamental that you have to understand!

Being a programmer is also about having that programmer mindset.

Worry not, you can learn it ๐Ÿ˜Š
Read 35 tweets
24 Sep
Do you want to master Python ๐Ÿ list comprehensions?

Do you want to become more proficient working with lists in Python ๐Ÿ?

If you answered with โ€œyesโ€, then here's a cheatsheet of mine to help you out.

This is also a thread ๐Ÿ‘‡๐Ÿงต that breaks it down and explains everything:
First off, here is the anatomy of a list comprehension.

There's 4 parts to a list comp:
1. enclosing brackets to create the list [];
2. expression that transforms your data;
3. `for` iteration over the initial data;
4. (optional!) condition to filter some data.
Do list comprehensions look confusing?

Maybe.

But that's because you didn't realise that list comprehensions have equivalent `for` loops!

The coloured boxes below show the equivalent bits in the list comp and in the `for` loop:
Read 19 tweets
23 Sep
Do you know what the Python ๐Ÿ `type` is?

But do you _really_ know what it is?

Here is a valuable thread that will give you insights into what `type` is and does.

Let's go ๐Ÿ‘‡๐Ÿงต
What does `type` do?

You might say that `type` takes an object and returns the type of the argument.

Here are some examples:
Fine, so `type` is a function!

Or is it..?

Take a look at the example above.

`sum` is a built-in function and `type(sum)` returned โ€œbuilt-in function or methodโ€.

So, logically, if `type` is a (built-in) function, the type of `type` should give the same thing:
Read 14 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(