DEV Community

oldtechaa
oldtechaa

Posted on

Perl Weekly Challenge #219 - Squaring Up

Hi everybody! This week again because of time I only finished the first challenge of The Weekly Challenge. However, because work for my client requires Python, I'm busy learning Python and I thought "Why not do Python for a simple weekly challenge task?" This is the first Python code I've ever truly written and not just modified!

First, the Perl:

say $_ for (sort {$a <=> $b} (map {$_ * $_} @ARGV));
Enter fullscreen mode Exit fullscreen mode

Yep, a one-liner. Normally I prefer to write longer, more readable code, but this time the task was so simple it made sense just to write it on one line.

We map each argument on the command line into its square, then sort (with a numerical sort because map defaults to strings) and then just say() them.

Originally I was sorting with a custom sort routine based on absolute values, but then I realized (thanks to other blog posts) that it would be more efficient not to abs() anything and just to replace everything with its square first, then sort.

Now for Python:

list = [int(input("Num1:")), int(input("Num2:")), int(input("Num3:")), int(input("Num4:")), int(input("Num5:"))]
for index in range(len(list)):
    list[index] = list[index] ** 2
list.sort()
for square in list:
    print(square)
Enter fullscreen mode Exit fullscreen mode

It essentially does the same thing by replacing everything with its square, then sorting, then printing. It only takes 5 arguments because I'm not familiar with Python argument methods. I do like the simple input() command. It's quite a nice feature compared to Perl.

Hope to see you all next week!

Top comments (0)