Thursday, April 2, 2020

find all the substrings in a python string

def find_subs(s):
  n = len(s)
  return [s[i:j + 1] for i in range(n) for j in range(i,n)]

Fibonacci series starting with any two numbers

def multiply(F, M):
    x = (F[0][0] * M[0][0] + F[0][1] * M[1][0])
    y = (F[0][0] * M[0][1] + F[0][1] * M[1][1])
    z = (F[1][0] * M[0][0] + F[1][1] * M[1][0])
    w = (F[1][0] * M[0][1] + F[1][1] * M[1][1])
    F[0][0] = x
    F[0][1] = y
    F[1][0] = z
    F[1][1] = w
   
def power(F, n):
    if( n == 0 or n == 1):return
    M = [[0, 1],[1, 1]] 
    power(F, n // 2)
    multiply(F, F)
    if (n % 2 != 0):
        multiply(F, M) 


def fib(a,b,n):
     
    F = [[0, 1],[1, 1]]
    if (n == 0): return a
    if (n == 1): return b
    power(F, n - 1)
         
    return F[0][1]*a + F[1] [1]*b

How to initialize dynamic variables

Example 1:


Example 2 :
 
str[i] = malloc(len(char)*5)

Why lowercase variable is used other than uppercase?

Practically speaking variables should be allowed in any case, but just to follow convention in a particular domain we use certain format of words.
For example Class-names usually start with  UPPERCASE and if you want to use same name for object it can be only possible by using lowercase.

Monday, February 18, 2019

python remove text from string after character(s) without using regex

pivot = '...'
required = text.split(pivot, 1)[0]

regex to find datetime in text format

import re
r = re.compile('(?P<dow>[a-zA-Z]+,) (?P<date>[0-9]{2}) (?P<month>[A-Za-z]+) (?P<year>[0-9]{4}) (?P<hour>[0-9]{2}):(?P<minute>[0-9]{2}) (?P<ampm>[A-Z]{2})')

s = "Monday, 14 January 2019 11:50 PM"

print([m.groupdict() for m in r.finditer(s)][0])


output :
 
{'dow': 'Monday,', 'date': '14', 'month': 'January', 'year': '2019', 'hour': '11', 'minute': '50', 'ampm': 'PM'}