Skip to content

Instantly share code, notes, and snippets.

@computer-tutor
computer-tutor / gistChap6Q1.py
Created April 24, 2020 07:32
Chapter 6] Q1
def prime(n, i=2):
if(n<=2):
return True if(n==2) else False
if(n%i==0):
return False
if(i*i>n):
return True
return prime(n,i+1)
print(prime(15))
def prod(a,b,p=0):
p+=a
if b==1:
return p
return prod(a,b-1,p)
print(prod(7,5))
print(prod(8,9))
def generate_hail_seq(n):
lnum=[n]
while n!=1:
if(n%2)==0:
n=n//2
lnum.append(n)
else:
n=(n*3)+1
lnum.append(n)
return lnum
def sum_sq_digits(n):
ans=0
for i in str(n):
ans+=int(i)*int(i)
return ans
def is_happy(n):
if len(str(n))==1:
if n==1:
return 'It is a Happy Number'
def adm_search(arr, x, f=0, l=10):
if l >= f:
mid = (f+l)//2
if arr[mid] == x: # Found
return mid
elif arr[mid] > x:
return adm_search(arr, x, f, mid-1) # search below
else:
return adm_search(arr, x, mid+1, l) # search above
else:
def push(stack,x):
stack.append(x)
def pop(stack):
return stack.pop()
l=[4,5,6,7]
ans=int(input("Enter your choice:\n1:Press 1 to Push \n2:Press 2 to Pop\n Your Option:"))
if ans==1:
n=int(input("Enter element to push on stack:"))
push(l,n)
s = input("Enter a String:")
stack = []
for i in s:
stack.append(i)
l=len(stack)
for i in range(l):
print(stack.pop()*2,end="")
print()
def push(stack, x):
stack.insert(0, x) # this way top is always at the front
def pop(stack):
return stack.pop(0) # pops from the front because it is the top
l = [4, 5, 6, 7]
push(l, 8) # l becomes [8, 4, 5, 6, 7] x = pop(l)
print(l)
pop(l)
def enqueue(queue,x):
queue.append(x)
def dequeue(queue):
global front #using global variable to modify front
t=queue[front]
front +=1 #Front is incremented, thus there is no shifting
return t
l=[]
def enqueue(queue,x):
queue.append(x)
def dequeue(queue):
return queue.pop(0) #pops element present at front as elements are shifted after dequeue
l=[]
front =0
enqueue(l,1)# l=[1]
print(l)