Complex Problems which can be solved in a line or two using python

   

1.Removing duplicate elements from list or array

       Example:
           input [1,1,1,2,2,3,4,5,6,6,1]
          output  [1, 2, 3, 4, 5, 6]

we can convert the given list into set which will remove its duplicate elements and then again convert it back to the list.
>>> a=[1,1,1,2,2,3,4,5,6,6,1]
>>> list(set(a))
[1, 2, 3, 4, 5, 6]

     2.Using filter function to solve complex problem like extracting even numbers from list or a number greater than some number.

 We can use the filter method to to solve above problem.
The filter() method filters the given sequence with the help of a function that tests each element         in the sequence to be true or not.

Extracting numbers greater than another number such as 2

Example
Input:[1,2,3,4]
Output:[3,4]
>>> n=[1,2,3,4]
>>> print (list(filter(lambda x: x > 2, n)))
[3,4]

Extracting even numbers from a list

Example:
Input:[0,1,2,3,5,8,13]
Output:[0,2,8]
>>> n=[0,1,2,3,5,8,13]
>>> print (list(filter(lambda n: n % 2, seq) ))
    [0,2,8]

    3.Taking Transpose of a Matrix(Inverting it would be a dream)

Example:
Input:[[1,2,3],[4,5,6],[7,8,9]]
Output:[[1, 4, 7], [2, 5, 8], [3, 6, 9]] 

>>> n=[[1,2,3],[4,5,6],[7,8,9]]
>>> print ([list(i) for i in zip(*a)])
    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

4.Common Strings from two lists

>>> P = {'Ann','Joe','Jill','Tim'}
>>> R= {'Ann','Vik','Nathan','Zack'}
>>> P & R
    {'Ann'}

5.Reading lines as list from files

>>> lines = [line.strip() for line in open('foo.txt')]

5. Some other common but important problems

Reversing a string

>>> n="itspythonand"
>>> n[::-1]
    andnothypsti

Swapping two variables

>>> a=10
>>> b=20
>>> a,b=b,a    #it swaps their values
we can intialize two variables like this also
>>> a,b=10,20



Comments