"""
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]: [, ]
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
More about Split
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.
>> 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)
More about Split
Return a list of the words in the string, usingsepas the delimiter string. Ifmaxsplitis given, at mostmaxsplitsplits are done (thus, the list will have at mostmaxsplit+1elements). Ifmaxsplitis not specified, then there is no limit on the number of splits (all possible splits are made).
Ifsepis given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,'1,,2'.split(',')returns['1', '', '2']). Thesepargument may consist of multiple characters (for example,'1<>2<>3'.split('<>')returns['1', '2', '3']). Splitting an empty string with a specified separator returns[''].
Ifsepis not specified or isNone, 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 aNoneseparator 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
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.
"""
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.
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
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.
Subscribe to:
Posts (Atom)





