""" 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.
Saturday, May 23, 2015
Python split with examples
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.
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 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.
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.
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]: [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., ] 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'}
Subscribe to:
Posts (Atom)