Monday, July 9, 2018

Format


Here is all you need to know about string formatting. I have summarized the page https://pyformat.info/ , in fact I just removed all explanations and made a simple cheat sheet in Jupyter Notebook. I copy the text here for convenience but you can download notebook file from GitHub


'{} {}'.format('one', 'two')
Out:  'one two'

'{} {}'.format(1, 2)
Out[2]: '1 2'

'{1} {0}'.format('one', 'two')
Out: 'two one'

class Data(object): 
     def __str__(self): 
          return 'str' 
     def __repr__(self): 
          return 'repr' 
'{0!s} {0!r}'.format(Data()) 

Out:'str repr'

class Data(object): 

     def __repr__(self): 
          return 'räpr' 
'{0!r} {0!a}'.format(Data())
Out: 
'räpr r\\xe4pr'

'>{:>10}<'.format('test')
Out:  '> test<'

'>{:10}<'.format('test')
Out:  '>test <'

'{:.<10}'.format('test')
Out:    'test......'

'{:.^10}'.format('test')
Out:    '...test...'

'{:.^6}'.format('zip')
Out:   '.zip..'

'{:.5}'.format('xylophone')
Out:   'xylop'

'{:.<10.5}'.format('xylophone')
Out:    'xylop.....'

'{:d}'.format(42)
Out:   '42'

'{:f}'.format(3.141592653589793)
Out:     '3.141593'

'>{:4d}<'.format(42)
Out:   '> 42<'

'{:06.2f}'.format(3.141592653589793)
Out:   '003.14'

'{:04d}'.format(42)
Out:   '0042'

'{:+d}'.format(42)
Out:    '+42'

'{: d}'.format(-23)
Out:    '-23'

'{: d}'.format(23)
Out:    ' 23'

'{:=5d}'.format(-23)
Out:    '- 23'

'{:=+5d}'.format(23)
Out:   '+ 23'

data = {'first': 'Hodor', 'last': 'Hodor!'} 
'{first} {last}'.format(**data)
Out:   'Hodor Hodor!'

'{first} {last}'.format(first='Hodor', last='Hodor!')
Out:   'Hodor Hodor!'

person = {'first': 'Jean-Luc', 'last': 'Picard'} '{p[first]} {p[last]}'.format(p=person)
Out:     'Jean-Luc Picard'

data = [4, 8, 15, 16, 23, 42] '{d[4]} {d[5]}'.format(d=data)
Out:       '23 42'

class Plant(object): type = 'tree' '{p.type}'.format(p=Plant())
Out:     'tree'

class Plant(object): 

        type = 'tree' 
kinds = [{'name': 'oak'}, {'name': 'maple'}] '{p.type}: {p.kinds[0][name]}'.format(p=Plant()) 
Out:  'tree: oak'

from datetime import datetime 

'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
Out:   '2001-02-03 04:05'

'{:{align}{width}}'.format('test', align='^', width='10')
Out:    ' test '

'{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
Out:     'Gib = 2.718'

'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
Out:    ' 2.72'

'{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')
Out:    'Gib = 2.72'

from datetime import datetime 

dt = datetime(2001, 2, 3, 4, 5) 
'{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
Out:    '2001-02-03 04:05'

'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)
Out:    ' +2.72'

'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
Out:    ' +2.72'

class HAL9000(object): 

       def __format__(self, format): 
                if (format == 'open-the-pod-bay-doors'): 
                         return "I'm afraid I can't do that." 
                return 'HAL 9000' 
'{:open-the-pod-bay-doors}'.format(HAL9000())
Out:    "I'm afraid I can't do that."

class data(object): 
     Height = 52 
     Weight = 75 
class food(object): 
        price = 12 
        stock = 200 
 'Height = {0.Height} and price = {1.price}'.format(data,food)
Out:    'Height = 52 and price = 12'

n=42 'Binary = {:b}'.format(n)
Out:     'Binary = 101010'

n=42 'Character = {:c}'.format(n)
Out:    'Character = *'

n=42 'Octal = {:o}'.format(n)
Out:     'Octal = 52'

n=42 'Value = {}'.format(n)
Out:     'Value = 42'

n=42 'Exponent = {:e}'.format(n)
Out:    'Exponent = 4.200000e+01'

n=42 'Fixed Point = {:f}'.format(n)
Out:    'Fixed Point = 42.000000'

n=42 'Fixed Point = {:%}'.format(n)
Out:   'Fixed Point = 4200.000000%'


Twitter: @DataScienceStep

Sunday, July 1, 2018

Black Jack (OOP approach)

Black Jack 
(OOP approach)

As an assignment for my Python lessons I have to write a simple console Black Jack game logic with object oriented programming approach. So I made Card, Deck, and Players classes and made a simple game.
I was thinking to create a complete library of cards and their ranks in different games, but maybe later :)
The game uses to files constants.py and Black-Jack.py which you can find it at Github:

Twitter: @DataScienceStep



Friday, June 29, 2018

Tic Tac Toe




Tic Tac Toe (Console)

This is a simple game as one of my Python tutorial milestones. I think it worth to keep it and share it with friends.

The code is uploaded in GitHub : https://github.com/DataScienceStep/Python/blob/master/Tic-Tac.py

Saturday, June 23, 2018

Python: Bit-wise Swap Function



Bit-wise Swap Function

Apart from Python binary functions (<< , >> , ^) I noticed I need bit-wise swap function too, It is simple but useful. The Idea is swapping specified bit in binary format of an integer number, if it is 1 turns into 0 and vice versa.
The Functions counts bit positions from right to left and first bit is considered as 1. No error handling implemented.
In the figure you can see the function definition and the sample output as comments.
Enjoy :)


Learning Python via a Project Episode 2

Learning Python via a Project 
Episode 2 / ?
(Crime in Vancouver)

After part 1, I decided to get some analytics results from dataset for some basic insights.
In process I learned how to draw custom pie chars and bar charts.


From data I noticed the most common crime in Vancouver is Theft from vehicle and the region with highest number of crimes is Central Business District but I thought maybe the region is huge that's why the number is high so I calculated percentage of crime in region and it turned out Stanley Park has the highest Theft from vehicle crime rate with much lower number of total crimes in the region. 

I uploaded the code in Github

Learning Python via a Project Episode 1


If there is any comment or suggestion please comment here or twit me at: @DataScienceStep

https://twitter.com/DataScienceStep

Github like:
https://github.com/DataScienceStep/Python/blob/master/CrimeProject.ipynb



Thursday, June 21, 2018

Learning Python via a Project Episode 1



Learning Python via a Project
Episode 1 / ?

I am a newbie in python so I decided to learn it!
The best way to learn a new language is getting hands dirty with the code :)
so I decided to pick a dataset and start an imaginary project and document whatever I think and do for my future reference and also share with others!

The codes are written in Jupyter Notebook with extra explanations but not tutoring in mind :)

Disclaimer! 
These codes and concepts may have wrong ideas or not the best methods, they are just a learning process showcase.

Instead of copy and paste the code here I just give Github address so you can view it there. Later after finishing whole project, I will summarize the concepts that I dealt with them here and update these posts.

leave comments or twit any suggestions.
Thanks


Twitter:
https://twitter.com/DataScienceStep
Github:
https://github.com/DataScienceStep/Python/blob/master/CrimeProject.ipynb

Saturday, June 9, 2018

Python - Linear Regression with tolerance

Ok, here is the situation: In linear regression we come up with a hypothesis to predict a new given value based on train dataset. Standard algorithms output is a real number as prediction but user has no idea about accuracy of the prediction (as far as i know), therefore I thought to write a simple Python code to check how much giving tolerance will be useful.
I wrote a simple code to create a fake dataset which has linear correlation. The output was as figure 1:

As we can see the predicted value in lower values of X has huge tolerance but in higher values it has predicted visibly lower than average data. Therefore knowing how much the predicted value can vary could be useful in some cases. For this matter the function predict() will return final predicted value as well as distance of predicted value from minimum value and maximum value in the nearby data to give better insight of maximum and minimum possible values and the relation of the predicted value with the possible ranges. For demonstration purpose the code prints the calculated values as following:
we can see for given value 2 the predicted value is 0.258 and mean of nearby data around 2 is 0.2612 by calculating average of these two numbers the final prediction will be 0.260 which is enhanced a little based on the data spread nearby. In given value 2 the prediction is almost in the middle of max and min values but for x=3 the distance of prediction with min is -0.21 and with max is 0.14 which indicates the prediction is off from min , and the final value update shows that enhancement is correct. (toward min value)

The function considers 5% of total data as nearby data.

Note: this method works in the range of training data, therefore this function can't enhance results outside of data range as there is no data.

You can find the Python code in GitHub


Format

Here is all you need to know about string formatting. I have summarized the page  https://pyformat.info/  , in fact I just removed all e...