Saturday, May 23, 2015

Python split with examples

"""
Rsplit. Usually rsplit() is the same as split.
The only difference occurs when the second argument is specified. 
This limits the number of times a string is separated.

So:
When we specify 3, 
we split off only three times from the right. 
This is the maximum number of splits that occur.
Source:#http://www.dotnetperls.com/split-python
"""
In [1]: s="Obama,President,USA,Ajay,cam,cyber"

In [2]: s.rsplit(",",3)
Out[2]: ['Obama,President,USA', 'Ajay', 'cam', 'cyber']

In [4]: s.split(",",3)
Out[4]: ['Obama', 'President', 'USA', 'Ajay,cam,cyber']

In [5]: s = "foo    bar   foobar foo"

In [7]: s.split(None,2)
Out[7]: ['foo', 'bar', 'foobar foo']

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Thursday, May 7, 2015

Strategy to learn python for a beginner



 Complete the following books

1.Learn python the hard way[website][Download] or Think Python or tutorials point or new circle or cs 101from udacity or codecademy for python.

2.a. Python standard library by example[buy]
At first you don't understand some things,no probs leave  the things you don't understand and move on.You may just want to just read this article
Join  irc channel or create an account on stackoverflow.
But please don't ask any question(for atleast one week) just observe,out of enthusiasm we try ask some stupid question(which might already have a possible duplicate) and get downvoted. So my suggestion is to master the second book (mainly data structures and algorithms).
But you can ask specific question.
I've so and so problem and i tried
this is my following code.
Show them what you have coded,input and expected output. In this way your question is less likely to get downvoted.To get a better score try reading the answers to most frequently asked questions,because mostly the questions repaeat.
Try reading these answers

b. OOP is the most import like ... understanding classes,methods,constructors...
This is the best resource 1.New Circle 2. Mastering OOP

3.If you are intersted in competetive programming i suggest this book .or codeforcers(Hacker rank,Project euler,).By doing the problems here you'll get experience.

4. Python cookbook[This is the best book]
5. Algorithms and Data Structure in python   (i didn't complete this book myself so it's up to you) or buy Think Complexity 
While reading algorithms(if you don't understand for the first time don't panic.Pretend you understood move on.)
Check the following sites(visual-algo ,algo-viz)

With these four books done you'll become a novice to an avergae python programmer.
From here you need to select a specific domain like GUI development,Web development,big data,etc...
Many of them come with frame works
GUI ==> Tkinter,Pyside,PyQt
Web==>Django,flask
Select your domain and master a framework.

There are some earlier posts on this blog for resource you may check them.


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Pyvideos-The best resources of python videos


Once you've learned basic python,this is a great resource
pyvideo
I didn't know how to deploy a django app but there is a video here and that's really helpful.
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Wednesday, May 6, 2015

Understanding list comprehensions with if else

"""
[dosomething if else for ]

Today list comprehensions alone killed most of time.
http://stackoverflow.com/questions/30080047/replacing-letters-in-python-with-a-specific-condition/30080898#30080898

In [35]: meds
Out[35]: ['tuberculin Cap(s)', 'tylenol Cap(s)', 'tramadol 2 Cap(s)']

In [36]: new_meds=[ i.replace(" Cap(s)", " 1 Cap(s)") if any(char.isdigit() for char in i) == False  else i for i in meds]

In [37]: new_meds
Out[37]: ['tuberculin 1 Cap(s)', 'tylenol 1 Cap(s)', 'tramadol 2 Cap(s)']
"""



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Tuesday, May 5, 2015

one vim command a day makes you feel happy

I mostly switch to sublime,after getting frustrated with vim but vim is really cool if you know commands.So i decided i want to post what i've learned today.
#How to delete all lines of file in Vim?
"""
Date:6-5-2015
Solution

    Type gg to move the cursor to the first line of the file, if it is not already there.
    Type dG to delete all the lines.
"""


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Understading Scope of a function in python

Fire up your terminal or IDLE and type all these.

 In python functions create it's own name space or scope.
In the example below we are using two functions to illustrate that .
Each namespace is a different world.The variables defined in one function don't know about the variables defined in another function.
Python has builtins called globals() --> to display global variables.
locals() --> to display local variables.




>>> myvar="Hi i'm global"
>>> def foo():
...     a=1
...     print(locals())
... 

>>> def bar():
...     b=2
...     print(locals())
... 
>>> def my_func():
...     print("hi")
...     name="ajay"
...     place="India"
...     age='you cannot ask'
...     print(locals())
... 
>>> my_func()
hi
{'name': 'ajay', 'age': 'you cannot ask', 'place': 'India'}
>>> foo()
{'a': 1}
>>> bar()
{'b': 2}
>>> globals() #this may slightly vary for you
{'bar': , '__builtins__': , '__name__': '__main__', 'my_func': , '__package__': None, '__doc__': None, 'foo': , 'myvar': "Hi i'm global", '__spec__': None, '__loader__': }



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Sunday, May 3, 2015

Basic usage of heapq in python

"""
Understang heapq
"""

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

# How to find max and min in the list??

In [2]: max(nums)
Out[2]: 42

In [3]: min(nums)
Out[3]: -4
#How to find n maximum  numbers?
#this is not a well written .I'm lazy so is there a pythonic way?
def n_max(n,nums):
 max_list=[]

 if len(nums) == 0:
  return (0)
 elif len(nums) == 1:
  return nums
 elif len(nums) >1:
  for i in range(n):

   max_list.append(max(nums))
   nums.remove(max(nums))

 return max_list,len(max_list)

print n_max(11,nums)

#Using heapq

#The heapq module has two functions— nlargest() and nsmallest() —that do exactly and more efficeint way

In [1]: nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

In [2]: import heapq

In [3]: print (heapq.nlargest(3,nums))
[42, 37, 23]

In [4]: print (heapq.nsmallest(3,nums))
[-4, 1, 2]

In [5]: portfolio =[{'name':"Ajay",'age':24,'sex':'Male'},
   ...:              {'name':"Cam",'age':23,'sex':'Male'},
   ...:              {'name':"Cyber",'age':16,'sex':'Female'}]

In [6]: 

In [6]: youngest=heapq.nsmallest(1,portfolio,key=lambda s: s['age'])

In [7]: youngest
Out[7]: [{'age': 16, 'name': 'Cyber', 'sex': 'Female'}]

In [8]: youngest=heapq.nsmallest(2,portfolio,key=lambda s: s['age'])

In [9]: youngest
Out[9]: 
[{'age': 16, 'name': 'Cyber', 'sex': 'Female'},
 {'age': 23, 'name': 'Cam', 'sex': 'Male'}]

In [10]: eldest=heapq.nlargest(1,portfolio,key=lambda s: s['age'])

In [11]: eldest
Out[11]: [{'age': 24, 'name': 'Ajay', 'sex': 'Male'}]

"""
A heap is a tree-like data structure where the child nodes have a sort-order relationship
with the parents. Binary heaps can be represented using a list or an array organized
so that the children of element N are at positions 2*N+1 and 2*N+2 (for zero-based
indexes). This layout makes it possible to rearrange heaps in place, so it is not necessary
to reallocate as much memory when adding or removing items.
A max-heap ensures that the parent is larger than or equal to both of its children.
A min-heap requires that the parent be less than or equal to its children. Python’s heapq
module implements a min-heap.
Check http://visualgo.net/heap.html(max heap implementation)
minheap --> https://www.cs.usfca.edu/~galles/visualization/Heap.html
http://kanaka.github.io/rbt_cfs/trees.html

check heapify,heappush,heapop from the standard library

Practical use of heapq

http://stackoverflow.com/questions/8627109/what-would-you-use-the-heapq-python-module-for-in-real-life
https://docs.python.org/3/library/heapq.html

"""

#To understand heap start with an empty list

>>> import heapq
>>> l=[1,9,2,4,8,5,6] # (L is llooking like 1)
>>> l=[]
>>> heapq.heappush(l,1)
>>> heapq.heappush(l,10)
>>> heapq.heappush(l,4)
>>> heapq.heappush(l,6)
>>> heapq.heappush(l,8)
>>> l
[1, 6, 4, 10, 8]

>>> heapq.heappop(l)
1
>>> l
[4, 6, 8, 10]
>>> heapq.heappushpop(l,83)
4
>>> l
[6, 10, 8, 83]


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Friday, May 1, 2015

Convert Strings,list of strings into a python dict or dictionary

"""
Strings ==> Dicts

"""

#problem1
#Input: s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" --> a string
#output:  {'muffin' : 'lolz', 'foo' : 'kitty'} --> dictionary

>>> s
"{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> from ast import literal_eval
>>> literal_eval(s)
{'muffin': 'lolz', 'foo': 'kitty'}

>>> s
"{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> import json

>>> json_acceptable_string = s.replace("'", "\"")
>>> d = json.loads(json_acceptable_string)
>>> d
{'muffin': 'lolz', 'foo': 'kitty'}

"""
NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement

"""

#problem:2
#Input: mystring="a=0 b=1 c=3"
#output: {'a': 0, 'b': 1, 'c': 3}

"""
It's easy to convert list into a dict.

"""

In [1]: mystring = "a=0 b=1 c=3"

In [2]: mylist1=mystring.split() #using split for a string generates a list 

In [3]: mylist1
Out[3]: ['a=0', 'b=1', 'c=3']

In [4]: mylist2=[]

In [5]: for i in mylist1: #for every element in list1 i'm caling split at '='
   ...:     mylist2.append(i.split('='))
   ...:     

In [6]: mylist2
Out[6]: [['a', '0'], ['b', '1'], ['c', '3']]

In [7]: dict(mylist2)
Out[7]: {'a': '0', 'b': '1', 'c': '3'} #it worked but values in dictonary are strings not ints

In [8]: mylist2
Out[8]: [['a', '0'], ['b', '1'], ['c', '3']]

#convert the value item into an int  i.e '0'->0, '1'->1,'3'->3  ; mylist2 has 3 lists 
#So for every list in mylist2 i want to change the first element into a int
#mylist2[0][1] is '0'
#mylist2[1][1] is '1'

In [9]: for lists in mylist2: 
   ...:     lists[1]=int(lists[1])
   ...:     

In [10]: mylist2
Out[10]: [['a', 0], ['b', 1], ['c', 3]]


#we can use a single line answer for this

In [1]: mystring = "a=0 b=1 c=3"

In [2]: dict( (n,int(v)) for n,v in (i.split('=') for i in mystring.split() ) )
Out[2]: {'a': 0, 'b': 1, 'c': 3}


#using eval to solve 
#try to avoid using eval.
#eval() interprets a string as code.
>>> a='2*3'
>>> eval(a)
6
mystring = "a=0 b=1 c=3"


In [3]: mydict=eval('dict(%s)'%mystring.replace(' ',','))

In [4]: mydict
Out[4]: {'a': 0, 'b': 1, 'c': 3}

"""
This one took  me a while to understand.

try this 
"""
In [27]: dict(a=0,b=2,c=3)
Out[27]: {'a': 0, 'b': 2, 'c': 3}
#After trying this i came to understand

In [25]: 'dict(%s)' % mystring.replace(' ',',')
Out[25]: 'dict(a=0,b=1,c=3)'

# Invoking eval on the above line gives us desired dictionary





#problem 3
#Input:list_with_strings=["name","Ajay Kumar","age",25,"place","India"]

#Output:{'age': 25, 'name': 'Ajay Kumar', 'place': 'India'} 

In [1]: list_with_strings=["name","Ajay Kumar","age",25,"place","India"]

In [2]: dict(zip(*[iter(list_with_strings)]*2))
Out[2]: {'age': 25, 'name': 'Ajay Kumar', 'place': 'India'}

"""
func(*a) is the same as func(a[0], a[1], a[2], a[3] ... a[n]) if ahad n arguments
* is an argument unpacking
More @ http://stackoverflow.com/questions/287085/what-do-args-and-kwargs-mean/287582#287582
"""
In [37]: list_with_strings=["name","Ajay Kumar","age",25,"place","India"] 

In [38]: l = [iter(list_with_strings)]*2

In [39]: l
Out[39]: [, ]

In [40]: dict(zip(l[0], l[1]))
Out[40]: {'age': 25, 'name': 'Ajay Kumar', 'place': 'India'}


In [41]: def foo(a,b,c,d):
   ....:     print a,b,c,d
   ....:     

In [42]: l=[0,1] 

In [43]: d={"d":3,"c":2}

In [44]: foo(*l,**d) #for arguments we use * and keyword arguments we use **
0 1 2 3

#Easy way to understand this

n [3]: my_iterable=iter(list_with_strings) #iter keyword makes it iterable 

In [4]: dict(zip(my_iterable,my_iterable))
Out[4]: {'age': 25, 'name': 'Ajay Kumar', 'place': 'India'}






Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Thursday, April 30, 2015

Convert strings to tuple in python

#Strings to tuple


>>> myname='cam'
>>> tuple(myname)
('c', 'a', 'm')
>>> (myname,) #did you see the trailing comma after myname, ??
('cam',)

#Problem 1
mylist=["('good', 'buono')", "('afternoon', 'pomeriggo')"]

#my list contains two elements and  they are strings not tuples.

>>> from ast import literal_eval

>>> [literal_eval(i) for i in mylist]

[('good', 'buono'), ('afternoon', 'pomeriggo')]


#problem2

#Input : ['aaa','bbb','ccc']
#output:[('aaa',),('bbb',),('ccc',)]

lst = ['aaa','bbb','ccc']
tpl_lst = [(i,) for i in lst]
>>> tpl_lst
[('aaa',), ('bbb',), ('ccc',)]


#problem 3

# Input : '1/2' ==> it's  a string
#output: (1,2)
>>> my_frac='1/2'
>>> my_frac.split('/')
['1', '2']

>>> my_frac = tuple(map(int, my_frac.split('/')))
>>> my_frac
(1, 2)

#problem 4

#Input: s = "a b c d"
#output1: [(a,a),(b,b),(c,c),(d,d)]
#output2:[(a, b), (b, c), (c, d)]

#Solution for output1

>>> s = "a b c d"
>>> w = s.split()
>>> w
['a', 'b', 'c', 'd']
#python 3.x
>>> list(zip(w,w))
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]

#python 2.7

>>> zip(w,w)
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]

#Solution 2:

#python 3.x
>>> list(zip(w,w[1:]))
[('a', 'b'), ('b', 'c'), ('c', 'd')]

#python 2.7

>>> zip(w,w[1:])
[('a', 'b'), ('b', 'c'), ('c', 'd')] 
"Check one more example from SO" Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Convert string or strings into a list in python

I always wanted a python cheatsheet where by looking could get an idea.Since i'm a novice programmer,i need to look at these snippets so that it will get into longterm memory
>> myname="cam"
>>> list(myname)
['c', 'a', 'm']
>>> myname.split()
['cam']

>>> "cam".split('c') # split at c and eliminate c
['', 'am']
>>> "cam".split('cam')
['', '']

>>> "cacacacacacccaaaa".split('c')  #split or break at c and remove c 
['', 'a', 'a', 'a', 'a', 'a', '', '', 'aaaa']
#observe the fist character it's empty string
# ""+"cacacacacacccaaa" will give us same string "cacacacacacccaaa"


>>> "cacacacacacccaaaa".split('a')
['c', 'c', 'c', 'c', 'c', 'ccc', '', '', '', '']


"""
Problem: I've a text which have a | seperators.
I need to make a list of numbers 

text = '2,4,6,8|10,12,14,16|18,20,22,24' 

Output:

[[2,4,6,8],[10,12,14,16,18],[18,20,22,24]]

"""

>>> list(text)
['2', ',', '4', ',', '6', ',', '8', '|', '1', '0', ',', '1', '2', ',', '1', '4', ',', '1', '6', '|', '1', '8', ',', '2', '0', ',', '2', '2', ',', '2', '4']

>>> text.split()
['2,4,6,8|10,12,14,16|18,20,22,24']

# but it's just one single string and i still see the seperators '|'

 >>> text.split('|')
['2,4,6,8', '10,12,14,16', '18,20,22,24']

"""wow we got rid of '|'
well this is okay but  it is a list of 3 strings 
'2,4,6,8'==>together one string"""


>>> len(text.split('|'))
3



 #we can use a for loop iterate over the list and add each element to a new list

>>> mynewlist=[]
>>> for i in text.split('|'):
...     mynewlist.append(i.split(','))
... 
>>> mynewlist
[['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']]


 
#There's more cleaner way to do it.
#So let's use list comprehension to acheive this.


>>> text = '2,4,6,8|10,12,14,16|18,20,22,24' 
>>> my_data = [x.split(',') for x in text.split('|')]
>>> my_data
[['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']] #but they are still strings

>>> [[int(y) for y in x.split(',')] for x in text.split('|')]
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]


#or alternatively we can use map function
#http://pythonnotesbyajay.blogspot.in/2013/03/imap-and-map-in-python.html
#Simple usage of map (it takes 3 arguments 1.function,2.iterable,3.iterable )

>>> x=[1,2,3]
>>> y=[4,5,6]
>>> map(pow,x,y)

>>> output=list(map(pow,x,y))
>>> output
[1, 32, 729]


>>> text = '2,4,6,8|10,12,14,16|18,20,22,24'
>>> strs1=text.split('|')

>>> [map(int,x.split(',')) for x in strs1] 
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]


#How do you change this string into list 'QH QD JC KD JS' ?

>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']



More about Split
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Palindrome of first characters of strings in a list

I've scored 70/100 for this problem because i've missed few cases like empty list,list with one word(although this is implemented in actual algorthm).There might be some error crept
"""
Problem: Take first letters of a words in a list and check if it is palindrome or not,you can remove as many as letters and see if the word is
palindrome or not

Ex:  

inputlist=["Ajay","IS","ALIEN"]
Solution: 
First letters of words ==> AIA
Check if the word is palindrome or not ;
if word is not a palindrome drop any letter and check if it is a palindrome.
do this till you find a palindrome.

"""

from itertools import *
def PalindromeLengthPuzzle(input1): #==> ['ADAM','EVE','ABRAHAM','ELVIS']
  myList=[]
  for i in range(len(input1)):
   myList.append(input1[i][0]) #==> adding first letters to myList( myList = ['A','E','A','E']

  """
 Concept 1:

 1. How to join elements in a list to a single string? (Most frequently you will come across )
 Ex:1 ===> no space between ('') so you'll get an output :abc
 >>> myList=['a','b','c']
 >>> mystring=''.join(myList)
 >>> mystring
 'abc'
 Ex:2 ==> Space (' ') so you'll get an output : abc
 >>> mystring1=' '.join(myList)
 >>> mystring1
 'a b c'


  """
  mystring=''.join(myList) #==> mystring='AEAE'
  print mystring

  if len(input1) == 0:
   return 0,''
  elif len(input1) ==1:
   return mystring,1
  elif len(input1) == 2:
   if mystring[0:] == mystring[::-1] :
    return mystring,len(mystring)


  elif len(input1)>2:
   for i in reversed(range(len(mystring)+1)):
    #print i

    my_list=[''.join(item) for item in combinations(mystring,i)] # generate different combinations of 'AEAE' into a list
    #print my_list

    for item in my_list:
     #print my_list

     if item[0:] == item[::-1]:

      return len(item),item








input1=["Bharati","Akash","Bharat","BUMM","CAT","BAT","CUT","ATE","BY"]
input2=["Bharati"]
input3=['BOB','BAAB','BAABS']

print PalindromeLengthPuzzle(input1)
print PalindromeLengthPuzzle(input2)
print PalindromeLengthPuzzle([])
print PalindromeLengthPuzzle(input3)
"""
Output:

BABBCBCAB
(7, 'BABBBAB')
B
('B', 1)

(0, '')
BBB
(3, 'BBB')
[Finished in 0.0s]

"""





Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Wednesday, April 29, 2015

Understanding staticmethod classmethod Decorators


I've been using python from a while but and i've came across these terms but didn't find them where to use.I've been learning Java for a while,now suddenly all these python terms started to make a sense.




class Hello(object):
 """Understanding @staticmethod, @classmethod decorators"""

 @staticmethod
 def main(i):
  """ Using @staticmethod decorator.There is no self argument"""
  print(i)
  print("I'm inside main method which has @staticmethod decorator")

 @classmethod
 def func2(self,i):
  """ using @classmethod You need to provide a self argument """
  print(i)
  print("I'm inside func2 method which has @classmethod decorator")

 def func3(self,i):
  print(i)
  print("I'm inside func3 method which has no decorator  so to acess func3 I need to create an instance of Hello class to access the methods of Hello class")
  
Hello.main(1) #didn't create any instanc of Hello class,yet able to access the methods 
Hello.func2(1)
#Hello.func3(1) ==> This will be an error. General way to acess methods is to create an instance of object 
hello_object = Hello() # Created an instance of Hello class
hello_object.func3(100)
hello_object.func2(100)
hello_object.main(100)


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Wednesday, April 15, 2015

Python program that inputs a list of words, separated by white- space, and outputs how many times each word appears in the list

Write a Python program that inputs a list of words, separated by white- space, and outputs how many times each word appears in the list.



import collections

#without using Counter from Collections
def myFunc():
	myinp=input().split()
	mylist=list(set(myinp))
	mycount=[]
	for i in range(len(mylist)):
		mycount.append(myinp.count(mylist[i]))

	mydict=dict(zip(mylist,mycount))
	print (mydict)



#myFunc()

#Use Counter from Colections

def myFunc1():
	myinp=input().split()
	a=collections.Counter(myinp)
	print (dict(a))

myFunc1()
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

How can I tell if a string repeats itself in Python?



 This one is from stackoverflow




I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
[
    '0045662100456621004566210045662100456621',             # '00456621'
    '0072992700729927007299270072992700729927',             # '00729927'
    '001443001443001443001443001443001443001443',           # '001443'
    '037037037037037037037037037037037037037037037',        # '037'
    '047619047619047619047619047619047619047619',           # '047619'
    '002457002457002457002457002457002457002457',           # '002457'
    '001221001221001221001221001221001221001221',           # '001221'
    '001230012300123001230012300123001230012300123',        # '00123'
    '0013947001394700139470013947001394700139470013947',    # '0013947'
    '001001001001001001001001001001001001001001001001001',  # '001'
    '001406469760900140646976090014064697609',              # '0014064697609'
]
are strings which repeat themselves, and
[
    '004608294930875576036866359447',
    '00469483568075117370892018779342723',
    '004739336492890995260663507109',
    '001508295625942684766214177978883861236802413273',
    '007518796992481203',
    '0071942446043165467625899280575539568345323741',
    '0434782608695652173913',
    '0344827586206896551724137931',
    '002481389578163771712158808933',
    '002932551319648093841642228739',
    '0035587188612099644128113879',
    '003484320557491289198606271777',
    '00115074798619102416570771',
]
are examples of ones that do not.
The repeating sections of the strings I'm given can be quite long, and the strings themselves can be 500 or more characters, so looping through each character trying to build a pattern then checking the pattern vs the rest of the string seems awful slow. Multiply that by potentially hundreds of strings and I can't see any intuitive solution.
I've looked into regexes a bit and they seem good for when you know what you're looking for, or at least the length of the pattern you're looking for. Unfortunately, I know neither.



The best answer which makes you say wow

def principal_period(s):
    i = (s+s).find(s, 1, -1)
    return None if i == -1 else s[:i]




Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Monday, April 13, 2015

Django Girls the best resource to learn Django for starters

I thought of learning django back in 2012,but back then it wasn't possible.
I wanted to learn Django downloaded couple of books,checked on quora and reddit.
At the end i've learned
1.Official Documentation is good.
2.Some suggested Test deriven Development using Django.(This is by far best but it takes time.This is the hard way of learning Django but if you were a beginer then  suggest start with django girls)
3.Tango with Django
4.Django-girls(Intutively i could understand but after reading this i got a basic idea of django.From here i would take up TDD using django.)
5.Hellowebapp (Dont know but seems promisng).
There's a sub on reddit

Download Django-girls book


 The above four are upto date(Django v1.7 and v1.8),rest of the tutorials are based on django v1.5.
I started with TDD with Django but it's taking time so i skipped it.Then I tried Tango with django,then official documentation.I skipped them half way.
I completed Django-girls within (1-2hrs).It depends on your pace.You may want to skip some parts like installing app on heroku just work locally.

Basic Skills you may require

1. Basic understanding of HTML and CSS (No probs if you don't know the book will guide you.)
2. Basic python(if,for loops,functions and classs).
3. Regular Expressions(this is not a requirement) .




I don't have a proper internet connection so relying on pdfs . I want to learn quick,atleast make my own blog and then improvise writing other apps.So i tried Django girls.It worked fine.
There is a sub on reddit






Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Thursday, April 2, 2015

Renaming and Moving files ,directories in ubuntu

 
 """
Moving/Renaming Files and Directories


Commands

mv       Move or rename files & Directories.

mv source destination

mv -i source destination



To get better understanding.
Create two files and two directories on your Desktop.

files --file1 file2

directories -- blog-promotion backup 

File Renaming

cam@hack3r:~/Desktop$ mv file1 file2

It renamed file1 --> file2 but there's file with same name so it is deleted.


A File moving into a Directory.

cam@hack3r:~/Desktop$ mv file2 backup

This command moves file2 into backup Directory.


A Directory being moved into a Directory

cam@hack3r:~/Desktop$ mv backup blog-promotion

This moves backup folder into blog-promotion.Since both are in Desktop directory we ddn't specify any path.

"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Copying files and directories in ubuntu

"""
Copying Files and Directories


Commands


cp file1 file2             Copy contents of file1 to file2   

cp file1 file2 file3 dir1  Copy file1,file2,file3 to dir1

cp -r dir1 dir2            copy dir1 contents to dir2.

You can use cp -i file1 file2 for interactive mode.
For copying directories cp -r is a must.

Explaining Screenshot.

cd Desktop

Changes my directory to Desktop.

nano file1

creates a file called file1.You enter some info.Once you are done press (ctrl+o) followed by hitting enter and lastly
ctrl+x to exit

To create a file named file1
[nano file1 --> fill some info --> ctrl+0 -->hit enter-->ctrl+x ]

cat file1

It displays the contents of file1

cp file1 file2

It creates a new file called file2 in the same directory with the contents of file1.

[* Here we didn't give any path,we just gave two file names.what if we want to copy file1 to another directory.
In that case use full paths. 
cp source-file destinatio-file
cp /home/cam/Desktop/file1 /home/cam/file2 
The above command copies file1 which is on my Desktop to my cam diectory which is in home ]


mkdir blog-promotion

It creates a new directory called blog-promotion on my Desktop.

cp file1 file2 blog-promotion

copies both file1 and file2 to a folder or directory called blog-promotion.

ls blog-promotion

shows all files and directories inside blog-promotion.

cd .. 

Takes me to previous directory.

skipping to end.


cp -i 

Before replacing a file which already exists it will ask you...that's called interactive


"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Removing Files and directories in ubuntu

"""
Removing Files


Commands


rm file    Removes a file

rm -r dir    Removes a dir(directory) and 
     all files in it.

rm -f file    Force removal.




* nano filename (opens a file or creates if there is no such file)
In this post we have created two files in target directory
1.this-week-target
2.blog-taarget (Spelling mistake bare with me)
"""

"""

Explaining the screenshot (screenshot @ bottom)

As I opened my terminal I'm at my home directory.

cd Desktop 

changed my directory to Desktop(it's D )

mkdir target

It creates a new directory called target

cd target

It changes my current directory to target.So now i'm in the target directory.

nano this-week-target

It creates a file called this-week-target in target folder.

So you need to type some info.Now to save the file you need to press (ctrl+o) and hit enter.
Now press ctrl+x to get back to normal terminal.

To create a file [nano filename --> fill the file with some info --> ctrl+o --> hit enter--->ctrl+x]
nano blog-taarget creates another file

now ls command shows there are two files in target directory.

cat blog-taarget 

The above command shows the content of the file..

rm blog-taarget removes the file

now you can give ls and see there is only one file in target directory.

Now I want to remove the target directory also.Since target directory is on Desktop,I'll change my directory to Desktop.

cd .. (cd followed by two dots)

The above command takes me to the previous directory.

Now to remove the target directory and all files inside it we use

rm -r target

rm -r means remove recursively...
So be careful while using rm -r.
now ls on Desktop you will not see the target directory.




"""

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Tuesday, March 31, 2015

Hands on Ruby Numbers and Arrays

#Ruby can handle both integars and floating points
twenty=20
one_point_two=1.2
 #we can add this putting a # before a variable prints 
puts "twenty + one_point_two = #{twenty+one_point_two}"
puts 4+4.0
#puts 4+"Ajay"  #   <=== Try this you will get an error
=begin 
you can use an underscore as a thousands divider when writing long numbers; Ruby ignores the underscore. 
This makes it easy to read large numbers:
=end
billion=1_000_000_000 
puts billion
#creating an Array
first_array = []   #empty array
second_array = Array.new #empty array
third_array =[1,2,3]
puts third_array
first_array.push("Ajay")
second_array[0]="Different ways of adding an object to array"
puts first_array
puts second_array
fourth_array = Array.new(20) #created an array of size 20
puts fourth_array.size
puts fourth_array.length
names = Array.new(4, "Ajay")  #names has 4 objects
puts "#{names}"
puts names.length

 


 
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Hands on ruby:Install,run,hello world

1.Install from Terminal
 sudo apt-get install ruby2.0 ruby2.0-dev 
2.How to run a program? There are two ways to do it.
 a.Interactive ruby shell Open your terminal(Ctrl+alt+t)
Type irb and hit enter.
Voila you can start typing your commands here
 b.Type all your commands and save it as filename.rb
 open your terminal ruby filename.rb
3.Every thing in ruby is an object including numbers
puts "Hello World"

puts "puts is like \n 1.printf in C \n 2. cin in C++ \n 3.System.out.print in java \n4.print in Python\n"

puts " # is a Single line comment"
=begin

This is multiline comment 
Every thing in between =begin and =end
is a multi line comment 

=end
languagge = "Ruby" #variable languagge has a value Ruby

puts "Hello #{languagge}" 

puts 4  #Number is an object in ruby
puts 4+4
puts 4.class
#puts 4.methods # Displays all methods that you can call on a number
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Monday, March 30, 2015

Finding Patterns Multiplication of 2 digit number part 2

for i in range(25,100,10):


 print(str(i)+"*"+str(i)+"=",i*i)

 for j in range(10,80,10):
  print(str(i)+"*"+str(i+j)+"=",i*(i+j))
 print""

"""
Results


There is a sequence observe the first digits they are (6,8,11,13,16,18...)(2,3,2,3,2,3...)(6+2,8+3,11+2,13+3...)
I know 25*25 = 625 (25*25=(2*3)25)==>625
To get 25*35 all i need to do do is add 2 to 6 = 8
and change 25 to 75
so final answer would be 875

('25*25=', 625)
('25*35=', 875)
('25*45=', 1125)
('25*55=', 1375)
('25*65=', 1625)
('25*75=', 1875)
('25*85=', 2125)
('25*95=', 2375)


There is a sequence (12,12+3,15+4,19+3,22+4,26+3).
Addition of (3,4,3,4,3,4)...


('35*35=', 1225)
('35*45=', 1575)
('35*55=', 1925)
('35*65=', 2275)
('35*75=', 2625)
('35*85=', 2975)
('35*95=', 3325)
('35*105=', 3675)

Addition of (4,5,4,5,4,5)...

('45*45=', 2025)
('45*55=', 2475)
('45*65=', 2925)
('45*75=', 3375)
('45*85=', 3825)
('45*95=', 4275)
('45*105=', 4725)
('45*115=', 5175)

Addition of (5,6,5,6,5,6)

('55*55=', 3025)
('55*65=', 3575)
('55*75=', 4125)
('55*85=', 4675)
('55*95=', 5225)
('55*105=', 5775)
('55*115=', 6325)
('55*125=', 6875)

('65*65=', 4225)
('65*75=', 4875)
('65*85=', 5525)
('65*95=', 6175)
('65*105=', 6825)
('65*115=', 7475)
('65*125=', 8125)
('65*135=', 8775)

('75*75=', 5625)
('75*85=', 6375)
('75*95=', 7125)
('75*105=', 7875)
('75*115=', 8625)
('75*125=', 9375)
('75*135=', 10125)
('75*145=', 10875)

('85*85=', 7225)
('85*95=', 8075)
('85*105=', 8925)
('85*115=', 9775)
('85*125=', 10625)
('85*135=', 11475)
('85*145=', 12325)
('85*155=', 13175)

('95*95=', 9025)
('95*105=', 9975)
('95*115=', 10925)
('95*125=', 11875)
('95*135=', 12825)
('95*145=', 13775)
('95*155=', 14725)
('95*165

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Sunday, March 29, 2015

Finding Patterns two digit multiplication part 1


21 * 21

step 1 

20 * 20 =400

step 2

20*1
1*20
-----
40

Step 3

1*1


step 4

441

Base Method

base is 2

21 *21 = 2*(21+1)|(1*1) =44|1=441
21*22 =2*(21+2)|2=462
21*23=2*(24)6 = 486
21*24=2*(25)|4=504

visualise

21*26

considering base 20

21   1(1 away from base 20)

26   6(6 away from base 20)

----------

21+6|1*6

21+6 or 26+1 followed by 1*6

27|6

27*2|6

546


So within 20 or 30 we can do these caluclations easily

Base 30 

33*34

37*3|12

111|12

1122

or 
33*34

I know 35*35=1225

(35-2)*(35-1)

1227-105

1122


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Finding Patterns Multiplication by 19 the harder way



for i in range(1,30):
 print (str(19)+"*"+str(i)+"=",19*i)
 print "difference=",((19*(i+1))/10 - (19*i)/10)
 print("=======================================")

"""
Multiplication by 19 ==> The harder way

Many would suggest ==> 1| 3|5| 7|9|11| 13| 15| 17|19  ==> odd numbers(1,3,5..)
                       9| 8|7| 6|5|4 | 3 | 2 | 1 | 0  ==> numbers from 9,8,7....
         ------------------------------
         19,38,57,76.......


 It's easy but you should write it down

This is for kids ==> Rather than by heart just know that
19*n=(2*n)-1 ==> This will be first digit 

From the observations

19*36=??
Once you know 19 table it's not a big deal but sometime for starters it's a mess to remember numbers.

I assume you know 2 table;i assume you know compliment of a number; 
for compliment pairs ==> (1,9),(2,8),(3,7),(4,6),(5,5),(6,4),(7,3),(8,2),(9,1)

Ex : 19* x = (2x-1)[compliment of x]

19*36==> (2*3 - 1)7 [compliment of 3 is 7] and (2*6 -1)4 [compliment of 6 is 4]==> 57 114 ==> 11 carry over ==> 57+11 =68==>684



"""



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Never ever mess with compizconfig setting manager


I had a very bad experience,when i messed up with CCSM. 

Compiz /kɒmpɪz/ is a compositing window manager for the X Window System, using 3D graphics hardware to create fast compositing desktop effects for window management. Effects, such as a minimization animation or a cube workspace, are implemented as loadable plugins.

 What i did is

Ctrl+alt+f2

Enter your login and password.

rm -r ~/.config  
rm -r ~/.compiz  
sudo restart lightdm 

 This worked for me.But there is an alternative method which didn't work for me.

Don't get too much lost in the looks of ubuntu.I regret when everything on system started to behave weired.So you can have conky themes..but if you are person who want to show off install the other ubuntu based os like elementary os.
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Grub Rescue



 In grub you will see a prompt like this.

grub and grub rescue has slight variations in commands.If you have grub-rescue shell,skip to the end.

grub>

grub> set pager=1

no space between = and 1;it invokes pager for large command outputs.

grub> ls
(hd0) (hd0,msdos2) (hd0,msdos1)

The ls commands shows all partitions.This may vary from computer to computer.
But you will see similar listing of partitions

grub> ls (hd0,1)/


lost+found/ bin/ boot/ cdrom/ dev/ etc/ home/  lib/
lib64/ media/ mnt/ opt/ proc/ root/ run/ sbin/
srv/ sys/ tmp/ usr/ var/ vmlinuz vmlinuz.old
initrd.img initrd.img.old

ls on every partition till you find an output like this.This is the root file system.

grub> cat (hd0,1)/etc/issue
Ubuntu 14.04 LTS \n \l

Use cat to read etc file to dermine the linux if you have multiple linuxes.


Booting From grub>

if root file system is on (hd0,1) and vmlinuz-3.13.0-29-generic(The third line sets the initrd file, which must be the same version number as the kernel.).
And if you have (hd0,1) then root=/dev/sda1;
If you have hd0,1 = /dev/sda1. hd1,1 = /dev/sdb1. hd3,2 = /dev/sdd2.


grub> set root=(hd0,1)
grub> linux /boot/vmlinuz-3.13.0-29-generic root=/dev/sda1
grub> initrd /boot/initrd.img-3.13.0-29-generic
grub> boot


If this didn't work then,try these.

grub> set root=(hd0,1)
grub> linux /vmlinuz root=/dev/sda1
grub> initrd /initrd.img
grub> boot


But if you are on grub rescue then commands vary

grub rescue> set prefix=(hd0,1)/boot/grub
grub rescue> set root=(hd0,1)
grub rescue> insmod normal
grub rescue> normal
grub rescue> insmod linux
grub rescue> linux /boot/vmlinuz-3.13.0-29-generic root=/dev/sda1
grub rescue> initrd /boot/initrd.img-3.13.0-29-generic
grub rescue> boot



Making Permanent Repairs

When you have successfully booted your system, run these commands to fix GRUB permanently:

Caution: Third Line from bottom grub-install /dev/sda.Don't use sda1 or anyother number after it.you
may use sdb but don't include any number


# update-grub
Generating grub configuration file ...
Found background: /usr/share/images/grub/Apollo_17_The_Last_Moon_Shot_Edit1.tga
Found background image: /usr/share/images/grub/Apollo_17_The_Last_Moon_Shot_Edit1.tga
Found linux image: /boot/vmlinuz-3.13.0-29-generic
Found initrd image: /boot/initrd.img-3.13.0-29-generic
Found linux image: /boot/vmlinuz-3.13.0-27-generic
Found initrd image: /boot/initrd.img-3.13.0-27-generic
Found linux image: /boot/vmlinuz-3.13.0-24-generic
Found initrd image: /boot/initrd.img-3.13.0-24-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
done
# grub-install /dev/sda
Installing for i386-pc platform.
Installation finished. No error reported.










Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Saturday, March 28, 2015

From Noob to ubuntu pro terminal commands


Source

The Ubuntu Terminal is very complex and useful tool that all Linux distributions use.
The terminal is more then often a huge barrier for a new Linux user and may be keeping them from effectively using the Linux system.
So many users have been using point and click methods of desktop navigation since MS-DOS. Typing text into a command window can be a bit overwhelming for today’s average user but it shouldn’t be.
Some of the advantages of using the command-line Terminal to accomplish tasks are great.
The speed of using the terminal is a fraction of time that it takes to accomplish the same task graphically.
Once you’ve opened the Terminal with your first click you can type and execute commands faster.




Using Terminal – Ubuntu


Lets get started, there are two ways to get to the terminal one you can open the Dash Home and search for “Terminal” to open it. or you can simply press (CTRL+ALT+T) at the same time and a terminal will pop up for you.
Here is what the Terminal looks like.
cam@h@ck3r:~$
 
 
 
 
 
 
Now that you know how to open the terminal here are a few basic commands that will help you on your way to becoming a better Linux user, NOTE: be careful what you do here.

Managing Privileges & Rights to Files and Directories

» chmod — Change Mode
» su — Switch User
» sudo — run command as root
» sudo -r — open a root shell as user
» sudo -r -u user — open a shell as user
» sudo -k — forget sudo passwords
» gksudo — visual sudo dialog (GNOME)
» kdesudo — visual sudo dialog (KDE)
» sudo visudo — edit /etc/sudoers
» gksudo nautilus — root file manager (GNOME)
» dkesudo konqueror — root file manager (KDE)

Movement In The directory

» cd — Change Directory
» pwd — Print Working Directory

Managing Files and Text

» cp — Copy
» ls — List
» mkdir – Make Directory
» mv — Move
» rm — Remove
» grep — Search for Text Strings
» head — Display Start of File
» less — Display Part of File
» more — Display Part of File
» tail — View the End of a File

Managing the Display

» sudo /etc/init.d/gdm restart — restart X and return to login (GNOME)
» sudo /etc/init.d/kdm restart — restart X and return to login (KDE)
» sudo dexconf — reset xorg.conf configuration
» CTRL+ALT+BKSP — restart X display if froxen
» CTRL+ALT+FN — switch to tty N
» CTRL+ALT+F7 — switch back to X display

Managing Packages

» apt-get update — refresh abailable updates
» apt-get upgrade — upgrade all packages
» apt-get dist-upgrade — upgrade with package replacements; upgrade Ubuntu Version
» apt-get install pkgname — install package by name
» apt-get purge pkgname — uninstall package by name
» apt-get autoremove — remove obsolete packages
» apt-get -f install — try to fix broken packages
» dpkg –configure -a — try to fix broken packages
» dpkg -i pkg.deb — install file pkg.deb

Special Packages

» ubuntu-desktop — standard Ubuntu environment
» kubuntu-desktop — KDE desktop
» xubuntu-desktop — XFCE desktop
» ubuntu-minimal — core Ubuntu utilities
» ubuntu-standard — standard Ubuntu utilities
» ubuntu-restricted-extras — non-free, but useful
» kubuntu-restricted-extras — KDE non-free, but useful
» xubuntu-restricted-extras — XFCE non-free, but useful
» build-essential — packages used to compile programs
» linux-image-generic — latest generic kernel image
» linux-headers-generic — latest build headers

Managing System Services

» start service — start job service (Upstart)
» stop service — stop job service (Upstart)
» status service — check if service is running (Upstart)
» /etc/init.d/service start — start service (SysV)
» /etc/init.d/service stop — stop service (SysV)
» /etc/init.d/service status — check service (SysV)
» /etc/init.d/service restart — restart service (SysV)
» runlevel — get current runlevel

Managing System and Program Information

» cal — Calendar
» date — Date

Troubleshooting

» fsck — File System Check

System

while holding down ALT and PRINTSCRN type this command with about 1 second between each letter.
» REISUB — Your system will reboot
» lsb-release -a — get Ubuntu version
» uname -r — get kernel version
» uname -a — get all kernel information

Managing Network Connections

» chkconfig — Check Activated Services
» ping — Test Network Connections
» ftp — file Transfer Protocol
» host — Check IP of Domain
» ifconfig — show network information
» iwconfig — show wireless incormation
» sudo iwlist scan — scan for wireless networks
» ifup eth0 — bring interface eth0 online
» ifdown eth0 — disable eth0 interface
» netstat — Display Routing Table
» route — Set Routes
» telnet — Connect to telnet
» traceroute — Display Route

Managing A Firewall

» ufw enable — turn on firewall
» ufw disable — turn off firewall
» ufw default allow — allow all connections by default
» ufw default deny — drop all connections by default
» ufw status — cyrrebt status and rules
» ufw allow port — allow traffic on port
» ufw deny port — block port
» ufw deny from ip — bkicj ip address

Manage Drives and Formats

» mount — Mount a Drive
» umount — Unmount Drive
» fdisk — Format Disk
» dd — Dupliate Disk
» df — Disk Free Space

Managing Users and Groups

» passwd — Create Password
» groupadd — Add a Group
» groupmod — Modify a Group
» chgrp — Change Group
» groupdel — Delete Group

Applications

» nautilus — file manager (GNOME)
» dolphin — file manager (KDE)
» konqueror — web browser (KDE)
» kate — text editor (KDE)
» gedit — text editor (GNOME)

Note: you can get more information about a command by using ‘man’ followed by the command you need the info about. This will give you information about the ‘grep’ command
$ man grep




Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Environmental variable in ubutnu mycat implementation


"""

.   This directory or current directory

..   The parent directory

cd -        Change to previous directory

Usage: cd .
cd ..
There's output from my computer at the end of this post.

To display last working directory

echo $OLDPWD

Demo:

cam@hack3r:~$ pwd
/home/cam
cam@hack3r:~$ cd /var/tmp
cam@hack3r:/var/tmp$ pwd
/var/tmp
cam@hack3r:/var/tmp$ echo $OLDPWD
/home/cam
cam@hack3r:/var/tmp$ cd -
/home/cam
cam@hack3r:~$ pwd
/home/cam
cam@hack3r:~$ 


How to implement your version of cat

question:why do i need to implement another cat version?
Ans: If you install java jdk or django..you would know.
If you don't add into environmental path,then you can't run that program from other directories


cam@hack3r:~$ which cat
/bin/cat
cam@hack3r:~$ 

That executable is at /bin/cat
Click on computer browse through bin folder and you'll find cat(a diamond shaped file)
copy and paste it on Desktop;now rename it to mycat
================================================================================================

cam@hack3r:~/Desktop$ ls
1  1~  2  2~  D  msf_install.sh~  mycat  trytac.txt  Untitled Document~



cam@hack3r:~/Desktop$ mycat 1
No command 'mycat' found, did you mean:
 Command 'mmcat' from package 'sleuthkit' (universe)
 Command 'mlcat' from package 'svtools' (multiverse)
 Command 'mscat' from package 'libpwiz-tools' (universe)
 Command 'mcat' from package 'mtools' (main)
mycat: command not found


cam@hack3r:~/Desktop$ ./mycat 1
hi i'm in 1
i'm last line
cam@hack3r:~/Desktop$ 


===================================================================================================



cam@hack3r:~$ pwd
/home/cam
cam@hack3r:~$ cd /
cam@hack3r:/$ pwd
/
cam@hack3r:/$ cd /home/cam/Desktop/D
cam@hack3r:~/Desktop/D$ pwd
/home/cam/Desktop/D
cam@hack3r:~/Desktop/D$ cd .
cam@hack3r:~/Desktop/D$ cd ..
cam@hack3r:~/Desktop$ 

"""




Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

MAN Command in ubuntu explained

"""
man command revisited

man ls 

it displays huge output...
You need to hit enter to move down...but it does move only 1 line...
you use space,it displays page by page rather line by line.
use g to goto top of the page
use [shift+g] to move to down of the page.
q to quit

Environmental Variables == Storage location that has name and value.


==>Mostly uppercase names


PATH is one of the environmental variables.

echo $PATH (we have to use $ sign before the variable)

Output

cam@hack3r:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/cam/bin:/usr/local/java/jdk1.8.0_40/bin


This will not be same for you;

they are different paths separated by ':'

Long back I've installed oracle java jdk and added to environmental variables.It's showing the path of jdk.

Question:
Why are there so many paths??

If you type a command then it is first searched in all the paths starting from /usr/local/sbin (this is for my laptop).
If the command typed by you is not in the path then it will display command not found.

which command 

You might want to know in "which" path does ls reside.you can find that by using wich command

which ls

cam@hack3r:~$ which ls
/bin/ls
cam@hack3r:~$ which man
/usr/bin/man

Note: Which doesn't work for builtins;so don't try it on cd












"""







Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

what exactly is a Shell in ubuntu or Linux

 """
shell ==>
1.The default interface to linux
2. The program that accepts your commands and execute those commands
3. Also called commandline interpreter

To acess it on ubuntu desktop/laptop(ctrl+alt+t)
when shell(Terminal emulator application) is opened it shows you prompt.Prompt waits for you to type something in it.
(type whoami)


question: Why use a CLI when we have graphical interdace?
If you want to acess some linux server ,most server distributions doesn't include GUI.
There will be many tedious tasks like renaming a 1000 files....
So in GUI you have to right click and rename,but if you get familiar with commandline you can do it with a command..


Normal VS root

A prompt  will typically look like
[username@computername ~]$
But if you want to have more privelages then you need to change to root prompt.
[root@computername:~]#
To change to root prompt you have to type
An Example from my laptop

cam@hack3r:~$ sudo su
[sudo] password for cam:
root@hack3r:/home/cam#

Observe there is a different symbol for root at the end(#)

Question:
Now in the last post we've discussed a root (directory),mother of all directories.Is that root is same is this root prompt??
No..That is a directory.This root is an account,like super account.

Root,The Superman account
It's like Administrator account in windows.
I've an account called cam on my laptop..
cam<root
for that matter any account on my ubuntu have less privelages than root.


Question:
Why is there a root account when i can access it with a simple command.why can't my user account have all privelages?
Answer:
Simple,In most linux servers there will be multiple user with different tasks...
Only system admins have access to root.You might have seen in many movies people trying to access root.


Tilde(~) Expansion

wait i've seen this somewhere??
Yes it's on your prompt and it is called Tilde

~cam = /home/cam
~root=/root
~ftp = /srv/ftp

Try out these:

cam@hack3r:~$ sudo su
[sudo] password for cam:
root@hack3r:/home/cam# pwd
/home/cam
root@hack3r:/home/cam# cd ~
root@hack3r:~# pwd
/root
root@hack3r:~# cd ~cam
root@hack3r:/home/cam# pwd
/home/cam
root@hack3r:/home/cam# exit
exit
cam@hack3r:~$



Take out from this post



===========                        ==========
command                          Action
===========                        ==========

1.pwd                             displays present working directory

2.cd                             Change directory[you cannot type any directory.You've type the exact path]

3.sudo su                         To access root account from terminal

4.exit                             To exit from root account to normal account(Use root account carefully..)

5.Clear                            Clears the terminal application















 
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Basic Ubuntu/linux Commands


"""
Linux commands are case sensitive(capital letters are different from small letters)

==============        ==============
   Command            Action
 =============        ==============

 1. ls           lists directories and files

 2. cd           changes current directory

 3. cat          concatenates(add) and displays files

 4. echo          Displays arguments to the screen(print)

 5. man          Displays the manual.




 Ex 1:

 ls name_of_the_directory  
 note:if you have spaces in the name of your folder,you've to use "folder name"

 Ex:2

 ls "name of the directory with spaces"
 Shows all the files and directories inside the directory on which ls is performed


Ex:3

cd directory 

this can be bit confusing at first.Every directory is in some hierarchy.you cannot jump from one path to other..
Check the screenshot.

use pwd to know where you are.
Your prompt will start at /home/username
On my Desktop you can see there is only one directory D.
Inside D there are many directories.
To access my directories in D i've to use this commands.
cd Desktop/java
but for you to access usr directory which is in root directory you have to use this

cd /usr


Ex:4

echo My name is Ajay

Displays the line on terminal

echo $PATH 

Output

/usr/local/sbin:/usr/local/bin:


This may vary from user to user


Ex:

man cd 

man man (funny)

displays the documentation page of cd

well i know command cd so i can type man cd.what if i don't know which command to search for but i know just a word.
I want to edit a file.so i'll search a term edit rather a command.

doing vague search on man

man -k search_term



Output:

cam@hack3r:~/Desktop$ man -k edit
atobm (1)            - bitmap editor and converter utilities for the X Window...
bitmap (1)           - bitmap editor and converter utilities for the X Window...
bmtoa (1)            - bitmap editor and converter utilities for the X Window...
dconf-editor (1)     - Graphical editor for dconf
desktop-file-edit (1) - Installation and edition of desktop files
desktop-file-install (1) - Installation and edition of desktop files
djvused (1)          - Multi-purpose DjVu document editor.
ed (1)               - line-oriented text editor
..........      ....................
........     ...................
..........      ...................
Many more editors displayed


*** Extra
There is a command called tac reverse of cat command.
Can you guess what it does??
cat displays contents of file,so tac should display contents of file in reverse order[last line first;first line last].

nano is a tex editor that can be accessed from terminal by typing nano

cam@hack3r:~/Desktop$ nano trytac.txt     ==>check how to use nano
cam@hack3r:~/Desktop$ tac trytac.text      |
             |
i'm in last lines                          |
i'm in 2                                   |
i'm in 1                                   |
cam@hack3r:~/Desktop$                      |
                                           |
how to write and save in nano:    <=========

nano filename
A text editor will open in terminal don't panic.
type some lines hit enter...
now to save (ctrl+o) but now the cursor blinks after trytac.txt press enter.
Now you need to press (ctrl+x) to exit out of the editor







"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Directories structure in Ubuntu/Linux

Check Images Some images are taken from Linuxtrainingacademy.com video tutorials


"""
 /   "Root",the top of the file system

 /bin  Binaries and other executable programs

 /etc  System Configuration files

 /home      Home directories,if you have multiple users then you have different directories for different people


 /opt   Optional or third pirty software
 Ex:The editor i'm using is sublime text 3,which donot come bundled with ubuntu,so some of the third party
 softwares gets installed at /opt

 /tmp  Temporary space,typically cleared on reboot

 /usr   User related programs

 There will be sub directories inside these directories

 /var  Variable data like log files



Other directories

/boot  Files need to boot the operating system

/cdrom  Mount point for CD-ROMS


/dev  Device files,typically controled by the operating system and sys admins

/media  Mount removable devices

/mnt(used to mount external file systems),/proc(provides info about running process),/srv(contains data which is served by the system)




What to do with the info??

Just check these directories with ls -al command,see what files are in there...

just get an idea,don't panic....

=================================================================================================

The content below is optional.... You need not get into details
=================================================================================================

Application Data Structure

If you are from windows you would know all softwares would install @ 
C:\\Program files\software
or 
C:\\Program Files(x86)\software ==> For a 32 bit
C:\\Program Files (x64)==> for a 64 bit
or 
at custom location

Similarly 

Some external softwares in ubuntu get installed at

1. /usr/local/software

Inside the software you will have other directories (bin,etc,lib,log)

some install at

2. /opt/software

Inside the software you will have other directories (bin,etc,lib,log)



3. Google products get installed at
/opt/google
/opt/google/chrome
/opt/google/earth


There are bunch of other ways that programs get installed



"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Wednesday, March 25, 2015

Quine -Self reproducing code


a = ['print "a =", a', 'for s in a: print s']
print "a =", a
for s in a: print s
If you give input it prints the input as output Check out the rest



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Patterns-Finding squares in the hard way


The methods 1-5 are available in most aptitude books.


Basic Assumptions:

1.You know how to caluclate squares ending with number 5

Many of us know how to caluclate square of numbers ending in 5

Ex: x5*x5=(x*x+1) 25

1. 45*45 = 4*(4+1)  25 = 2025
2. 75*75=7*8  25=5625
3. 85*85 = 8*9 25=7225


2.You know how to caluclate squares of numbers near to 100. 

Ex1:
102 * 102 = 10404

Number           By how much it is away from 100

102                          +2                            Line 1
102                          +2                            Line 2

-------                          -----
                                  04(2*2) ==>last two digits

Take 102 from first line and add 2 from 2nd line(cross)
102+2=104 ==> First first 3 digits
final answer: 10404

Ex:2

112*112

Number           By how much it is away from 100

112                          +12                            Line 1
112                          +12                            Line 2

-------                          -----
                                 144(12*12) ==>last two digits
       

Take 112 from first line and add 12 from 2nd line(cross)
112+12=124 ==> First first 3 digits
final answer:12 (4+1)44 ==> 12544



3.You know how to caluclate squares of numbers from 31-50

47*47=??

  • 47 = 50-3
  • (-3)*(-3) = 09 ==> Last two digits
  •  for first two digits  ==>[25 is used as standard]
  •  So use 25-3 = 22
  • final answer is 2209

4.You know how to caluclate squares of numbers from 51-80

64*64 =??

  • 64 = 50+14 (for 66 write as 50+16)
  • 14*14=196 take 96 for last two digits
  • First two digits ==> 25+14+1(this 1 is from 196)  = 40
    [25 is used as standard]
  • final answer 4096

5. You know how to caluclate squares of numbers from 81-100

 88*88=??

  • 88=100-12
  • Last two digits: (-12)*(-12)=144 ==>44(1 carried)
  • First two digits:88-12+1=77
  • final answer = 7744


The above methods 4 and 5 involves two steps.If you can remember some squares by heart then Instead of two steps we can acheive in one step.The above methods are easy,recommended.The methods below are for mnemonic guys.
So for academic purposes use the above methods (4,5)
 1,2 methods are common and the only easy methods.



I've seen some aptitude books,finding squares,it's fine but i want to find out a hard way.
 I was in my class way back in  2012 in mining lecture.I wanted to play with numbers .So after many caluclations i thought i found a pattern.But i didn't go beyond some huge numbers.Just confined to 3 digit caluclations.

This is a good method to find squares upto 100.You can extend upto 200 though.





 for i in range(10,127):

    print (str(i)+"*"+str(i)+"=",i*i)

    print(((i*i)/100)%10)

    print "difference=",(((i+1)*(i+1))/100 - (i*i)/100)

    print("=======================================")



This piece of got bought to me to the above conclusions


"""
Values to Memorise

base             Number             Square                 Squares you can find

4                 17                289                        [17 to 23] (base for these numbers is 4)


6                 27                 729                        [27-33] (base for these numbers is 6)

8                 37                 1369                    [37-43] (base for these numbers is 8)

10                 47                 2209                    [47-53] (base for these numbers is 10)

12                 57                 3249                    [57-63] (base for these numbers is 12)

14                 67                 4489                    [67-73] (base for these numbers is 14)

16                 77                 5929                    [77-83] (base for these numbers is 16)

18                 87                 7569                    [87-93] (base for these numbers is 18)

"""

"""
45*45 =(4*5)(5*5) = 2025 i guess everyone know for numbers ending

Type 3 Example-1




Type 2 Example-1

31*31=?

base of 31 is 6

first two digits

Now I know 30*30=900;i will take first two digits 90
31 is one number away from 30;So i need to add 6 to first two digits;
90+6=96

last digit
31*31 = 1

final answer
961





Type 1 Example-1

28*28 =

first two digits

I know 27*27 = 729,it's base is 6;Now to get the answer i will take 72 from 729 and add 6 to it
72+6=78 ==> first two digits

last digit
8*8=4(last digit)

final answer
784




PS:Post incomplete...will update in time

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.