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.