Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, January 15, 2016

Python is Over 9000!

In my last post I asked you, my dear reader, to try and flex your programming muscles solving some tasks in C++ language. Now is the time to compare the solutions of the aforementioned exercises in both Python (written by me, please take a note that I have learnt Python in the last year) and C++ (solutions from my friends who know how to program). Big shoutouts to them, as without their work this post will not be that long. You can check their profiles on github - przemkovv and MichalNowicki).

The code

1) lets assume we have two collections and would like to print values from them in the following format:
value_0_from_first_collection, value_0_from_second_collection
value_1_from_first_collection, value_1_from_second_collection
etc.

So for the warm-up we are doing something rather easy, that in Python looks really straightforward:

for n1, n2 in zip(numbers_1, numbers_2):
    print(n1, n2)

For those not familiar with Python - you can check zip function here. In this case it is returning elements from both collections which are assigned to names n1 and n2.

In C++ it looks a little bit more cumbersome (what are this magical * sign? :P):

for (auto it = kolekcjaA.begin(), it2 = kolekcjaB.begin(); 
     it != kolekcjaA.end() && it2 != kolekcjaB.end(); ++it, ++it2) {
    std::cout << *it << " " << *it2 << std::endl;
}

Or if you use some dark magic you can get something similar to what Python is offering:

vector<tuple<char="", int="">> out_zipped;

transform(vec.begin(), vec.end(), str.begin(), back_inserter(out_zipped), [](auto x, auto y){ return make_tuple(x, y);});

for_each(out_zipped.begin(), out_zipped.end(), [](auto t) {
    cout << get<0>(t) << ", " << get<1>(t) << endl;
});

It gets the job done but I would say that Python solution is much neater.

2) lets assume we have a text and we would like to print it without the first and the last sign. In addition we would like to print the text length.

Python:
print(text[1:-1], ", " + str(len(text)))

C++:
// solution 1
std::cout << text.substr(1, text.size() - 2) << " " << text.length() << std::endl;

// solution 2
string cut_from_both_sides(str.begin() + 1, str.end() - 1);
cout << cut_from_both_sides.length() << " " << cut_from_both_sides << endl;

All of them looks similar, but look at the next task to see the advantage of Python solution!

3) we have a collection of values and we would like to print it without the first and last values. In addition we would like to print the size of the collection.

Python:
print(numbers_1[1:-1], ", " + str(len(numbers_1)))

C++:
// solution 1
for (auto it = kolekcjaA.begin() + 1; it + 1 != kolekcjaA.end(); ++it) {
    std::cout << *it << std::endl;
}

// solution 2
vector<int> vec2(begin(vec) + 1, end(vec) - 1);
cout << vec2 << endl;

As you can see the Python is still using the same way, while C++ solution 1 evolved to using iterators, while the C++ solution 2 is the same but will not work for lists (and other collections that do not offer [] operator)!

4) we have a function that has to return:
a) two values,
b) three values.
How would you implement that?

Python:
def increment_all(a, b, c):
    return a+1, b+1, c+1

x, y, z = increment_all(x, y, z)
print(x, y, z)

C++:
auto triple_return() {
    return make_tuple(5, "good", 3.5);
}

auto gotcha3 = triple_return();
cout << get<0>(gotcha3) << " " << get<1>(gotcha3) << " " << get<2>(gotcha3) << endl;

To save space I left just triple return. At first glance all the solutions look similar, but take a closer look how you print the returned values and you will appreciate Python simplicity. Also it is possible to swap values without additional buffers:

a, b = b, a

5) for collection of your choice do:
a) print all values,

Python:
for v in values:
    print(v)

C++:
for (auto value : vec3) {
    std::cout << value << std::endl;
}

Nothing extraordinary. C++ has similar construction for getting elements from collections.

b) increase each value by 10,

Python:
values = [v+10 for v in values]

C++:
// solution 1
for (auto& x : vec3) {
    x += 10;
}

// solution 2
transform(begin(vec3), end(vec3), begin(vec3), [](auto x) { return x + 10; });

This is where things start to be interesting. In Python you use thing called list comprehension, which is general and elegant way to work on containers. In C++ you can use solution similar to the last one but you have to remember to use another special C++ operator - &. Solution 2 is a way to mimic Python behaviour.

c) remove last element,

Python:
values.pop()

C++:
// solution 1
kolekcjaA.resize(kolekcjaA.size() - 1);

// solution 2
vec3.pop_back();

Nothing special, but C++ guys offered two different solutions :)

d) remove n-th element,

Python:
n = 2
values.pop(n)

C++:
// solution 1
int n = 4;
kolekcjaA.erase(kolekcjaA.begin() + n);
}
// solution 2
const int nth = 10;
vec3.erase(begin(vec3) + nth);

Once again C++ solutions does not work for lists.

e) print value alongside its index,

Python:
for i, v in enumerate(values):
    print(i, v)

C++:
// solution 1
for (int i = 0; i < kolekcjaA.size(); i++) {
     std::cout << "Index = " << i << " " << kolekcjaA[i] << std::endl;
}

// solution 2
int i=0;
for (auto it = begin(vec3); it != end(vec3); ++i, ++it) {
    cout << i << " " << *it << endl;
}
// solution 3
i=0;
for (auto x : vec3){
    cout << i << " " << x << endl;
    ++i;
}
// solution 4
for (auto p = make_pair(0, begin(vec3)) ; p.second != end(vec3); ++p.first, ++p.second) {
    cout << p.first << " " << *(p.second)  << endl;
}

In Python this is straightforward - enumerate and done! C++ offers a lot of solutions, that have some pros and cons. I prefer to have one main solution - it helps when more than one person is working on with the code.

f) check if value x is in collection,

Python:
if 27 in values:
    print("27 is in the collection")

C++:
// solution 1
bool contains_25 = find(begin(vec3), end(vec3), 25) != end(vec3);
cout << contains_25 << endl;
// solution 2
auto contains_x = [](auto C, auto x) { return find(begin(C), end(C), x) != end(C); };
cout << contains_x(vec3, 25) << endl;

Once again you can witness how elegant Python is. It is the most straightforward way and even non-programers would understand what this code do.

g) check if all values are smaller than y.

Python:
if all(v < 30 for v in values):
    print("All values are smaller than 30!")

C++:
// solution 1
int twojaWartosc = 4;
auto wart = std::find_if(kolekcjaA.begin(), kolekcjaA.end(), [&twojaWartosc](auto const &x) { return x < twojaWartosc; });
std::cout << "Wartosc : " << *wart << std::endl;

// solution 2
int y = 50;
cout << all_of(begin(vec3), end(vec3), [=](auto x) { return x < y; }) << endl;
// solution 3
auto less_y = [](auto y) { return [=](auto x) { return x < y;  }; };
cout << all_of(begin(vec3), end(vec3), less_y(20)) << endl;

Python is clean and simple. In C++ you can use different ways, but even this simple task can cause problems - solution 1 throws exception when the value is not in the collection as you try to access (dereference) an iterator that point to the end of collection.

6) having a text count how many letters are lower-case and how many are upper-case

Python:
number_of_uppercase_case = sum(1 for c in text if c.isupper())
number_of_lowercase_case = sum(1 for c in text if c.islower())

C++:
// solution 1
int male = std::count_if(podanyTekst.begin(), podanyTekst.end(), [](unsigned char x) { return islower(x); });
int duze = std::count_if(podanyTekst.begin(), podanyTekst.end(), [](unsigned char x) { return isupper(x); });

// solution 2
cout << count_if(begin(s), end(s), islower) << endl;
cout << count_if(begin(s), end(s), isupper) << endl;

All the solutions are very similar - they use built-in functions. The thing with Python is that you can use almost the same code for other things like e.g. extraction of lower-case letters:

lower_case_letters = [c for c in text if c.islower()]

7) is there any situations that you do not use indentation?

We all have agreed that apart of code golfing everybody should use indentation. So if it is obligatory lets resign from { and } brackets. Their are unneeded and deprecated. Lets use Python!

8) are you using standard arrays (static or dynamic) at all (like: int a[5] or int* b = new int[5])?

Once again we had a consensus - dynamic tables should be avoided as they can be dangerous.
When I think about them two quotes comes to my mind:

C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.

-- Bjarne Stroustrup

With great power comes great responsibility.

-- Voltaire

Other

On a side note - this is probably the longest most in my career.
If anybody is interested I used Syntax highlighter to post the code. It offers nice looking code but embedding small portions of code is cumbersome - you have to edit html code and doing it through the browser is a pain.

Summary

I hope you enjoyed this long, over 9000 signs comparison. By no mean I was trying to defame C++. I think it is an important programming language, that has its uses (C for microcontrollers, some high performance routines and libraries). Just in my opinion the new additions to C++ (C11, C14) that tries to convert it to modern programming are a failure. They change many things upside-down, make the code much different to understand for people that are not familiar with new standards while the code is still not as elegant and readable as Python. It is just my two cents, opinion that is probably heavy influenced by my experience - I did a lot of programming for embedded systems (microcontroller based).



If, by some accident, you are still not convinced about Python greatness you are not alone. Apparently some people think Python is overrated ;)

TL; DR

This post describes why I think Python is a great language, especially when you are starting learning how to program. Different simple exercises were done in both Python and C++ and the code was compared. Python rulez.

Wednesday, December 30, 2015

I became a Python zealot!

Some time ago I started solving coding puzzles from codingame webpage. I mentioned it in a previous blog entry. I am doing all the puzzles in Python as a way to learn this language. Currently I have done all easy, all except one medium, half of hard and half of very hard. You can find solutions on my github account.

Thing that I would like to share with you today my dear reader is my findings about Python language.

Let me give you some background:

I learned some basics Pascal in a high school (using the Free Pascal IDE, yes the blue one pictured below!) and created a master mind game (you can admire this marvellous piece of work here).


Then I started my studies - Control Engineering and Robotics and learned C and C++. It was during medieval ages, harsh and dark times without vectors, list and all other shiny things kids play with these days. I prepared my own double-linked list, stack, queue through the pain and hard work.

On a second year, way before it was introduced on lectures I started working with microcontrollers and after short stint using asembler (I still have one of the programs I wrote, check it HERE) I switched to programming them in C. At that times the mighty AVR Studio 4 was considered a state of the art IDE, with no code completion and ugly looking font! All of this skewed me away from the objective C++ and made me favour C.

After the second year of studies I started additional field of studies - Computer Science. There I have learnt that C# is a great way to write programs with windows, buttons and so on. I also got to know collections, generic types and a world without pointers. On the other hand I was introduced to image processing library called OpenCV (during glory days of C api with IPLImage and manual memory managment <yay>). What is funny is that you can still found a lot of advices and code examples related to old OpenCV APIs. During that times I just coded - if there was a task, I did it, did not have any favourite language - I used what was best suited - C for micros, C++ for image processing, C# for windows apps. I did not know about unit tests, refactoring, clean code theories, version control systems (!) and other things. There were just problems that had to be solved. If the problem was small enough I was able to finish it fast, if it was rather large I was suffering because of my unawareness of  proper code management techniques. I drifted far away from the main point that I was planning to make - during all that time I did not find my go to language.

Diving into Python

Last year a friend (thanks a lot Marek!) convinced me to try Python. At the beginning I was sceptical as I thought that the same thing can be achieved with C# or C++ with heavy usage of standard library (especially with new things from C++11). Boy I was wrong! During this year I wrote some programs with Python:
and solutions for codingame puzzles:

After the last one especially I came to conclusion that Python is a great language to start your programming journey. This is somehow important to me as I am teaching programming at the Poznan University of Technology. Earlier, I was teaching students how to solve problems using C/C++ programming language and I did it with passion. Nowadays I am doubting if it is the best way and it is because of Python. I tried to convince my colleagues about Python superiority but they are stubborn so I will try to convince YOU, the reader. Try solving following problems in C++, while I will do them in Python and we will compare the solutions in the instalment of this series (I sent the questions to a few friends and if they accept I will post their solutions too). Here we go:

* you can use any collection you find appropriate for the task (vector / list / other). Same goes for strings / arrays of chars.

1) lets assume we have to collections and would like to print values in the following format:
value_0_from_first_collection, value_0_from_second_collection
value_1_from_first_collection, value_1_from_second_collection
etc

2) lets assume we have a text and we would like to print it without the first and the last sign. In addition print text length.

3) we have a collection of values and we would like to prit it without the first and the last value. In addition print collection size.

4) we have a function that has to return:
a) two values,
b) three values.
How would you implement that?

5) for collection of your choice do:
a) print all values,
b) increase each value by 10,
c) remove last element,
d) remove n-th element,
e) print value alongside its index,
f) check if value x is in collection,
g) check if all values are smaller than y.

6) having a text count how many letters are lower-case and how many are upper-case

7) is there any situation that you do not use indentation?

8) are you using standard arrays (static or dynamic) at all (like: int a[5] or int* b = new int[5])?

TL; DR

My programming history was presented. It is full of entertaining and absorbing adventures (who would contempt some asembler and pascal code!) that you should read carefully. Also Python is the thing right now. At the end I ordered you a homework that you have to do and post the solution in the comment section below!

Thursday, November 19, 2015

Programming quotes

I have few posts written, all filled with ideas and a lot of raw text. I wanted to post each of them a long time ago, but I always postpone it for later, to finish it, than get new idea, start working on it and never finish the old ones. Today I decided to start and finish post to convince myself that I am able to do it!

As you know I am doing puzzles from codingame webpage (this post describes it). I am doing my best, but still did not cracked top 100 (I am ranked at 132). While solving some problems I found that I am often reinventing the wheel - due to my poor knowledge of algorithms I am wasting a lot of time discovering simple things (e.g. graph algorithms...). I decided that even though they say you can not teach old dogs new tricks I will read Algorithms in a Nutshell book to raise my skills to the next level! There is interesting quote in the introduction that I quickly inserted into my collection of programming quotes. Then I decided to share my little collection, maybe it will be helpful to somebody. So here we go:

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
-- Brian W. Kernighan


premature optimization is the root of all evil
-- Donald Knuth


Modern software development is not about being an ace programmers anymore. It is about being a team player that empowers co-workers with:
Elegant design.
Easy to read and commented code implementing it.

-- Fabien Sanglard, http://fabiensanglard.net/


Any code of your own that you haven't looked at for six or more months might as well have been written by someone else.
-- Eagleson's law


Projects just seem to rot when you leave them alone for long periods of time.
-- John Carmack


There are only two hard things in Computer Science: cache invalidation and naming things.
-- Phil Karlton


Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
-- Douglas Hofstadter


Later means never.
-- LeBlanc’s Law


C++11 feels like a new language.
-- Bjarne Stroustrup


Write lasagne code instead of spaghetti code.


Great Developers Know When Not To Refactor. If it ain’t broke, don’t fix it.


Perfect is the enemy of the good.


Release early, release often.


If the physics allows then it can always be solved given enough money – which just means finding a big enough market.
-- notzed comment @ CNXSoftware


TL; DR
In the post I shared my collections of programming quotes that I found somewhere on the Internet and think that they are useful.

If you have your favourite quotes please share them in the comment section below!

Saturday, October 17, 2015

Codingame - fun way to hone your programming skills

Some time ago a friend show me a webpage where you can polish you coding skills while having fun!

There are a lot of sites that offer programming tasks / exercises. Usually you get the instructions and when you have prepared the solution then you can upload it as a source file. It is then tested and at the end you are provided with the information about the results of you program (if it work as it should or if it does not work).

The main advantages of CodinGame site are:
  • number of languages accepted (23),
  • online editor with autocomplete function and three styles (e.g. Vim / Emacs),
  • well defined tasks with a lot of well-thought out test cases,
  • the ability to debug your program round by round,
  • fancy and nice looking graphics and animation (I know that it is not the most important part, but it makes solving the task more appealing, especially to begginers) alongside console output to help with the debug process,
  • achievements ;)
You can visit the site by clicking the image below:


The site offers few types of competition:
  • single player puzzles,
  • multi player,
  • optimization,
  • online clashes,
  • live contests.
Today I will focus on the first type - single player puzzles. This is the oldest feature of the site and there are 52 puzzles with different difficulty levels. On each of the level you get the task description, which states what the program has to do alongside with detailed information about  the input that is provided and the output expected. Usually some initial information is given at the beginning and then the puzzles are played in turn-by-turn way - you are given current state and have to provide the output - your action. For each task there are well defined test cases that starts with very simple ones, that can often be passed with simple, naive solution. Each test is more and more difficult and checks your program against different input data (edge cases) or tests performance of your code (so that you use something more refined than bruteforce solutions). In addition to this some of the puzzles has graphic animations of what is happening so it feels like you are playing a game and in the end you even get achievements! What is even better - it can land you a job!

 All in all I can wholeheartedly recommend the CodinGame website for both the advanced programmers and to beginners. Great way to improve coding skills while having fun!

Also you can find my solutions on my github:

https://github.com/Michal-Fularz/codingame_solutions

at the moment I have all easy puzzles done in Python (2.7.x). Some others (medium / contest /clash of code) are work in progress. Please take into account that I am learning Python language currently. If you find errors or non-pythonic code let me now. I would like to improve my Python skills as I enjoy the language a lot. 


TL; DR

CodinGame is a webpage with coding puzzles done right - they are interesting and fun to do. Also you get achievements on your way and can even get a job!

Wednesday, December 31, 2014

Project Shining Runners Cap

Greetings my dear reader (readers? - I dunno how many of you reads my scribbles)!

When I started running I made one more resolution - to stop procrastination. To never ever postpone doing something I wanted to. Usually I had a lot on my mind (mostly stuff related to work) and all this pulls me from bringing my new cool ideas to life. The end result is that I waste my time - I don't have power to do the things I had to so I just... wander around the Internet for too much time. This era has definitely ended and now I will carry out all my ideas :) I say NO to procrastination!



Project origins


During October I was usually running few hours after work which means at around 8 or 9 pm (20/21 in polish time). The place I run has some parts with lights, but some parts are covered in darkness. To avoid collisions with bikers and other people (and to be less scared of darkness) I used simple app on my phone that uses flash light to blink at some intervals. The app is called Tiny Flashlight and can be found in Google Play. The strobe mode can be found here (there is some problem with that link... I don't know why, it works for me (I have this app installed) but not for other users...).

During my night runs I was thinking how to better light myself (not literally!) - eg. use colourful lights to show the pace or the music that I'm listening. That's how it all started...

The result


After few single person brain storms done while running I decided to upgrade my current cap with lightings. I grab some led lights from older projects, convinced my wife to prepare some material and this is what I get:



As you can see from the video it is in very early pre-alpha state. I used some W2801 led stripe sewed into scrap of material. It is connected to Arduino (control, on the right) and some DC/DC inverter (power, on the left). It supposed to be letter A... at the back of the cap there are four more lights.

All in all I'm not satisfied with current version. The led stripe is difficult to strap to material, its connectors are prone to be damage by bending (like iphone... maybe it should be named iCap;) and at the moment it looks just bad. That's why I'm abandoning this version and  leaving it in this unfinished state. It's not worth putting the work when you can have much better lights (they are already coming thanks to aliexpress.com!).

Somewhere in the future I will describe in details all the plans and parts for my super-duper cap!

Ohh and: Happy new year!

Sunday, December 14, 2014

Hackathon numer 1!!11!!!!1!!

The idea of late night coding

Some time ago a friend of mine linked me this article:
http://en.codeceo.com/why-programmers-work-at-night.html

It strikes me that I totally agree with all the arguments about why coding at night is productive. Unfortunately my work obligations require me to get up early on every Monday, Tuesday and sometimes on Thursday. Despite this, last week I tried late-night coding at it was fun, it reminds me of the times when we were constructing and programming sumo robots whole night, just before the competition!

Goal definition

Encouraged by the success of this programming effort I decided to do it again on the weekend. As weekend should be free from work stuff I went for my own secret project that I was planning during my running workouts. I found some inaccuracies in the way the Endomonod (application + website I use for recording my runs) calculates records and lap time. More details about this in some future post. In short the planned app has to be able to:

  • read the *.tcx file (holds all the information about activity like all the trackpoints)  exported from Endomondo website,
  • calculate the distance travelled based on longitude, latitude and altitude data,
  • show the data on charts.

As you may know, writing an app is not as much fun as writing it in a new language! Killing two birds with one stone - writing the app and learning the basics of Python was my goal!

Hell, it's about time to start The Hackathon!

It all started at 6:00 pm and finished at 2:16 am (not that late!) with some breaks in-between (eating, discussing differences between programming languages with friend and so on).

The whole process was documented and can be found on github (tried to commit changes regularly):
https://github.com/Michal-Fularz/python_tcxVisualizer

This was my first foray into the Python world, and oh boy, what a ride it was! I don't know where to start so maybe I will just write how the hackathon went and then present my thoughts on Python.

I used Python Tools For Visual Studio with Visual Studio 2013 Community Edition and Python 3.4. All the necessary packages were downloaded from this dedicated website. (lxml, scipy).

As reinventing the wheel was not my goal so I started with a search for libraries / code that can help me with my task. I found this and was able to almost immediately start working with the data from *.tcx files. Then I ask google about the way to calculate the distance between two points described by latitude and longitude and found a link to a Python implementation through a wiki page. Almost all the code was found somewhere in the internet (as I didn't know how to iterate through the collection, how to write if statement or even for loop). Fortunately there are so many good tutorials and info pages that I was able to accomplish my goals - prepared application reads the data from *.tcx file, put it into designed object, calculates all the interesting values (lap times, average speed, total distance, etc.) and shows them on the charts. I manually added some values from Endomondo website to compare with the ones I calculated. Image below shows my app printing some calculated values.

Results printed by my program. Also the speed chart (I run over 80 km/h at some point!).

Summary

To sum up this lengthy post (keep in mind that these are beginner thoughts on Python):

I have a lot of fun programming this simple app in Python. What really surprised me is how much examples you can find (almost all my problems were resolved with just one query to google). The syntax is really neat. The way you handle most things is different than C/C++ or C# (languages I'm familiar the most). I have to thank a lot Przemek Walkowiak (przemkovv) for his tips about Python. He showed me some secret magic like list cohesion, bisect and zip functions. Instead of using this tools I was for looping (C-style) most of the time :)

8-hour hackathon was nice experience and I'm satisfied with what I achieved.

What the future holds

The program still requires some work - it can't handle lack of altitude filed in *.tcx files. It will fail if there were stops during the workout. The charts require some polishing. There should be some automatic way to download the data from endomondo website (I found this). All in all two or more hackathons are required two finish this little project. See you soon!

TL; DR

I taken part in my own 8-hour hackathon and learned Python programming language while writing the program to analyse and visualise the data from my workouts (Endomonod website). Result can be found on my github.