Check if the characters in a string form a Palindrome in O(1) extra space

def firstPos(str, start, end):

firstChar = -1

for i in range(start, end + 1):

if (str[i] >= 'a' and str[i] <= 'z') :

firstChar = i

break

return firstChar

def lastPos(str, start, end):

lastChar = -1

for i in range(start, end - 1, -1) :

if (str[i] >= 'a' and str[i] <= 'z') :

lastChar = i

break

return lastChar

def isPalindrome(str):

firstChar = 0

lastChar = len(str) - 1

ch = True

for i in range(len(str)) :

firstChar = firstPos(str, firstChar, lastChar);

lastChar = lastPos(str, lastChar, firstChar);

if (lastChar < 0 or firstChar < 0):

break

if (str[firstChar] == str[lastChar]):

firstChar += 1

lastChar -= 1

continue

ch = False

break

return (ch)

if __name__ == "__main__":


str = "m a 343 la y a l am"

if (isPalindrome(str)):

print("YES")

else:

print("NO")

 

program to print all Prime numbers in an Interval

def prime(x, y):

prime_list = []

for i in range(x, y):

if i == 0 or i == 1:

continue

else:

for j in range(2, int(i/2)+1):

if i % j == 0:

break

else:

prime_list.append(i)

return prime_list

starting_range = 2

ending_range = 7

lst = prime(starting_range, ending_range)

if len(lst) == 0:

print("There are no prime numbers in this range")

else:

print("The prime numbers in this range are: ", lst)


Program for compound interest

def compound_interest(principle, rate, time):

Amount = principle * (pow((1 + rate / 100), time))

CI = Amount - principle

print("Compound interest is", CI)

compound_interest(10000, 10.25, 5)


Tkinter-Text Widget

from tkinter import *

root = Tk()

root.geometry("300x300")

root.title(" Q&A ")

def Take_input():

INPUT = inputtxt.get("1.0", "end-1c")

print(INPUT)

if(INPUT == "120"):

Output.insert(END, 'Correct')

else:

Output.insert(END, "Wrong answer")

l = Label(text = "What is 24 * 5 ? ")

inputtxt = Text(root, height = 10,

width = 25,

bg = "light yellow")

Output = Text(root, height = 5,

width = 25,

bg = "light cyan")

Display = Button(root, height = 2,

width = 20,

text ="Show",

command = lambda:Take_input())

l.pack()

inputtxt.pack()

Display.pack()

Output.pack()

mainloop()


Pattern Printing

def Pattern(line):

pat=""

for i in range(0,line):

for j in range(0,line):

if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or

i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2)

and j > line-5 and j < line-1) or (j == line-2 and

i != 0 and i != line-1 and i >=((line-1)/2))):

pat=pat+"#"

else:

pat=pat+" "

pat=pat+"\n"

return pat

line = 7

print(Pattern(line))


Program for Brick Sort

def oddEvenSort(arr, n):

    isSorted = 0

    while isSorted == 0:

        isSorted = 1

        temp = 0

        for i in range(1, n-1, 2):

            if arr[i] > arr[i+1]:

                arr[i], arr[i+1] = arr[i+1], arr[i]

                isSorted = 0

                  

        for i in range(0, n-1, 2):

            if arr[i] > arr[i+1]:

                arr[i], arr[i+1] = arr[i+1], arr[i]

                isSorted = 0

    return

arr = [34, 2, 10, -9]

n = len(arr)

oddEvenSort(arr, n);

for i in range(0, n):

    print(arr[i], end =" ")

      


Program for Find sum of even factors of a number

import math

def sumofFactors(n) :

if (n % 2 != 0) :

return 0

res = 1

for i in range(2, (int)(math.sqrt(n)) + 1) :

count = 0

curr_sum = 1

curr_term = 1

while (n % i == 0) :

count= count + 1

n = n // i

if (i == 2 and count == 1) :

curr_sum = 0

curr_term = curr_term * i

curr_sum = curr_sum + curr_term

res = res * curr_sum

if (n >= 2) :

res = res * (1 + n)

return res

n = 18

print(sumofFactors(n))


Program for Legendre\’s Conjecture

import math

def isprime( n ):

i = 2

for i in range (2, int((math.sqrt(n)+1))):

if n%i == 0:

return False

return True

def LegendreConjecture( n ):

print ( "Primes in the range ", n*n

, " and ", (n+1)*(n+1)

, " are:" )

for i in range (n*n, (((n+1)*(n+1))+1)):

if(isprime(i)):

print (i)

n = 50

LegendreConjecture(n)


Design with turtle

import turtle

turtle.speed(0)

turtle.bgcolor("black")

for i in range(15):

for colours in ("red", "magenta", "yellow", "orange", "blue", "green", "purple"):

turtle.color(colours)

turtle.pensize(3)

turtle.left(4)

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(90)


Counter to find the size of largest subset of anagram words

from collections import Counter

def maxAnagramSize(input):

input = input.split(" ")

for i in range(0,len(input)):

input[i]=''.join(sorted(input[i]))

freqDict = Counter(input)

print (max(freqDict.values()))

if __name__ == "__main__":

input = 'ant magenta magnate tan gnamate'

maxAnagramSize(input)


program to count Even and Odd numbers in a List Using Python Lambda Expressions

list1 = [10, 21, 4, 45, 66, 93, 11]

odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))

even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)


Break a list into chunks of size N

my_list = ['python', 'for', 'engineers', 'like',

'complete','solution', 'for', 'python',

'related','queries']

def divide_chunks(l, n):

for i in range(0, len(l), n):

yield l[i:i + n]

n = 5

x = list(divide_chunks(my_list, n))

print (x)


Matrix creation of n*n Using next() + itertools.count()

import itertools

N = 4

print("The dimension : " + str(N))

temp = itertools.count(1)

res = [[next(temp) for i in range(N)] for i in range(N)]

print("The created matrix of N * N: " + str(res))


Program for Find remainder of array multiplication divided by n

from functools import reduce

def find_remainder(arr,n):

   sum_1=reduce(lambda x,y: x*y,arr)

   remainder=sum_1%n

   print(remainder)

arr=[100,10,5,25,35,14]

n=11

find_remainder(arr,n)

Reconstruct the array by replacing arr[i] with (arr[i-1]+1) % M

def construct(n, m, a):

ind = 0

for i in range(n):

if (a[i]!=-1):

ind = i

break

for i in range(ind-1, -1, -1):

if (a[i]==-1):

a[i]=(a[i + 1]-1 + m)% m

for i in range(ind + 1, n):

if(a[i]==-1):

a[i]=(a[i-1]+1)% m

print(*a)

n, m = 6, 7

a =[5, -1, -1, 1, 2, 3]

construct(n, m, a)

Program for Number of stopping station problem

def stopping_station( p, n):

num = 1

dem = 1

s = p

while p != 1:

dem *= p

p-=1

t = n - s + 1

while t != (n-2 * s + 1):

num *= t

t-=1

if (n - s + 1) >= s:

return int(num/dem)

else:

return -1

num = stopping_station(4, 12)

if num != -1:

print(num)

else:

print("Not Possible")


Pattern matching with Regex

import re

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

mo = phoneNumRegex.search('My number is 415-555-4242.')

print('Phone number found: ' + mo.group())



Draw Among Us Character with Turtle

import turtle

color1 =  'yellow'

color2 = ''

color3 = 'skyblue'

color4 = ''

s = turtle.getscreen()

t = turtle.Turtle()

def x():

    t.pensize(20)

    t.fillcolor(color1)

    t.begin_fill()

    t.right(90)

    t.forward(50)

    t.right(180)

    t.circle(40, -180)

    t.right(180)

    t.forward(200)

    t.right(180)

    t.circle(100, -180)

    t.backward(20)

    t.left(15)

    t.circle(500, -20)

    t.backward(20)

    t.circle(40, -180)

    t.left(7)

    t.backward(50)

    t.up()

    t.left(90)

    t.forward(10)

    t.right(90)

    t.down()

    t.right(240)

    t.circle(50, -70)

    t.end_fill()

def glass():

    t.up()

    t.right(230)

    t.forward(100)

    t.left(90)

    t.forward(20)

    t.right(90)

    t.down()

    t.fillcolor(color3)

    t.begin_fill()

    t.right(150)

    t.circle(90, -55)

    t.right(180)

    t.forward(1)

    t.right(180)

    t.circle(10, -65)

    t.right(180)

    t.forward(110)

    t.right(180)

    t.circle(50, -190)

    t.right(170)

    t.forward(80)

    t.right(180)

    t.circle(45, -30)

    t.end_fill()

def y():

    t.up()

    t.right(60)

    t.forward(100)

    t.right(90)

    t.forward(75)

    t.fillcolor(color1)

    t.begin_fill()

    t.down()

    t.forward(30)

    t.right(255)

    t.circle(300, -30)

    t.right(260)

    t.forward(30)

    t.end_fill()

x()

glass()

y()

turtle.done()

Colored Hexagons Turtle

import turtle

from random import randint

x = 20

y = 20

turtle.speed(300)

turtle.colormode(255)

def move(l, a):

                turtle.right(a)

                turtle.forward(l)

def hex():

        turtle.pendown()

        turtle.color( randint(0,255),randint(0,255),randint(0,255) )

        turtle.begin_fill()

        for i in range(6):

                move(x,-60)

        turtle.end_fill()

        turtle.penup()

turtle.penup()

for color in range (y):

        if color == 0:

                hex()

                move(x,-60)

                move(x,-60)

                move(x,-60)

                move(0,180)

        for i in range (6):

                move(0,60)

                for j in range (color+1):

                        hex()

                        move(x,-60)

                        move(x,60)

                move(-x,0)

        move(-x,60)

        move(x,-120)

        move(0,60)

turtle.exitonclick()

Generating random strings until a given string is generated

import string

import random

import time

possibleCharacters = (string.ascii_lowercase + string.digits +

string.ascii_uppercase + ' ., !?;:')

t = "hi"

attemptThis = ''.join(random.choice(possibleCharacters)

for i in range(len(t)))

attemptNext = ''

completed = False

iteration = 0

while completed == False:

print(attemptThis)

attemptNext = ''

completed = True

for i in range(len(t)):

if attemptThis[i] != t[i]:

completed = False

attemptNext += random.choice(possibleCharacters)

else:

attemptNext += t[i]

iteration += 1

attemptThis = attemptNext

time.sleep(0.1)

print("Target matched after " +

str(iteration) + " iterations")


Check if Binary representation is Palindrome

def binaryPallindrome(num):

binary = bin(num)

binary = binary[2:]

return binary == binary[-1::-1]

if __name__ == "__main__":

num = 9

print (binaryPallindrome(num))


Program to accept string ending with alphanumeric character

import re

regex = '[a-zA-z0-9]$'

def check(string):

if(re.search(regex, string)):

print("Accept")

else:

print("Discard")

if __name__ == '__main__' :

string = "python@"

check(string)

string = "python326"

check(string)

string = "python."

check(string)

string = "python"

check(string)


Program for Recursive Insertion Sort

def insertionSortRecursive(arr, n):

if n <= 1:

return

insertionSortRecursive(arr, n - 1)

last = arr[n - 1]

j = n - 2

while (j >= 0 and arr[j] > last):

arr[j + 1] = arr[j]

j = j - 1

arr[j + 1] = last

if __name__ == '__main__':

A = [-7, 11, 6, 0, -3, 5, 10, 2]

n = len(A)

insertionSortRecursive(A, n)

print(A)


Finding sum of digits of a number until sum becomes single digit

import math

def digSum( n):

sum = 0

while(n > 0 or sum > 9):

if(n == 0):

n = sum

sum = 0

sum += n % 10

n /= 10

return sum

n = 1234

print (digSum(n))


Check whether a number has consecutive 0’s in the given base or not

def hasConsecutiveZeroes(N, K):

z = toK(N, K)

if (check(z)):

print("Yes")

else:

print("No")

def toK(N, K):

w = 1

s = 0

while (N != 0):

r = N % K

N = N//K

s = r * w + s

w = 10

return s

def check(N):

fl = False

while (N != 0):

r = N % 10

N = N//10

if (fl == True and r == 0):

return False

if (r > 0):

fl = False

continue

fl = True

return True

N, K = 15, 8

hasConsecutiveZeroes(N, K)


Program for Number of solutions to Modular Equations

import math

def calculateDivisors (A, B):

N = A - B

noOfDivisors = 0

a = math.sqrt(N)

for i in range(1, int(a + 1)):

if ((N % i == 0)):

if (i > B):

noOfDivisors +=1

if ((N / i) != i and (N / i) > B):

noOfDivisors += 1;

return noOfDivisors

def numberOfPossibleWaysUtil (A, B):

if (A == B):

return -1

if (A < B):

return 0

noOfDivisors = 0

noOfDivisors = calculateDivisors;

return noOfDivisors

def numberOfPossibleWays(A, B):

noOfSolutions = numberOfPossibleWaysUtil(A, B)

if (noOfSolutions == -1):

print ("For A = " , A , " and B = " , B

, ", X can take Infinitely many values"

, " greater than " , A)

else:

print ("For A = " , A , " and B = " , B

, ", X can take " , noOfSolutions

, " values")

A = 26

B = 2

numberOfPossibleWays(A, B)

A = 21

B = 5

numberOfPossibleWays(A, B)


Square Mania

import turtle as t

pen = t.Turtle()

pen.color("cyan")

pen.speed(0)

colors = ["green","black","orange","navy","green","black","orange","navy"]

def draw_square(color):

        for side in range(4):

                pen.forward(100)

                pen.right(90)

                for side in range(4):

                        pen.forward(50)

                        pen.right(90)

pen.penup()

pen.back(40)

pen.pendown()

for color in colors:

        pen.color(color)

        draw_square(color)

        pen.forward(50)

        pen.left(45)


pen.hideturtle()

t.done()

Program for Print Number series without using loop

def PrintNumber(N, Original, K, flag):

print(N, end = " ")

if (N <= 0):

if(flag==0):

flag = 1

else:

flag = 0

if (N == Original and (not(flag))):

return


if (flag == True):

PrintNumber(N - K, Original, K, flag)

return

if (not(flag)):

PrintNumber(N + K, Original, K, flag);

return

N = 20

K = 6

PrintNumber(N, N, K, True)


Regex to extract maximum numeric value from a string

import re

def extractMax(input):

numbers = re.findall('\d+',input)

numbers = map(int,numbers)

print (max(numbers))

if __name__ == "__main__":

input = '100klh564abc365bg'

extractMax(input)


Pigeonhole Sort

def pigeonhole_sort(a):

my_min = min(a)

my_max = max(a)

size = my_max - my_min + 1

holes = [0] * size

for x in a:

assert type(x) is int, "integers only please"

holes[x - my_min] += 1

i = 0

for count in range(size):

while holes[count] > 0:

holes[count] -= 1

a[i] = count + my_min

i += 1

a = [8, 3, 2, 7, 4, 6, 8]

print("Sorted order is : ", end =" ")

pigeonhole_sort(a)

for i in range(0, len(a)):

print(a[i], end =" ")


Order Tuples by List

lst = [('for', 3), ('python', 9), ('engineers', 10)]

print("The original list is : " + str(lst))

ord_list = ['python', 'for', 'engineers']

temp = dict(lst)

res = [(key, temp[key]) for key in ord_list]

print("The ordered tuple list : " + str(res))


Check if binary representations of two numbers are anagram

from collections import Counter

def checkAnagram(num1,num2):

bin1 = bin(num1)[2:]

bin2 = bin(num2)[2:]

zeros = abs(len(bin1)-len(bin2))

if (len(bin1)>len(bin2)):

bin2 = zeros * '0' + bin2

else:

bin1 = zeros * '0' + bin1

dict1 = Counter(bin1)

dict2 = Counter(bin2)

if dict1 == dict2:

print('Yes')

else:

print('No')

if __name__ == "__main__":

num1 = 8

num2 = 4

checkAnagram(num1,num2)


Check if a given string is binary string or not

def check(string) :

p = set(string)

s = {'0', '1'}

if s == p or p == {'0'} or p == {'1'}:

print("Yes")

else :

print("No")


if __name__ == "__main__" :

string = "101010000111"

check(string)


Using itemgetter sort list of dictionaries by values

from operator import itemgetter

lis = [{ "name" : "Pooja", "age" : 22},

{ "name" : "Arjun", "age" : 20 },

{ "name" : "Nikhil" , "age" : 19 }]

print ("The list printed sorting by age:")

print (sorted(lis, key=itemgetter('age')))

print ("\r")

print ("The list printed sorting by age and name:")

print (sorted(lis, key=itemgetter('age', 'name')))

print ("\r")

print ("The list printed sorting by age in descending order:")

print (sorted(lis, key=itemgetter('age'),reverse = True))


Get Kth Column of Matrix using list comprehension

test_list = [[4, 5, 8], [8, 1, 20], [7, 12, 10]]

print("The original list is : " + str(test_list))

K = 2

res = [sub[K] for sub in test_list]

print("The Kth column of matrix is : " + str(res))


Words Frequency in String Shorthands

 # Using Counter() + split()

from collections import Counter

test_str = 'Python for engineers . Solution for python programs'

print("The original string is : " + str(test_str))

res = Counter(test_str.split())

print("The words frequency : " + str(dict(res)))


Program for Maximum height when coins are arranged in a triangle

def squareRoot(n):

x = n

y = 1

e = 0.000001 

while (x - y > e):

x = (x + y) / 2

y = n/x

return x

def findMaximumHeight(N):

n = 1 + 8*N

maxh = (-1 + squareRoot(n)) / 2

return int(maxh)

N = 12

print(findMaximumHeight(N))


Program for Product of unique prime factors of a number

import math

def productPrimeFactors(n):

product = 1

if (n % 2 == 0):

product *= 2

while (n%2 == 0):

n = n/2

for i in range (3, int(math.sqrt(n)), 2):

if (n % i == 0):

product = product * i

while (n%i == 0):

n = n/i

if (n > 2):

product = product * n

return product

n = 44

print (int(productPrimeFactors(n)))


Program in numpy percentile

import numpy as np

arr = [[14, 17, 12, 33, 44],

[15, 6, 27, 8, 19],

[23, 2, 54, 1, 4,]]

print("\narr : \n", arr)

print("\n50th Percentile of arr, axis = None : ",

np.percentile(arr, 50))

print("0th Percentile of arr, axis = None : ",

np.percentile(arr, 0))

print("\n50th Percentile of arr, axis = 0 : ",

np.percentile(arr, 50, axis =0))

print("0th Percentile of arr, axis = 0 : ",

np.percentile(arr, 0, axis =0))



Turtle 3D cubes

import turtle

screen=turtle.Screen()  

screen.setup(800,800)   

trtl = turtle.Turtle()

screen.title("3-D CUBES")

trtl.penup()

trtl.setposition(0,0)

trtl.setheading(90)

trtl.color('red')

def hexagon():

    for i in range(6):

        trtl.fd(50)

        trtl.rt(60)

i = 1

while i < 7:

    trtl.pendown()

    hexagon()

    trtl.right(60)

    i = i + 1 

Check if an URL is valid or not using Regular Expression

import re

def isValidURL(str):

regex = ("((http|https)://)(www.)?" +

"[a-zA-Z0-9@:%._\\+~#?&//=]" +

"{2,256}\\.[a-z]" +

"{2,6}\\b([-a-zA-Z0-9@:%" +

"._\\+~#?&//=]*)")

p = re.compile(regex)

if (str == None):

return False

if(re.search(p, str)):

return True

else:

return False

url = "https://www.pythonforengineers.in"

if(isValidURL(url) == True):

print("Yes")

else:

print("No")


Program to print double sided stair-case pattern

def pattern(n):

for i in range(1,n+1):

k =i + 1 if(i % 2 != 0) else i

for g in range(k,n):

if g>=k:

print(end=" ")

for j in range(0,k):

if j == k - 1:

print(" * ")

else:

print(" * ", end = " ")

n = 10

pattern(n)


Possible Words using given characters

def charCount(word):

dict = {}

for i in word:

dict[i] = dict.get(i, 0) + 1

return dict

def possible_words(lwords, charSet):

for word in lwords:

flag = 1

chars = charCount(word)

for key in chars:

if key not in charSet:

flag = 0

else:

if charSet.count(key) != chars[key]:

flag = 0

if flag == 1:

print(word)

if __name__ == "__main__":

input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run']

charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l']

possible_words(input, charSet)


program to check the validity of a Password

import re

password = "D@m@_u0rtu9e$"

flag = 0

while True:

if (len(password)<8):

flag = -1

break

elif not re.search("[a-z]", password):

flag = -1

break

elif not re.search("[A-Z]", password):

flag = -1

break

elif not re.search("[0-9]", password):

flag = -1

break

elif not re.search("[_@$]", password):

flag = -1

break

elif re.search("\s", password):

flag = -1

break

else:

flag = 0

print("Valid Password")

break

if flag ==-1:

print("Not a Valid Password")


Spinner Game

from turtle import *

state = {'turn': 0}

def spinner():

    clear()

    angle = state['turn']/10

    right(angle)

    forward(100)

    dot(120, 'red')

    back(100)

    right(120)

    forward(100)

    dot(120, 'green')

    back(100)

    right(120)

    forward(100)

    dot(120, 'blue')

    back(100)

    right(120)

    update()

def animate():

    if state['turn']>0:

        state['turn']-=1


    spinner()

    ontimer(animate, 20)

def flick():

    state['turn']+=10


setup(420, 420, 370, 0)

hideturtle()

tracer(False)

width(20)

onkey(flick, 'space')

listen()

animate()

done()


Python Calendar GUI

from tkinter import *

import calendar

def showCalender():

    gui = Tk()

    gui.config(background='grey')

    gui.title("Calender for the year")

    gui.geometry("550x600")

    year = int(year_field.get())

    gui_content= calendar.calendar(year)

    calYear = Label(gui, text= gui_content, font= "Consolas 10 bold")

    calYear.grid(row=5, column=1,padx=20)

    gui.mainloop()

if __name__=='__main__':

    new = Tk()

    new.config(background='grey')

    new.title("Calender")

    new.geometry("250x140")

    cal = Label(new, text="Calender",bg='grey',font=("times", 28, "bold"))

    year = Label(new, text="Enter year", bg='dark grey')

    year_field=Entry(new)

    button = Button(new, text='Show Calender',

fg='Black',bg='Blue',command=showCalender)

    cal.grid(row=1, column=1)

    year.grid(row=2, column=1)

    year_field.grid(row=3, column=1)

    button.grid(row=4, column=1)

    new.mainloop()