In [ ]:
'''#2.1 Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?'''
from llist import sllist
def remove_dubs(l):
if l.first is None:
raise ValueError ('list is empty')
current = l.first
seen=set([current.value])
while current.next:
if current.next.value in seen:
current.next = current.next.next
else:
seen.add(current.next.value)
current = current.next
return seen
In [ ]:
In [ ]:
l=sllist([1,2,3,3])
node = l.first
node.next.next()
In [ ]:
remove_dubs(l)
In [ ]:
In [ ]:
#2.2 Implement an algorithm to find the nth to last element of a singly linked list.
In [ ]:
def kthtolast(l,k):
if l.first is None:
return
runner = current = l.first
for i in range (k):
if runner is None:
return None
runner = runner.next
while runner:
current=current.next
runner = runner.next
return current
In [ ]:
l=sllist([1,2,3,3])
kthtolast(l,3)
In [ ]:
#2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
In [ ]:
def delete_middle_node(node):
node.value=node.next.value
node.next=node.next.next
In [ ]:
l=llist([1,2,3,3])
delete_middle_node(l)
In [ ]:
#2.4 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
In [ ]:
In [ ]:
import itertools
def maxtime(arr):
res=[]
arr=sorted(arr)
for i in itertools.permutations(arr):
if i[0]<=2:
if i[2]<6:
res.append(i)
#else:
#raise ValueError('cannt do it')
ti = res[-1]
t = str(ti[0])+''+str(ti[1])+':'+str(ti[2])+''+str(ti[3])
return t,res
In [ ]:
maxtime([4,7,5,1])
In [ ]:
In [ ]:
In [ ]:
a=[[1,1,1,2],
[1,9,1,2],
[1,8,9,2],
[1,2,3,4]]
In [ ]:
a
In [ ]:
def cavityMap(arr):
n=int(arr[0])
for i in range(1,n-1):
for j in range(1,n-1):
if arr[i-1][j] != 'X' and int(arr[i-1][j]) < int(arr[i][j]) and \
arr[i+1][j] != 'X' and int(arr[i+1][j]) < int(arr[i][j]) and \
arr[i][j-1] != 'X' and int(arr[i][j-1]) < int(arr[i][j]) and \
arr[i][j+1] != 'X' and int(arr[i][j+1]) < int(arr[i][j]):
arr[i][j] = 'X'
return arr
In [ ]:
n = int(input())
arr=[]
for k in range(n):
line = list(input())
arr.append(line)
#cavityMap(arr)
print (''.join(l))
arr
In [ ]:
In [ ]:
cavityMap(a)
In [ ]:
# Complete the function below.
def cavityMap(arr):
for i in arr:
i=int(i)
n=len(arr[0])
for i in range(1,n-1):
for j in range(1,n-1):
cur = int(arr[i][j])
left = int(arr[i][j-1])
right = int(arr[i][j+1])
top = int(arr[i-1][j])
bottom = int(arr[i+1][j])
if(cur>left and cur>right and cur> top and cur>bottom):
arr[i][j] = int(arr[i][j])
arr[i][j] = 'X'
return (arr)
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: