text stringlengths 37 1.41M |
|---|
'''
*Question
Given Binary Search Tree, design an algorithm which creates a linkedlist of all nodes at each depth
'''
class llNode:
def __init__(self,item):
self.val = item
self.next= None
class bstNode:
def __init__(self,item):
self.val = item
self.left=None
self.right=None
class LinkedList:
# def __init__(self,item):
# self.head=llNode(item)
#
# def add(self,item):
# cur=self.head
# while cur.next is not None:
# cur=cur.next
# cur.next=llNode(item)
def __init__(self):
self.head=llNode(None)
self.height=0
# self.linkedlist=[]
def add(self,item):
if self.head.val is None:
self.head.val=item
else :
cur=self.head
while cur.next is not None:
cur=cur.next
cur.next = llNode(item)
def length(self):
cur = self.head
length=0
if cur.val is None:
return 0
else:
while cur is not None:
length=length+1
cur=cur.next
return length
def printlinkedlist(self):
linkedlist=[]
cur =self.head
while cur is not None:
# print(cur.val)
linkedlist.append(cur.val)
cur=cur.next
print(linkedlist)
class BinarySearchTree :
def __init__(self):
self.head = bstNode(None)
self.linkedlists=[]
self.inorder_list=[]
def add(self,item):
if self.head.val is None:
self.head.val = item
else :
self.__add_node(self.head,item)
def __add_node(self,cur,item):
if cur.val <=item:
if cur.right is not None:
self.__add_node(cur.right,item)
else :
cur.right=bstNode(item)
else:
if cur.left is not None:
self.__add_node(cur.left, item)
else:
cur.left=bstNode(item)
def inorder_traverse(self):
if self.head is not None:
self.__inorder(self.head)
def __inorder(self, cur):
if cur.left is not None:
self.__inorder(cur.left)
self.inorder_list.append(cur.val)
if cur.right is not None:
self.__inorder(cur.right)
def treeHeight(self):
if self.head.val is None:
return 0
else:
return self.__tree_height(self.head,1)
def __tree_height(self, cur, height):
if cur.left is not None:
self.height=height+1
print('self.height in left ' ,self.height)
print('cur.left.val',cur.left.val)
self.__tree_height(cur.left, height+1)
if cur.right is not None:
self.height = height + 1
print('self.height in right ', self.height)
print('cur.right.val', cur.right.val)
self.__tree_height(cur.right, height+1)
if self.height > height:
return self.height
else :
return height
def findLevelLinkedList(self):
self.linkedlists = [LinkedList() for i in range(self.treeHeight())]
ll=LinkedList()
ll.add(self.head.val)
self.linkedlists[0] = ll
ll=LinkedList()
return self.__findLevelLinkedList(self.head,1,ll)
def __findLevelLinkedList(self,cur,level,ll):
if cur is None :
return False
else :
ll2=LinkedList()
if cur.left is not None:
ll.add(cur.left.val)
print('cur.left.val ' ,cur.left.val)
print('level ', level)
self.__findLevelLinkedList(cur.left,level+1,ll2)
if cur.right is not None:
ll.add(cur.right.val)
print('cur.right.val ', cur.right.val)
print('level ', level)
self.__findLevelLinkedList(cur.right,level+1,ll2)
if ll.length() != 0 :
print('**********ll.length()',ll.length())
print('********level ', level)
ll.printlinkedlist()
self.linkedlists[level] = ll
return self.linkedlists
else :
return False
bt = BinarySearchTree()
bt.add(5)
bt.add(3)
bt.add(7)
bt.add(2)
bt.add(4)
bt.add(6)
bt.add(9)
bt.add(10)
bt.add(11)
bt.add(12)
print('treeHeight ',bt.treeHeight())
linkedlists=bt.findLevelLinkedList()
print('len of linkedlists ',len(linkedlists))
for linkedlist in linkedlists:
linkedlist.printlinkedlist()
#result not right -> due to misunderstanding of insert #####################다시 정리!!!!
|
'''
*Anagram: whether it is permutation to each other
Method1: Sort 2 strings and Compare
Method2: Use HashMap as data structure
*Extra Consideration
1) upper/lower case
2) space inbetween
3) space in each end side of string
* Python
1) str.lower() : string to lower case. no return
2) str.upper() : string to upper case. no return
3) str.strip() : remove space at each end side of string. no return
4) "seperator".join(list) : combine list into string.
chars = [ "A", "B", "C", "D", "E", "F" ]
4-1) put space in between
print " ".join(chars) : A B C D E F
4-2) no seperator.
print "".join(chars) : ABCDEF
4-3) 슬래쉬(/) as seperator
print "/".join(chars) : A/B/C/D/E/F
4-4) enter (\n)
print "\n".join(chars)
'''
def anagram(str1, str2) :
if ''.join(sorted(str1.lower())).strip() == ''.join(sorted(str2.lower())).strip():
return True
else:
return False
# Using hashmap
# If there is 2 l and 2 s, cannot differentiate with HashMap!
# => instead of True/False flag, save the number of visits
def anagram2(str1, str2) :
dict={}
for i in range(len(str1)):
if str1[i] not in dict:
dict[str1[i]]=1 #appears one time
else:
dict[str1[i]] += 1
for i in range(len(str2)):
if str2[i] not in dict: #not anagram
return False
else:
dict[str2[i]] -= 1
for key in dict.values():
if key != 0:
return False
return True
print(anagram2("llisten","lsilent"))
#print(anagram2("lisTeN","SilEnt"))
#print(anagram2("l i s T e N"," Si lEnt "))
|
# https://labs.spotify.com/2014/02/28/how-to-shuffle-songs/
# import sys
# import codecs
# sys.stdin= codecs.getreader("utf-8")
# # (sys.stdin.detach())
# sys.stdout = codecs.getwriter("utf-8")
# (sys.stdout.detach())
from random import randint
import random
def shuffle(songs, artists):
n = len(songs)
info = []
dict = {}
# step1: let's construct vector of [(count of artists, artists)]
for s in set(artists):
info.append((artists.count(s), s)) # save as tuple
# let's construct dict of [artists : [their songs]]
for i in range(len(artists)):
if artists[i] not in dict:
dict[artists[i]] = [songs[i]]
else:
dict[artists[i]].append(songs[i])
random.shuffle(dict[artists[i]]) # shuffle the songs of that artists to have different result every time
info.sort(reverse=True) # descending order
# construct new data format
infostr = []
for i in range(len(info)):
infostr.extend(dict[info[i][1]])
# step 2: First distribute evenly the songs of most counted singers
result = [None] * n
# jump by 2 starting from index 0
result[::2] = infostr[:(n + 1) // 2]
# jump by 2 starting from 1 (the rest)
result[1::2] = infostr[(n + 1) // 2:] # using the rest of elements starting from (n+1)//2, distribute the rest
return '\t'.join(map(str, result[::]))
# Enter your code here. Read input from STDIN. Print output to STDOUT
casecnt = int(input())
for i in range(casecnt):
songs = [part for part in input().split("\t")]
artists = [part for part in input().split("\t")]
res = shuffle(songs, artists)
print(res)
|
'''
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
1) The left subtree of a node contains only nodes with keys "less than" the node’s key.
2) The right subtree of a node contains only nodes with keys "greater than" the node’s key.
3) Both the left and right subtrees must also be binary search trees.
'''
# Definition for a binary tree node
class Node: #TreeNode
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def __init__(self):
self.inorder=[]
def in_order(self, A):
if A.left is not None: ### DONT FORGET
self.in_order(A.left)
self.inorder.append(A.val)
if A.right is not None:
ls = self.in_order(A.right)
def isValidBST(self, A):
### to valid BST, do inorder (LvR) traverse and see it is ascending order
self.in_order(A)
for i in range(len(self.inorder)-1):
if self.inorder[i] >= self.inorder[i+1]: ### SHOULD ALSO CONTAIN EQUAL SIGN!!
return 0 #not ascending order
return 1
bt = Node(3)
bt.left=Node(2)
bt.right=Node(4)
bt.left.left=Node(1)
bt.left.right=Node(3)
# bt.add(3)
# bt.add(4)
# bt.add(1)
# bt.add(7)
solution = Solution()
print(solution.isValidBST(bt))
|
'''
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
'''
### Data Structure : hashmap (To make it clean as possible)
class Solution:
# @param A : string
# @return an integer
def romanToInt(self, A):
dict = {"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000}
# problem when I is before the key V, X (e.g. IV, IX) (I = 1)
# problem when X is before the key L, C (e.g. XL, XC) (X = 10)
# problem when C is before the key D, M (e.g. CD, CM) (C = 100)
### I CAN JUST PUT VECTOR AS THE VALUES!!
ruledict = {"I": ["V", "X"],
"X": ["L", "C"],
"C": ["D", "M"]}
# "M D C C C I V" 1804
sum = 0
for i in range(len(A)-1): # will use i+1 index. Take care the last one in the last moment
if A[i] != "I" and A[i] != "X" and A[i] != "C": #e.g. 1, 10, 100
sum = sum + dict[A[i]]
else:
if A[i + 1] not in ruledict[A[i]]:
sum = sum + dict[A[i]]
else:
sum = sum - dict[A[i]] #then V,X (or L,C or D,M) can be just added without problem
# Taking care of the last element (for loop was done only until len(A)-1)
sum = sum + dict[A[len(A) - 1]]
return sum
solution = Solution()
print(solution.romanToInt("MDCCCIV")) |
'''
1) preorder traverse (vLR)
When use preorder?
: When there are multiple servers,
send tree structure of one certain server to another server in preorder.
2) inorder traverse(LvR)
Time complexity : O(n)
3) postorder traverse(LRv)
'''
class Node:
def __init__(self,item):
self.val = item
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.head=Node(None)
self.preorder_list = []
self.inorder_list = []
self.postorder_list = []
def add(self,item):
if self.head.val is None:
self.head.val = item
else :
self.__add_node(self.head,item)
def __add_node(self, cur,item):
if item <= cur.val:
if cur.left is not None:
self.__add_node(cur.left,item)
else: #if cur.left is None
cur.left=Node(item)
else : #cur.val <= item
if cur.right is not None:
self.__add_node(cur.right,item)
else : #if cur.right is None
cur.right = Node(item)
def preorder_traverse(self):
if self.head is not None:
self.__preorder(self.head)
def __preorder(self,cur):
self.preorder_list.append(cur.val)
if cur.left is not None:
self.__preorder(cur.left)
if cur.right is not None:
self.__preorder(cur.right)
def inorder_traverse(self):
if self.head is not None:
self.__inorder(self.head)
def __inorder(self,cur):
if cur.left is not None:
self.__inorder(cur.left)
self.inorder_list.append(cur.val)
if cur.right is not None:
self.__inorder(cur.right)
def postorder_traverse(self):
if self.head is not None:
self.__postorder(self.head)
def __postorder(self,cur):
if cur.left is not None:
self.__postorder(cur.left)
if cur.right is not None:
self.__postorder(cur.right)
self.postorder_list.append(cur.val)
bt = BinarySearchTree()
bt.add(5)
bt.add(3)
bt.add(4)
bt.add(1)
bt.add(7)
# 5
# 3 7
# 1 4
print("pre order")
bt.preorder_traverse() #vLR
print(bt.preorder_list)
# 5 3 1 4 7
print("in order")
bt.inorder_traverse() #LvR
print(bt.inorder_list)
# 1 3 4 5 7
print("post order")
bt.postorder_traverse() #LRv
print(bt.postorder_list)
# 1 4 3 7 5
|
'''
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
'''
#strategy: start from the last index
class Solution(object):
def merge(self, nums1, m, nums2, n):
cur1=m-1 #last index of array1
cur2=n-1 #last index of array2
index=len(nums1)-1 #last index of nums1
#while valid index (until index 0)
while cur1 >=0 and cur2 >= 0: #stop when cur1 < 0 or cur2 < 0:
if nums1[cur1] <= nums2[cur2]:
nums1[index]=nums2[cur2]
index-=1
cur2-=1
else:
nums1[index] = nums1[cur1]
index-=1
cur1-=1
# problem occurs when cur2 has not been reached to the front (cur2 != -1)
# need to update the rest of nums2 to nums1
#problem already solved when cur2 == -1 because cur1 can stay where it is
while cur2 >= 0: #stop when cur2 == -1:
nums1[index]=nums2[cur2]
index-=1
cur2-=1
return nums1
solution = Solution()
print(solution.merge([1,2,3,0,0,0],3,[2,5,6],3))
print(solution.merge([4,5,6,0,0,0],3,[1,2,3],3)) #when cur2 has not been reached to the front
print(solution.merge([1,2,3,0,0,0],3,[4,5,6],3))
print(solution.merge([1,3,5,0,0,0],3,[2,4,6],3))
print(solution.merge([2,4,6,0,0,0],3,[1,3,5],3)) |
'''
Given a non-empty array of integers, every element appears "twice" except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
class Solution(object):
def singleNumber(self, nums):
dict={} # Use hashmap to check whether it has been visited
#Complexity O(N)
for i in range(len(nums)): #for loop in nums: O(N)
if nums[i] not in dict: #find in hashmap: O(1)
dict[nums[i]] = False
else: #more than twice, becomes True
dict[nums[i]] = True
for key, value in dict.items(): #for loop in dict.items(): O(N)
if value is False:
return key
def singleNumber2(self, nums):
#Complexity: O(logN) (to put nums array in set)
# applying the formula: every element appears twice except for one
return (2 * sum(set(nums)) - sum(nums))
solution = Solution()
print(solution.singleNumber([2,2,1]))
print(solution.singleNumber([2,2,3,5,3,5,1]))
print(solution.singleNumber2([2,2,3,5,3,5,1]))
|
'''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
You need to do this in place.
Note that if you end up using an additional array, you will only receive partial score.
Example:
If the array is
[
[1, 2],
[3, 4]
]
Then the rotated array becomes:
[
[3, 1],
[4, 2]
]
'''
class Solution:
# @param A : list of list of integers
# @return the same list modified
def rotate(self, A):
N = len(A)
# step1 : transpose the matrix
for i in range(len(A)):
for j in range(i+1, len(A)): #don't need to swap between i,i and just need to swap upper matrix
A[i][j], A[j][i] = A[j][i], A[i][j]
# step2: swap the columns
for j in range(len(A) // 2): #swap only half column
for i in range(len(A)): #swap each row of that column
A[i][j], A[i][(N-1)-j] = A[i][(N-1)-j], A[i][j]
return A
solution = Solution()
print(solution.rotate([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]))
|
nombre = 5
type(nombre) # <class 'init>
nombre1 = "Juan"
type(nombre1) # <class 'str'>
nombre2 = 5.2
type(nombre2) # <class 'float'>
mensaje = """Esto es un mensaje
con tres saltos
de linea """
print(mensaje)
numero3 = 5
numero4 = 7
if numero3>numero4:
print("el numero 3 es mayor")
else:
print("el numero 4 es mayor") # = es 'asignacion', == es 'comparacion'
|
midiccionario={"Alemania":"Berlin","Francia":"Paris","Reino Unido":"Londres","Mexico":"Ciudad de Mexico"} #"palabra":"significado"
midiccionario["Italia"]="Lisboa" #aniade un nuevo elemento al diccionario
print(midiccionario) #imprime todo el diccionario
print(midiccionario["Francia"]) #la funcion imprime lo que se busca
midiccionario["Italia"]="Roma" #corrige el valor de una palabra y se imprime el nuevo
print(midiccionario)
del midiccionario["Reino Unido"] #elimina un elemento indicado
print(midiccionario)
diccionario1={23:"Jordan","mosqueteros":3}
print(diccionario1)
mitupla=["Espania","Francia","Reino Unido","Alemania"]
diccionario2={mitupla[0]:"Madrid",mitupla[1]:"Paris",mitupla[2]:"Londres",mitupla[3]:"Berlin"}
print(diccionario2)
print(diccionario2["Francia"])
dicc={23:"Eva","Nombre":"Michael","Equipo":"Chicago","Anillos":{"temporadas":[1991,1992,1993,1996,1997,1998]}}
print(dicc.keys()) #imprime claves
print(dicc.values()) #imprime valores
print(len(dicc))
print(dicc)
print(dicc["Equipo"])
print(dicc["Anillos"])
|
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = []
queue.append((root, root))
# queue = collections.deque([(root, root)])
while queue:
t1, t2 = queue.pop(0)
if not t1 and not t2:
continue
elif not t1 or not t2:
return False
elif t1.val != t2.val:
return False
queue.append((t1.left, t2.right))
queue.append((t1.right, t2.left))
return True
|
from collections import deque
class Solution:
def maxAreaOfIsland(self, grid):
R, C = len(grid), len(grid[0])
size_max = 0
for i in range(R):
for j in range(C):
if grid[i][j] == 1:
print("find", i, j)
grid[i][j] = 0
size_max = max(self.bfs(i, j, grid), size_max)
print(i, j, size_max)
return size_max
def bfs(self, i, j, grid):
q = deque([(i, j)])
area = 1
while q:
i, j = q.popleft()
for I, J in [i - 1, j], [i, j - 1], [i + 1, j], [i, j + 1]:
if 0 <= I < len(grid) and 0 <= J < len(grid[0]) and grid[I][J] == 1:
grid[I][J] = 0
q.append((I, J))
area += 1
return area
"""
695. Max Area of Island
Medium
1508
67
Add to List
Share
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
""" |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
# left_correct = (not root.left or root.val == root.left.val
# and self.isUnivalTree(root.left))
# right_correct = (not root.right or root.val == root.right.val
# and self.isUnivalTree(root.right))
# return left_correct and right_correct
vals = []
def dfs(node):
if node:
vals.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return len(set(vals)) == 1
"""
965. Univalued Binary Tree
Easy
363
39
Add to List
Share
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
Example 1:
Input: [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: [2,2,2,5,2]
Output: false
Note:
The number of nodes in the given tree will be in the range [1, 100].
Each node's value will be an integer in the range [0, 99].
""" |
class Solution:
def maxDepth(self, root: 'Node') -> int:
queue = collections.deque()
if root:
queue.append((root, 1))
depth = 0
while queue:
root, curr_depth = queue.popleft()
if root:
depth = max(depth, curr_depth)
for c in root.children:
queue.append((c, curr_depth + 1))
return depth
"""
class Solution(object):
def maxDepth(self, root):
queue = []
if root: queue.append((root, 1))
depth = 0
for (node, level) in queue:
depth = level
queue += [(child, level+1) for child in node.children]
return depth
""" |
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
height, width = len(matrix), len(matrix[0])
row = height - 1
col = 0
while col < width and row >= 0:
if matrix[row][col] > target:
row -= 1
elif matrix[row][col] < target:
col += 1
else:
return True
return False
"""
240. Search a 2D Matrix II
Medium
2331
65
Add to List
Share
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
5
""" |
from collections import deque
import collections
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findClosestLeaf(self, root: TreeNode, k: int) -> int:
graph = collections.defaultdict(list)
# We use a depth-first search to record in our graph each edge travelled from parent to node.
def dfs(node, par=None):
if node:
graph[node].append(par)
graph[par].append(node)
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
# After, we use a breadth-first search on nodes that started with a value of k, so that we are visiting nodes in order of their distance to k. When the node is a leaf (it has one outgoing edge, where the root has a "ghost" edge to null), it must be the answer.
queue = collections.deque(node for node in graph
if node and node.val == k)
seen = set(queue)
while queue:
node = queue.popleft()
if node:
if len(graph[node]) <= 1:
return node.val
for nei in graph[node]:
if nei not in seen:
seen.add(nei)
queue.append(nei)
# stack = deque([root])
# while stack:
# node = stack.pop()
# print("node",node)
# if node:
# if node.val == k:
# if node.left:
# return node.left.val
# elif node.right:
# return node.right.val
# if node.left:
# stack.append(node.left)
# if node.right:
# stack.append(node.val)
# return k
|
# 2-line Recursion. In most tree problems, try recursion first.
class Solution(object):
def maxDepth(self, root):
if not root: return 0
return 1 + max(map(self.maxDepth, root.children or [None]))
# BFS (use a queue, the last level we see will be the depth)
class Solution(object):
def maxDepth(self, root):
queue = []
if root: queue.append((root, 1))
depth = 0
for (node, level) in queue:
depth = level
queue += [(child, level+1) for child in node.children]
return depth
# DFS (use a stack, use max to update depth)
class Solution(object):
def maxDepth(self, root):
stack = []
if root: stack.append((root, 0))
depth = 0
while stack:
(node, d) = stack.pop()
depth = max(depth, d)
for child in node.children:
stack.append((child, d+1))
return depth
class Solution {
public:
int
maxDepth(Node * root)
{
if (root == nullptr)
return 0;
int
depth = 0;
for (auto child: root->children) depth = max(depth, maxDepth(child));
return 1 + depth;
}
}; |
class RecentCounter(object):
def __init__(self):
self.q = collections.deque()
def ping(self, t):
self.q.append(t)
while self.q[0] < t - 3000:
self.q.popleft()
return len(self.q)
"""
input
["RecentCounter","ping","ping","ping","ping"]
[[],[1],[100],[3001],[3002]]
output
[null,1,2,3,3]
Complexity Analysis
Time Complexity: O(Q)O(Q), where QQ is the number of queries made.
Space Complexity: O(W)O(W), where W = 3000W=3000 is the size of the window we should scan for recent calls. In this problem, the complexity can be considered O(1)O(1).
"""
|
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
return ''.join(self.nextSequence(n, ['1', 'E']))
def nextSequence(self, n, prevSeq):
if n == 1:
return prevSeq[:-1]
nextSeq = []
prevDigit = prevSeq[0]
digitCnt = 1
for digit in prevSeq[1:]:
if digit == prevDigit:
digitCnt += 1
else:
# the end of a sub-sequence
nextSeq.extend([str(digitCnt), prevDigit])
prevDigit = digit
digitCnt = 1
# add a delimiter for the next sequence
nextSeq.append('E')
print("n="+str(n))
return self.nextSequence(n - 1, nextSeq)
print(Solution().countAndSay(3)) |
class Solution:
def countSubstrings(self, S: str) -> int:
N = len(S)
ans = 0
for center in range(2*N - 1):
left = int(center / 2)
right = int(left + center % 2)
while left >= 0 and right < N and S[left] == S[right]:
ans += 1
left -= 1
right += 1
return ans
"""
647. Palindromic Substrings
Medium
1971
96
Add to List
Share
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
input = "abc"
output = 3
center, left, right, ans
0 0 0 0
1 0 1 1
2 1 1 1
3 1 2 2
4 2 2 2
""" |
class Solution(object):
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
def count(word):
ans = [0]*3
for ch in word:
ans[ord(ch) - ord('x')] += 1
return ans
bmax = [0]*3
for b in B:
print("b: " + str(b))
for idx, ch in enumerate(count(b)):
print("idex: " + str(idx))
print("char: " + str(ch))
bmax[idx] = max(bmax[idx], ch)
ans = []
for a in A:
if all(x >= y for x, y in zip(count(a), bmax)):
ans.append(a)
return ans
A = ["amazon","apple","facebook","google","leetcode"]
B = ["e","o"]
A2 = ["xxy","yyz"]
B2 = ["x","y"]
Solution().wordSubsets(A2,B2)
"""
916. Word Subsets
Medium
217
54
Favorite
Share
We are given two arrays A and B of words. Each word is a string of lowercase letters.
Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world".
Now say a word a from A is universal if for every b in B, b is a subset of a.
Return a list of all universal words in A. You can return the words in any order.
Example 1:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
Output: ["facebook","google","leetcode"]
Example 2:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
Output: ["apple","google","leetcode"]
Example 3:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
Output: ["facebook","google"]
Example 4:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
Output: ["google","leetcode"]
Example 5:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
Output: ["facebook","leetcode"]
Note:
1 <= A.length, B.length <= 10000
1 <= A[i].length, B[i].length <= 10
A[i] and B[i] consist only of lowercase letters.
All words in A[i] are unique: there isn't i != j with A[i] == A[j].
"""
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
return res
def dfs(node, level):
# start the current level
if len(res) == level:
res.append([])
# append the current node value
res[level].append(node.val)
# process child nodes for the next level
if node.left:
dfs(node.left, level + 1)
if node.right:
dfs(node.right, level + 1)
dfs(root, 0)
return res
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
return res
level = 0
def bfs(node, level):
queue = deque([root, ])
while queue:
# start the current level
res.append([])
# number of elements in the current level
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
# fulfill the current level
res[level].append(node.val)
# add child nodes of the current level
# in the queue for the next level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# go to next level
level += 1
return res
bfs(root, 0)
return bfs
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
return res
level = 0
queue = deque([root, ])
while queue:
# start the current level
res.append([])
# number of elements in the current level
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
# fulfill the current level
res[level].append(node.val)
# add child nodes of the current level
# in the queue for the next level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# go to next level
level += 1
return res
"""
102. Binary Tree Level Order Traversal
Medium
2220
59
Add to List
Share
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
""" |
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
M, N, p = len(grid), len(grid[0]), 0
for m in range(M):
for n in range(N):
if grid[m][n] == 1:
if m == 0 or grid[m-1][n] == 0: p += 1
if n == 0 or grid[m][n-1] == 0: p += 1
if n == N-1 or grid[m][n+1] == 0: p += 1
if m == M-1 or grid[m+1][n] == 0: p += 1
# print(m,n,p)
return p
"""
463. Island Perimeter
Easy
1451
97
Add to List
Share
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example:
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
""" |
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
dic = {}
for num in nums2:
while stack != [] and num > stack[-1]:
dic[stack.pop()] = num
stack.append(num)
res = []
for num in nums1:
if num in dic.keys():
res.append(dic[num])
else:
res.append(-1)
return res
"""
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
out = [-1]*len(nums1)
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums2[j] == nums1[i]:
for l in range(j + 1, len(nums2)):
if nums2[l] > nums2[j]:
out[i] = nums2[l]
break
return out
"""
"""
496. Next Greater Element I
Easy
965
1554
Favorite
Share
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
"""
|
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.is_sorted = False
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.nums.append(number)
self.is_sorted = False
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
if not self.is_sorted:
self.nums.sort()
low, high = 0, len(self.nums) - 1
while low < high:
currSum = self.nums[low] + self.nums[high]
if currSum < value:
low += 1
elif currSum > value:
high -= 1
else:
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)
obj = TwoSum()
print(obj.add(1),
obj.add(3),
obj.add(5),
obj.find(4),
obj.find(7))
|
class Persona:
def __init__(self,nombre,apellidos,sexo,edad,altura,color_ojos,color_cabello):
self.nombre = nombre
self.apellidos = apellidos
self.sexo = sexo
self.edad = edad
self.altura = altura
self.color_ojos = color_ojos
self.color_cabello = color_cabello
def mostrar_info(self):
print("Nombre: " + self.nombre)
print("Apellido: " + self.apellidos)
print("Color de cabello: " + self.color_cabello)
print("Altura: " + self.altura)
print("Sexo: " + self.sexo)
print("Edad: " + self.edad)
#Etc...
def mostrar_edad(self):
edad = int(self.edad)
edad = edad + 10
print("En diez años "+self.nombre + " tendra: " +str(edad))
#pepito = Persona("José","Camilo santos","Hombre","12","1.56","negro","negro")
#pepito.mostrar_info()
#pepito.mostrar_edad()
nombre = input("Ingrese nombre aquí: ")
apellidos = input("Ingrese apellidos aquí: ")
sexo = input("Ingrese sexo de la persona aquí: ")
altura = input("Ingrese altura de la persona aquí: ")
color_ojos = input("Ingrese color de ojos de la persona aquí: ")
color_cabello = input("Ingrese color de cabello de la persona aquí: ")
edad = input("Ingrese la edad aquí: ")
persona = Persona (nombre,apellidos,sexo,edad,altura,color_ojos,color_cabello)
persona.mostrar_info()
persona.mostrar_edad()
|
"""
Finds the closest distance between a given location and the node locations found within data
Author: Henry Dikeman
Email: dikem003@umn.edu
Date: 07/15/21
"""
import math
def closest_distance(point, data):
min_dist = 1000
for i in data:
lon_dist = abs(point.lon - i.lon)
lat_dist = abs(point.lat - i.lat)
dist = math.sqrt(lon_dist**2 + lat_dist**2)
if (dist < min_dist):
min_dist = dist
return (min_dist)
|
"""
Selection function for training/evaluation. When a specific model architecture is selected, it is passed into this function where the appropriate dataset is curated for further use
Author: Henry Dikeman
Email: dikem003@umn.edu
Date: 07/15/21
"""
from LSTM_GenFuncs import *
def trainerModelSelect(model_num, x_nodes, y_nodes, day_num):
if model_num == 1:
return Gen_LSTM_Basic(x_nodes, y_nodes, day_num)
if model_num == 2:
return short_LSTM(x_nodes, y_nodes, day_num)
if model_num == 3:
return LSTM_BatchNorm(x_nodes, y_nodes, day_num)
if model_num == 4:
return LSTM_toConv(x_nodes, y_nodes, day_num)
if model_num == 5:
return LSTM_GRU(x_nodes, y_nodes, day_num)
else:
raise ValueError('invalid model selection')
return 0
|
import re
import unittest
# "Any word or phrase that exactly reproduces the letters in another order is an anagram." (Wikipedia).
# Add numbers to this definition to be more interest.
# The challenge is to write the function isAnagram
# to return True if the word test is an anagram of the word original and False if not.
def isAnagram(test, original):
# make sure the phrases in the Lowercase
a = test.lower()
b = original.lower()
# Get only the letters and numbers using regex
# if the sorted phrases are equal, return true
return sorted("".join(re.findall(r'[a-z0-9]+',a)))== sorted("".join(re.findall(r'[a-z0-9]+',b)))
class TestIsAnagram(unittest.TestCase):
def test_is_anagran(self):
self.assertEqual(isAnagram("William Shakespeare","I am a weakish speller"), True)
self.assertEqual(isAnagram("Silent","Listen"), True)
self.assertEqual(isAnagram("Car","Cat"), False)
self.assertEqual(isAnagram("12345","54321"), True)
if __name__ == '__main__':
unittest.main()
|
# Determine if the string has a uniqe characters
def uniqe_char2(s):
output = ''
for i in s:
if i in output:
return False
output += i
return True
def uniqe_char(s):
return len(s) == len(set(s))
print(uniqe_char('abcde'))
print(uniqe_char('aabcde'))
|
# https://www.codewars.com/kata/5629db57620258aa9d000014/train/python
# Given two strings s1 and s2, we want to visualize how different the two strings are.
# We will only take into account the lowercase letters (a to z).
# First let us count the frequency of each lowercase letters in s1 and s2.
# s1 = "A aaaa bb c", s2 = "& aaa bbb c d"
# s1 has 4 'a', 2 'b', 1 'c', s2 has 3 'a', 3 'b', 1 'c', 1 'd'
def mix(s1, s2):
s = []
lett = "abcdefghijklmnopqrstuvwxyz"
for ch in lett:
val1, val2 = s1.count(ch), s2.count(ch)
if max(val1, val2) >= 2:
if val1 > val2:
s.append("1:"+val1*ch)
elif val1 < val2:
s.append("2:"+val2*ch)
else: s.append("=:"+val1*ch)
s.sort()
s.sort(key=len, reverse=True)
return "/".join(s)
|
from collections import defaultdict
# The Trie itself containing the root node and insert/find functions
class Trie:
def __init__(self):
# Initialize this Trie (add a root node)
self.root = TrieNode()
def insert(self, word):
# Add a word to the Trie
node = self.root
for c in word:
node = node.children[c]
node.is_word = True
def find(self, prefix):
# Find the Trie node that represents this prefix
node = self.root
for c in prefix:
if c not in node.children:
return None
node = node.children[c]
return node
# Represents a single node in the Trie
class TrieNode:
def __init__(self):
# Initialize this node in the Trie
self.children = defaultdict(TrieNode)
self.is_word = False
def insert(self, char):
# Add a child node in this Trie
pass
def suffixes(self, suffix=''):
# Recursive function that collects the suffix for
# all complete words below this point
child_suffixes = []
if self.is_word:
child_suffixes.append(suffix)
for c in self.children:
child_suffixes += self.children[c].suffixes(suffix + c)
return child_suffixes
def trie_test(prefix, expected_suffixes):
trie = Trie()
word_list = [
"ant", "anthology", "antagonist", "antonym",
"fun", "function", "factory",
"trie", "trigger", "trigonometry", "tripod"
]
for word in word_list:
trie.insert(word)
prefix_node = trie.find(prefix)
if not prefix_node:
print('No Match')
if not expected_suffixes:
print("Pass")
else:
print("Fail")
return
actual_suffixes = prefix_node.suffixes()
print(actual_suffixes)
if set(actual_suffixes) == set(expected_suffixes):
print("Pass")
else:
print("Fail")
if __name__ == '__main__':
trie_test('ant', ['', 'hology', 'agonist', 'onym'])
# ['', 'hology', 'agonist', 'onym']
# Pass
trie_test('f', ['un', 'unction', 'actory'])
# ['un', 'unction', 'actory']
# Pass
trie_test('x', [])
# No Match
# Pass
|
import operator
import unittest
# Your job is to create a calculator which evaluates expressions in Reverse Polish notation.
#
# For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) should evaluate to 14.
#
# For your convenience, the input is formatted such that a space is provided between every token.
#
# Empty expression should evaluate to 0.
#
# Valid operations are +, -, *, /.
#
# You may assume that there won't be exceptional situations (like stack underflow or division by zero).
def polish_notation(expr):
OPERATORS = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
stack = [0]
for token in expr.split(" "):
if token in OPERATORS:
op2, op1 = stack.pop(), stack.pop()
print(op1, op2)
stack.append(OPERATORS[token](op2,op1))
elif token:
stack.append(float(token))
return stack.pop()
class TestPolishNotation(unittest.TestCase):
def test_notation(self):
self.assertEqual(polish_notation('3.5'), 3.5)
self.assertEqual(polish_notation('1 3 +'), 4)
self.assertEqual(polish_notation('1 3 *'), 3)
self.assertEqual(polish_notation('1 3 -'), -2)
self.assertEqual(polish_notation('4 2 /'), 2)
if __name__ == '__main__':
unittest.main()
|
def path_finder(maze):
start = (0, 0)
maze_list = maze.split('\n')
target = len(maze_list)-1, len(maze_list[0])-1
# stack.append(start)
stack = add_or_replace([], start, 0)
explored = set()
# print(stack)
#
while len(stack):
# print('c')
# node = stack.pop(0)
node, distance = remove(stack)
# print(explored)
if node == target:
return True
explored.add(node)
# print(stack)
for v, d in neighbors(node, maze_list, len(maze_list)-1, target):
# print(v, d)
if v not in explored:
print(v)
new_distance = distance + d
# if (v, new_distance) not in stack:
stack = add_or_replace(stack, v, new_distance)
return False
def neighbors(vertex, graph, n, target):
x, y = vertex
t = str(target[0]) + str(target[1])
moves = [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]
neighbors_node = set()
for (r, c) in moves:
if 0 <= r <= n and 0 <= c <= n and graph[r][c] != 'W':
v = str(r) + str(c)
d = int(t) - int(v)
neighbors_node.add(((r,c), d))
# print(vertex, neighbors_node)
return neighbors_node
def add_or_replace(min_heap, vertex, distance):
# print('j')
if min_heap:
min_heap_dict = dict((y, x) for y, x in min_heap)
else:
# print('h')
min_heap_dict = dict(min_heap)
if vertex in min_heap_dict:
if min_heap_dict[vertex] > distance:
min_heap_dict[vertex] = distance
else:
pass
else:
min_heap_dict[vertex] = distance
# print(min_heap_dict)
x = sorted(min_heap_dict.items(), key= lambda i: i[1])
# print(x)
return x
def remove(min_heap):
return min_heap.pop(0)
a = "\n".join([
".W.",
".W.",
"..."
])
# print(path_finder(a))
b = "\n".join([
".W.",
".W.",
"W.."
])
# print(path_finder(b))
c = "\n".join([
"......",
"......",
"......",
"......",
"......",
"......"
])
print(path_finder(c))
d = "\n".join([
"......",
"......",
"......",
"......",
".....W",
"....W."
])
# print(a)
# print('===========')
# print(a.split('\n'))
# print(path_finder(a))
# print(path_finder(b))
# print(path_finder(c))
# print(path_finder(d))
|
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
def quicksort(array, start, stop):
if stop - start > 0:
pivot, left, right = array[start], start, stop
while left <= right:
while array[left] < pivot:
left += 1
while array[right] > pivot:
right -= 1
if left <= right:
array[left], array[right] = array[right], array[left]
left += 1
right -= 1
quicksort(array, start, right)
quicksort(array, left, stop)
quicksort(input_list, 0, len(input_list) - 1)
sum1 = 0
sum2 = 0
i = 0
factor = 1
while i < len(input_list):
sum1 += input_list[i] * factor
if i + 1 < len(input_list):
sum2 += input_list[i + 1] * factor
factor *= 10
i += 2
return sum1, sum2
def test_function(test_case):
output = rearrange_digits(test_case[0])
print(output)
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
test_function([[], [0, 0]])
# (0, 0)
test_function([[0], [0, 0]])
# (0, 0)
test_function([[0, 1], [0, 1]])
# (0, 1)
test_function([[1, 2, 3, 4, 5], [542, 31]])
# (542, 31)
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
# (964, 852)
import random
l = [i for i in range(0, 9)] # a list containing 0 - 999
random.shuffle(l)
test_function([l, [86420, 7531]])
# (86420, 7531)
|
# Entries are (h, m) where h is the hour and m is the minute
sleep_times = [(24,13), (21,55), (23,20), (22,5), (24,23), (21,58), (24,3)]
def bubble_sort_2(l):
start = len(sleep_times) - 1
while start:
for time in range(1, len(sleep_times)):
prev_time, current_time = sleep_times[time-1], sleep_times[time]
if prev_time[0] < current_time[0]:
sleep_times[time-1], sleep_times[time] = current_time, prev_time
elif prev_time[0] == current_time[0]:
if prev_time[1] < current_time[1]:
sleep_times[time-1], sleep_times[time] = current_time, prev_time
else:
continue
start -= 1
return sleep_times
print(bubble_sort_2(sleep_times))
print ("Pass" if (sleep_times == [(24,23), (24,13), (24,3), (23,20), (22,5), (21,58), (21,55)]) else "Fail")
|
# Solve the problem using simple recursion
def fib_rec(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib_rec(n-1) + fib_rec(n-2)
# print(fib_rec(10))
# Implement the function using dynamic programming to store results (memoization).
memo = {}
def fib_dyn(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
if not n in memo:
memo[n] = fib_rec(n-1) + fib_rec(n-2)
return memo[n]
# print(fib_dyn(5))
# Implement the solution with simple iteration.
def fib_iter(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
print(fib_iter(8))
|
class Node:
def __init__(self, value=None, key=None):
self.prev = None
self.next = None
self.key = key
self.value = value
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def push_head(self, node):
"""
Push node to the head of the list.
:param node: Node to push
:return: None
"""
if self.head:
self.head.prev = node
else:
self.tail = node
node.next = self.head
node.prev = None
self.head = node
self.size += 1
def pop_tail(self):
"""
Remove node from end of list
:return: last Node in list, with next and prev nullified. Return None if list is empty.
"""
if not self.tail:
return None
saved_tail = self.tail
if self.tail.prev: # tail != head
self.tail.prev.next = None
self.tail = self.tail.prev
else: # tail == head
self.head = None
self.tail = None
saved_tail.prev = None
self.size -= 1
return saved_tail
def remove(self, node):
"""
Remove node from list. Assumes node is in list.
:param node: Node to remove
:return: Node that was removed, with next and prev nullified
"""
if node.prev: # node is not head
node.prev.next = node.next
else: # node is head
self.head = node.next
if node.next: # node is not tail
node.next.prev = node.prev
else:
self.tail = node.prev
node.next = None
node.prev = None
self.size -= 1
return node
class LRU_Cache:
def __init__(self, capacity=5):
self.capacity = capacity
self.used = DoublyLinkedList() # head is most-recently used item, tail is least-recently used
self.map = dict() # key -> Node, node contains value
def get(self, key):
"""
Return value associated with key.
Return -1 if the key is not in the cache.
Updates the used list to indicate that the key is most recently used.
:param key: the key
:return: value associated with key
"""
if key not in self.map:
return -1
node = self.map[key]
self.used.remove(node)
self.used.push_head(node)
return node.value
def set(self, key, value):
"""
Put value into cache.
If the cache is full, remove the least-recently-used item from the cache before putting the new value in the
cache.
:param key: the key
:param value: the value associated with the key
:return: None
"""
if self.capacity == 0:
return
if self.capacity == self.used.size:
node = self.used.pop_tail()
if node:
del self.map[node.key]
if key in self.map:
node = self.map[key]
node.value = value
else:
node = Node(value, key)
self.used.push_head(node)
self.map[key] = node
def test_lru(description, capacity, setup_instructions, test_get_values):
print(description)
lru = LRU_Cache(capacity)
for instruction in setup_instructions:
command, args = instruction
if command == 'get':
lru.get(args[0])
elif command == 'set':
lru.set(args[0], args[1])
for value in test_get_values:
print(lru.get(value))
if __name__ == '__main__':
test_lru("Test 1 - Basic get and put without overflow",
2, [('set', (1, 11)), ('set', (2, 12))], [1, 2])
# 11
# 12
test_lru("Test 2 - Basic get and put with overflow",
2, [('set', (1, 11)), ('set', (2, 12)), ('set', (3, 13))], [1, 2, 3])
# -1
# 12
# 13
test_lru("Test 3 - Basic get and put with getting and overflow",
2, [('set', (1, 11)), ('set', (2, 12)), ('get', (1,)), ('set', (3, 13))], [1, 2, 3])
# 11
# -1
# 13
test_lru("Test 4 - LRU with zero capacity",
0, [('set', (1, 11)), ('set', (2, 12)), ('get', (1,)), ('set', (3, 13))], [1, 2, 3])
# -1
# -1
# -1
|
import unittest
# Write a method that takes an array of consecutive (increasing) letters as
# input and that returns the missing letter in the array.
# You will always get an valid array.
# And it will be always exactly one letter be missing.
# The length of the array will always be at least 2.
# The array will always contain letters in only one case.
# Example:
# ['a','b','c','d','f'] -> 'e'
# ['O','Q','R','S'] -> 'P'
def find_missing_letter(chars):
# get the unicode code for each letter in the list
x = [ord(i) for i in chars]
# create a list of number from unicode code of 1st letter to last letter
y = [i for i in range(ord(chars[0]), ord(chars[0]) + len(chars) + 1)]
# use set and difference method to get the missing number (unicode code)
missi = set(y).difference(x)
# convert unicode code to unicode character and return it
return chr(list(missi)[0])
class TestFindMissing(unittest.TestCase):
def test_find_missing(self):
self.assertEqual(find_missing_letter(['a','b','c','d','f']), 'e')
self.assertEqual(find_missing_letter("['O','Q','R','S']"), 'P')
if __name__ == '__main__':
unittest.main()
|
import math
for reeks in range(11):
n = reeks
root5 = math.sqrt(5)
a = (1 + root5)**n
b = (1 - root5)**n
c = 2**n * root5
answer = int((a-b)/c)
print("When n is", reeks, "the Fibonacci number is:", answer)
print("Done :)") |
from queue import PriorityQueue
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
compnodeq= PriorityQueue()
for index, node in enumerate(lists):
if node != None:
compnodeq.put((node.val, index, node)) # https://leetcode.com/problems/merge-k-sorted-lists/discuss/10511/10-line-python-solution-with-priority-queue
orderednodes = []
while not compnodeq.empty():
val, index, minnode = compnodeq.get()
orderednodes.append(minnode)
if minnode.next != None:
compnodeq.put((minnode.next.val, index, minnode.next))
for i in range(len(orderednodes) - 1):
orderednodes[i].next = orderednodes[i+1]
if len(orderednodes) == 0:
return None
orderednodes[-1].next = None
return orderednodes[0]
|
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums) == 0:
return -1
start = 0
end = len(nums) - 1
if target >= nums[0]: # target on the left
while start <= end:
mid = (start + end) // 2
if nums[mid] < nums[start] or target < nums[mid]:
end = mid - 1
elif target > nums[mid]:
start = mid + 1
else:
return mid
else: #target on the right
while start <= end:
mid = (start + end) // 2
if nums[mid] > nums[end] or target > nums[mid]:
start = mid + 1
elif target < nums[mid] :
end = mid - 1
else:
return mid
return -1
|
class Solution(object):
"""
https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/
"""
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left_max = {}
right_max = {}
left_max[0] = 0
right_max[len(height)-1] = 0
for i in range(1, len(height)):
left_max[i] = max(left_max[i-1], height[i-1])
right_max[len(height)-1-i] = max(right_max[len(height)-1-i+1], height[len(height)-1-i+1])
water = 0
for i in range(len(height)):
up = min(left_max[i], right_max[i])
if up > height[i]:
water += up - height[i]
return water
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if TreeNode == None:
return True
line = []
line.append(root)
while len(line) != 0:
if self.checkline(line) == False:
return False
newline = []
for node in line:
if node == None:
pass
else:
newline.append(node.left)
newline.append(node.right)
line = newline
return True
def checkline(self, line):
i = 0
j = len(line) - 1
while j > i:
if (line[j] == None and line[i] == None) or (line[j] != None and line[i] != None and line[j].val == line[i].val):
i += 1
j += 1
else:
return False
return True |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
res = head
reverseStack = []
i = 1
while i < m:
head = head.next
i += 1
while i <= (m + n) // 2:
reverseStack.append(head)
head = head.next
i += 1
if i > (m + n + 1) // 2:
reverseStack.pop()
while len(reverseStack) != 0:
head.val, reverseStack[-1].val = reverseStack[-1].val, head.val
reverseStack.pop()
head = head.next
return res |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
headnode = head
tailnode = head
prevnode = None
count = 1
while tailnode != None:
if count == k:
nextnode = tailnode.next
newheadnode, newtailnode = self.reverse(headnode, tailnode)
if prevnode != None:
prevnode.next = newheadnode
else:
head = newheadnode
newtailnode.next = nextnode
headnode = newtailnode.next
tailnode = newtailnode.next
prevnode = newtailnode
count = 1
else:
tailnode = tailnode.next
count += 1
return head
def reverse(self, headnode, tailnode):
newtailnode = headnode
newheadnode = headnode
while newheadnode != tailnode:
passedheadnode = newheadnode
newheadnode = newtailnode.next
newtailnode.next = newheadnode.next
newheadnode.next = passedheadnode
return newheadnode, newtailnode
|
def remove_tail(self):
if not self.head:
return None
if self.head is self.tail:
value = self.head.get_value()
self.head = None
self.tail = None
return value
current = self.head
while current.get_next() is not self.tail:
current = current.get_next()
value = self.tail.get_value()
self.tail = current
self.tail.set_next(None)
return value |
print('Crie um programa que leia duas notas do aluno e mostre sua média e uma mensagem de acordo com a média\n'
'Média abaixo de 5.0: Reprovado'
'Média entre 5.0 e 6.9: Recuperação'
'Média 7.0 ou superior: Aprovado')
print('\033[33m *** Resolução do Exercicio *** \033[m')
nota1 = float(input('Informe a nota cabloco'))
nota2 = float(input('Informe a segunda nota'))
média = (nota1 + nota2)/2
if média < 5.0:
print('Seu merda, foi reprovado, sua média é {:.1f} '.format(média))
elif média == 5.0 or média < 6.9:
print('Sem condições, você foi para recuperação com média {:.1f} '.format(média))
else:
print('Mais do que a obrigação, você passou com média {:.1f} '.format(média))
|
print('----- Bem vindo ao exercicio 63 ---')
print('Escreva um programa que leia um número n inteiro qualquer e mosstre na tela os n primeiros elementos de uam sequencia de fibonacci'
'exemplo: 0->1->1->2->3->5->8')
n = int(input('Informe a quantidade de termos que você quer mostrar'))
t1 = 0
t2 = 1
print('~'*30)
print('{} -> {}'.format(t1,t2), end='')
cont = 3
while cont <=n:
t3 = t1 + t2
print('-> {}'.format(t3), end='')
t1 = t2
t2 = t3
cont += 1
print('-> FIM')
|
print('\033[31m Bem vindo ao exercicio 56 \033[m')
print('Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: A média de idade do grupo, Qual é o nome do homem mais velho, Quantas mulheres tem menos de 20 anos')
media = 0
totalidade = 0
hvelho = 0
C=0
namevelho = ''
mulhermenos = 0
for people in range (0, 4):
print('----- {} Pessoa ----'.format(people+1))
name = str(input('Qual o seu nome, jovem?')).strip()
age = int(input('Qual sua idade, jovem?'))
sexo = str(input('Você é uma jovem ou um jovem? F ou M')).strip()
totalidade = totalidade + age
if people == 0 and sexo in 'Mm':
hvelho = age
namevelho = name
if sexo in 'Mm' and age > hvelho:
hvelho = age
namevelho = name
if sexo == 'F' and age <20:
mulhermenos = mulhermenos + 1
media = totalidade / 4
print('A média da idade do grupo é de {} '.format(media))
print('O nome do homem mais velho é {} e ele tem {} anos '.format(namevelho, hvelho))
print('A quantidade de mulheres com menos de 20 anos é de {} '.format(mulhermenos))
|
print('Bem vindo ao 53')
print('Crie um programa que leia uma frase qualquer e diga se ela é um palindromo')
# Palavra que é lida tanto na frente quanto atrás e dá igual
frase = str(input('Informe uma frase')).strip().upper()
palavras = frase.split() # Aqui ela divide todas as palavras
juntas = ''.join(palavras)
inverso = ''
for letra in range(len(juntas)-1,-1,-1):
inverso = inverso + juntas[letra]
print(juntas, inverso)
if inverso == juntas:
print('Temos um palindromo')
else:
print('Não é palindromo')
|
print('\033[32m ** Bem vindo ao Exercicio 37 **')
print('\033[31m ** Escreva um programa que leia um número inteiro qualquer e peça para o usuario escolher qual será a base de conversão\n'
'1- para binário, 2- para octal, 3- para hexadecimal')
print('\033[33m *** Resolução do Exercicio ***\033[m')
numero = int(input('Informe um número inteiro'))
print('''Escolha a base de conversão:
'1 - Binário'
'2 - Octal'
'3 - Hexadecimal''')
opçao = int(input('Informe sua opção: '))
if opçao == 1:
print('{} convertido para Binário é igual a {} '.format(numero, bin(numero)[2:]))
elif opçao == 2:
print('{} convertido para Octal é igual a {} '.format(numero, oct(numero)[2:]))
elif opçao == 3:
print('{} convertido para hexadecimal é igual a {} '.format(numero, hex(numero)[2:]))
else:
print('Opção invalida')
|
"""
PROBLEM 3 Objective
Fit a linear regression model with new features to predict # of tweets in the next
hour, from data in the PREVIOUS hour.
New Fetures from the paper in the preview:
1. number of tweets
2. number of retweets
3. number of followers
4. max numbber of followers
5. time of the data (24 hours represent the day)
6. ranking score
7. impression count
8. number of user
9. number of verified user
10. user mention
11. URL mention
12. list count
13. Max list
14. Friends count
15. number of long tweets
Attention: This is NOT the order the following program uses
Model: Random Forest
Explain your model's training accuracy and the significance of each feature using
the t-test and P-value results of fitting the model.
"""
import datetime
import help_functions
from sklearn.ensemble import RandomForestRegressor
import statsmodels.api as sm
# Remember this order!
features = ['ranking', 'friends_count', 'impression', 'URL', 'list_num', 'long_tweet', 'day_hour', 'tweets_count',
'verified_user', 'user_count', 'Max_list','retweets_count', 'followers', 'user_mention', 'max_followers']
input_files = ['gohawks', 'gopatriots', 'nfl', 'patriots', 'sb49', 'superbowl'] # tweet-data file names
#input_files = ['gohawks'] # tweet-data file names
for file_name in input_files:
tweets = open('./tweet_data/tweets_#{0}.txt'.format(file_name), 'rb')
######### Perform linear regression for each hashtag file #######
hour_wise_data = help_functions.features_extraction(tweets)
X, Y = [], []
print (hour_wise_data.values()[0])
for prev_hour in hour_wise_data.keys():
hour = datetime.datetime.strptime(prev_hour, "%Y-%m-%d %H:%M:%S")
next_hour = unicode(hour + datetime.timedelta(hours=1))
if next_hour in hour_wise_data.keys():
Y.append(hour_wise_data[next_hour]['tweets_count'])
X.append(hour_wise_data[prev_hour].values())
# random forest regression analysis
model = RandomForestRegressor(n_estimators=50, random_state=42)
results = model.fit(X, Y)
print('The accuracy is: ' + str(results.score(X, Y)))
print('Feature importance are: ' + str(results.feature_importances_))
t_val = results.feature_importances_
# lasso/ridge regression analysis
# X_const = sm.add_constant(X)
# LR_model = sm.OLS(Y, X_const)
# LR_results = LR_model.fit_regularized(L1_wt=0, alpha=0.01)
# print(LR_results.summary())
# print('P values: ' + str(LR_results.pvalues))
# print('T values: ' + str(LR_results.tvalues))
# t_val = LR_results.tvalues.tolist()
# t_val.pop(0) # pop the constant item
#
# t_val = [abs(i) for i in t_val]
# retrive indeces of top three T values in the order of third, second, first
indeces = sorted(range(len(t_val)), key=lambda i: t_val[i])[-3:]
print('top three features are:')
print(features[indeces[2]], features[indeces[1]], features[indeces[0]])
# Extract top three features
first_fea, sec_fea, third_fea = [], [], []
for i in range(len(X)):
first_fea.append(X[i][indeces[2]])
sec_fea.append(X[i][indeces[1]])
third_fea.append(X[i][indeces[0]])
# Plot diagrams:
help_functions.plot_feature(first_fea, Y, file_name, features[indeces[2]])
help_functions.plot_feature(sec_fea, Y, file_name, features[indeces[1]])
help_functions.plot_feature(third_fea, Y, file_name, features[indeces[0]])
print('-'*50)
# Top three features for different topics:
# gohawks: X1, X4, X12
# ('ranking', 'URL', 'user_mention')
# gopatriots: X1, X4, X13
# ('ranking', 'URL', 'max_followers')
# nfl: X12, X9, X7
# ('user_mention', 'user_count', 'tweets_count')
# patriots: X1, X11, X4
# ('ranking', 'followers', 'URL')
# sb49: X12, X11, X10
# ('user_mention', 'followers', 'retweets_count')
# Superbowl: X10, X4, X13
# ('retweets_count', 'URL', 'max_followers')
|
# coding: utf-8
import sqlite3
import csv
# connecting to the db and checking whether db exists: if not creates one (initiate_connection function)
conn = sqlite3.connect('url_data.db')
def initiate_connection():
try:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS urls(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
uuid INTEGER,
url TEXT,
content TEXT
)
""")
conn.commit()
except sqlite3.OperationalError:
print("[ERROR] Connection not initiated - terminate script")
conn.close()
exit()
def import_data(file_name):
try:
cursor = conn.cursor()
cursor.execute("DROP TABLE urls;",)
conn.commit()
cursor.execute("""
CREATE TABLE IF NOT EXISTS urls(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
uuid INTEGER,
url TEXT,
content TEXT
)
""")
conn.commit()
except sqlite3.Error:
print("[Error] - Could not delete existing data")
try:
cursor = conn.cursor()
with open(file_name, 'r') as fin:
# csv.DictReader uses first line in file for column headings
dr = csv.DictReader(fin) # comma is default delimiter
try:
to_db = [(i['uuid'], i['url']) for i in dr]
except KeyError as e:
print(e)
print("[Error] - Provided csv file does not follow the guidelines stated above")
conn.close()
exit()
cursor.executemany("INSERT INTO urls (uuid, url) VALUES (?, ?);", to_db)
conn.commit()
print("[OK] data loaded successfully")
except sqlite3.Error:
print("[ERROR] There was an error importing your data - terminate script")
conn.close()
exit()
def get_length():
cursor = conn.cursor()
cursor.execute("SELECT COUNT(id) FROM urls;")
data_size = cursor.fetchone()
return data_size[0]
def get_url(id_value):
cursor = conn.cursor()
cursor.execute("SELECT url FROM urls WHERE id = ?", (id_value,))
fetched_url = cursor.fetchone()
return fetched_url[0]
def get_last_range():
cursor = conn.cursor()
cursor.execute("SELECT MAX(id) FROM urls WHERE content IS NOT NULL;")
fetched_length = cursor.fetchone()
if fetched_length[0] is None:
return 1
else:
return fetched_length[0]
def upload_content(url_content, i):
cursor = conn.cursor()
cursor.execute("UPDATE urls SET content = ? WHERE id = ?", (url_content, i))
conn.commit()
print("[OK] Reached --- uploaded Nb :" + str(i))
|
# def cube_find(num):
# cube={}
# for i in range(1,num):
# cube[i]=i**3
# return cube
# print(cube_find(8))
#task5
user={}
name=input("what is your name : ")
age=input("what is your age : ")
gender=input("what is your gender : ")
fav_movie=input("what are your fav movie : ").split(",")
fav_song=input("what are your fav song : ").split(",")
user['name']=name
user['age']=age
user['gender']=gender
user['fav_movie']=fav_movie
user['fav_song']=fav_song
# print(user) simlple print
for keys,values in user.items():
print(f"{keys}:{values}") |
# #oop style of real project:
# class Person:
# def __init__(self,firstname,lastname,address,age):
# print("init called class")
# self.first_name=firstname
# self.last_name=lastname
# self.address=address
# self.age=age
# person1=Person('manisha','dhakal','bhairahawa',100)
# person2=Person('bhawana','thapa','butwal',200)
# person3=Person('bhawana','thapa magar','butwal',200)
# print(person1.first_name,person1.last_name)
# print(person2.age,person2.address)
# print(person3.last_name) |
class Circle:
pie=3.14
def __init__(self,radius):
# self.pi=pi
self.radius=radius
def circumtance(self):
return 2*Circle.pie*self.radius
circle1=Circle(5)
circle2=Circle(6)
print(circle1.circumtance())
print(circle2.circumtance())
|
# name=['manisha','cristina','manish']
# def function(l,target):
# for position,names in enumerate(l):
# if names==target:
# return position
# return -1
# print(function(name,'cristina'))
num=[1,2,3,4,5]
def power(a):
return a**2
# new_power=list(map(power,num))
new_power=list(map(lambda a:a**2,num))
print(new_power)
|
username=input("enter your number")
username=int(username)
total=0
i=1
while i<=username:
total+=i
i+=1
print(f"this is your number:{total}")
|
'''
write a python program to find those numbers which is divisbile
by 7 abd multiple of 5, between 1500 and 2700 (both included)
'''
number=[]
for i in range(1700,1500):
number.append(i/7)
number.append(i*5)
print(number)
#write a python program to construct the following pattern,using a nested
#for loop(
'''n=5
for i in range(0,n+1):
for j in range(i+1):
print("*",end="")
print()
for i in range(n,0,-1):
for j in range(i-1):
print("*",end=" ")
print()
'''
'''write a python program to guess a number between 1 to 9 go to
the editors
#note: user is prompted to enter a guess.
#if the user guesses wrong then the prompt appers again until the guess
is correct on the sucessful guess
user will get a well guessed "message",the program will exit'''
'''import random
guess_number=random.randint(1,9)
number=int(input("enter your guess number"))
guess=1
message_pass=False
while not message_pass:
if guess_number==number:
print(f"well guessed??guess the number{guess}times")
message_pass=True
else:
if number<guess_number:
print("you are right")
guess+=1
number=int(input("guess again:"))
if number < guess_number:
print("you are wrong")
guess += 1
number=int(input("guess again:"))'''
'''
wite a python program to convert temperatures to and from celsius,
fahrenheit.go to the editors
'''
'''
def celcius():
celcius=int(input("enter the temperature in celcius:"))
fahrenheit=(celcius*1.8)+32
print("temperature in fahrenheit is :")
def fahrenheit():
temperature = int(int("enter the celcius in temperature:"))
celcius=(fahrenheit-32)*5/9
celcius=fahrenheit()*5/9
print("celcius in fahrenheit is:")
'''
|
# def sum(a,b):
# if (type(a) is int) and (type(b) is int):
# return a+b
# raise TypeError('this is type error please input valid type')
# print(sum('1','2'))
class Animal:
def __init__(self,name):
self.name=name
def sound(self):
raise NotImplementedError('not implemented define function please define dog sound')
class Dog(Animal):
def __init__(self,name,bread):
super().__init__(name)
def sound(self):
return 'bhow bhow'
class Cat(Animal):
def __init__(self,name,bread):
super().__init__(name)
doggy=Dog('khushi','jap')
print(doggy.name)
print(doggy.sound())
|
print "I will now count my blessings"
# adds 25 and 30 divides by 6
print "Good Vibes", 25.0 + 30.0 / 6.0
# 100 minus 25 times 3 with 4 remaining
print "Good People", 100.0 - 25.0 * 3.0 % 4.0
print "Now I will count Karma:"
#
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?"
print 3.0 + 2.0 < 5.0 - 7.0
print "What is 3.0 + 2.0?", 3.0 + 2.0
print "What is 5.0 - 7.0?", 5.0 - 7.0
print "Oh, that's why it's false."
print "How about some more?"
print "Is it greater than?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
|
import unittest
from string_101 import *
class TestString(unittest.TestCase):
def test_rot1(self):
self.assertEqual(str_rot_13('abc'), 'nop')
def test_rot2(self):
self.assertEqual(str_rot_13('roof'), 'ebbs')
def test_rot3(self):
self.assertEqual(str_rot_13('gnat'), 'tang')
def test_translate1(self):
self.assertEqual(str_translate_101('banana', 'a', 'o'), 'bonono')
def test_translate2(self):
self.assertEqual(str_translate_101('aabbaabb', 'a', 'b'), 'bbbbbbbb')
def test_translate3(self):
self.assertEqual(str_translate_101('amanda', 'a', 'the'), 'themthendthe')
if __name__ == '__main__':
unittest.main()
|
def square_all(a):
return [x*x for x in a]
def add_n_all(a, n):
new_list = []
for i in a:
new_list.append(i + n)
return new_list
def even_or_odd_all(a):
new_list = []
index = 0
while index < len(a):
if a[index] % 2 == 0:
new_list.append(True)
else:
new_list.append(False)
index += 1
return new_list
|
"""
Program to calculate and display a user's bonus based on sales.
If sales are under $1,000, the user gets a 10% bonus.
If sales are $1,000 or over, the bonus is 15%.
"""
print("Enter Q to quit, enter any other key to calculate bonus.")
choice = input(">>> ").upper()
while choice != 'Q':
sales = float(input("Enter sales: $"))
if sales < 0:
print("Invalid sales input.")
pass
elif sales < 1000:
bonus = sales * 0.1
print("The bonus is ${:.2f}".format(bonus))
else:
bonus = sales * 0.15
print("The bonus is ${:.2f}".format(bonus))
print("Enter Q to quit, enter any other key to calculate again.")
choice = input(">>> ").upper()
print("Thank you")
|
# Task 1
name = input("Enter user's name: ")
out_file = open('names.txt', 'w')
print(name, file=out_file)
out_file.close()
# Task 2
in_file = open('names.txt', 'r')
username = in_file.read()
in_file.close()
print("Your name is", username)
# Task 3
in2_file = open('numbers.txt', 'r')
num1 = int(in2_file.readline())
num2 = int(in2_file.readline())
in2_file.close()
print(num1 + num2)
# Task 4
in3_file = open('numbers.txt', 'r')
total = 0
for lines in in3_file:
number = int(lines)
total = total + number
print(total)
|
class Auto:
# конструктор
def __init__(self, color):
self.brand = 'Opel'
self.model = 'Omega'
self.color = color
# деструктор
def __del__(self):
print(self.brand, self.model, '- удалено c памяти')
def info(self):
print(f'Бренд: {self.brand}\nМодель: {self.model}\nЦвет: {self.color}')
auto = Auto('Red')
auto.model = 'Cadet'
auto.info()
del auto
|
# Matrix Transpose
import numpy
m = numpy.mat([[1, 2], [3, 4]])
print("Matrix.Transpose:")
print(m.T)
''' Output:
Matrix.Transpose:
[[1 3]
[2 4]]
''' |
"""Simple autoencoder with generator
This is a simple autoencdoer (it has only one compressed layer). It uses a
generator to iterate over the data in an online fashion. This allows two
interesting things:
1. Changing the size of the samples easily; and
2. a method for data augmentation (look for the step argument)
"""
from keras.layers import Input, Dense, Reshape
from keras.models import Model
from keras.callbacks import TensorBoard
from generator.SimpleAutoencoderGenerator import SimpleAutoencoderGenerator
from functools import reduce
import operator
try:
import cPickle as pickle
except:
import pickle
import json
import h5py
class AutoencoderWithGenerator(object):
def __init__(self, hdf5_file, hdf5_group, input_dimension=(1000, 2),
encoding_dim=32):
"""Initialises the autoencoder
This is a simple autoencoder. It has only one layer for encoding and
one layer for decoding.
Args:
hdf5_file (str): name of the hdf5 file that contains the dataset
hdf5_group (str): name of the hdf5 group that contains the dataset
input_dimension: (int or tuple of ints) input dimension of the
network
encoding_dim (int): size of the encoded layer of the autoencoder
"""
self.__hdf5_file = hdf5_file
self.__hdf5_group = hdf5_group
self.__generator = SimpleAutoencoderGenerator(hdf5_file, hdf5_group)
self.__input_dimension = input_dimension # equivalent to sample_length
self.__encoding_dim = encoding_dim
# list to store the callbacks, initialised empty
self.__callbacks = []
self.__initialise(input_dimension=input_dimension, encoding_dim=encoding_dim)
def initialise(self, activation='relu', optimizer='adadelta',
loss='binary_crossentropy'):
"""Initialise the neural network
The neural network gets already initialised during __init__ so if
this methode is called the network behind is restarted.
"""
self.__initialise(input_dimension=self.__input_dimension,
encoding_dim=self.__encoding_dim,
activation=activation, optimizer=optimizer,
loss=loss)
def _culo(self):
print("culo")
def __initialise(self, input_dimension=(1000, 2), encoding_dim=32,
activation='relu', optimizer='adadelta',
loss='binary_crossentropy'):
"""Initialises the neural network
Creates an autoencoder type neural network following the
specifications of the arguments
Args:
input_dimension (int or tuple of ints): input dimension for the
network, if it is a tuple the input is flattened to only
one dimension
encoding_dim (int): compressed size
"""
if len(input_dimension) > 1:
flattened_dimension = (reduce(operator.mul, input_dimension),)
else:
flattened_dimension = input_dimension
print("flatten dim", flattened_dimension)
# this is the size of our encoded representations
# this is our input placeholder
input_tensor = Input(shape=input_dimension)
print("here",input_tensor._keras_shape)
# reshape if necessary, encode
if len(input_dimension) > 1:
input_reshape = Reshape(flattened_dimension,
input_shape=input_dimension,
name="input_reshape")(
input_tensor)
encoded = Dense(encoding_dim, activation=activation,
name="encoder")(input_reshape)
else:
encoded = Dense(encoding_dim, activation=activation, name="encoder")(
input_tensor)
# decode, reshape if necessary
if len(input_dimension) > 1:
decoded = Dense(flattened_dimension[0], activation=activation,
name="decoder"
)(encoded)
output = Reshape(input_dimension,
input_shape=flattened_dimension,
name="output_reshape")(
decoded)
else:
decoded = Dense(flattened_dimension, activation=activation,
name="decoder")(encoded)
output = decoded
# this model maps an input to its reconstruction
self.__autoencoder = Model(input_tensor, output)
self.__autoencoder.compile(optimizer=optimizer, loss=loss)
def song_section_to_chunk_section(self, data, song_section):
"""Converts a song section into a chunck section
Sections represent portions of the dataset in a tuple format
(start of section, end of section)
(start index, end index)
but the indexes themselves can represent a song or just a chunk of the
dataset. This fuction gets the former and converts into the latter,
which is the format needed for training.
Args:
data: dataset from which metadata will be retreived
song_section: tuple (start index, end index)
Returns:
(section chunk start index, section chunk end index)
"""
songs_lengths = [int(length) for length in data.attrs["songs_lengths"]]
start_index = sum(songs_lengths[0:song_section[0]])
end_index = sum(songs_lengths[0:song_section[1]+1])
return (start_index, end_index)
def callback_add_tensorboard(self, log_dir='/tmp/autoencoder',
histogram_freq=1, write_graph=True,
batch_freq=None, variables=['loss', 'val_loss']):
from callbacks.customTensorBoard import customTensorBoard
if batch_freq == None: # add standard callback
tensorboard_callback = TensorBoard(log_dir=log_dir,
histogram_freq=histogram_freq,
write_graph=write_graph)
# remove a posible tensorboard callback from the list
# there is no point into keeping several callbacks to tensorflow
# self.__callbacks = [callback for callback in self.__callbacks if not
# type(callback) == type(tensorboard_callback)]
self.__callbacks.append(tensorboard_callback)
else: # add custom callback
tensorboard_callback = customTensorBoard(log_dir=log_dir,
histogram_freq=histogram_freq,
write_graph=write_graph,
batch_freq=batch_freq,
variables=variables)
# remove a posible tensorboard callback from the list
# there is no point into keeping several callbacks to tensorflow
# self.__callbacks = [callback for callback in self.__callbacks if not
# type(callback) == type(tensorboard_callback)]
self.__callbacks.append(tensorboard_callback)
def callback_add_earlystopping(self, monitor="val_loss", patience=3):
from keras.callbacks import EarlyStopping
earlystopping_callback = EarlyStopping(monitor=monitor,
patience=patience, mode='min')
self.__callbacks = [callback for callback in self.__callbacks if not
type(callback) == type(earlystopping_callback)]
self.__callbacks.append(earlystopping_callback)
def callback_add_modelcheckpoint(self, filepath, period=1):
from keras.callbacks import ModelCheckpoint
modelcheckpoint_callback = ModelCheckpoint(filepath, period=period)
self.__callbacks = [callback for callback in self.__callbacks if not
type(callback) == type(modelcheckpoint_callback)]
self.__callbacks.append(modelcheckpoint_callback)
def fit_generator(self, batch_size=1000, epochs=1, step=None,
train_section=None, val_section=None, history_file=None):
if step == None: step = self.__input_dimension[0]
if val_section:
val_generator = SimpleAutoencoderGenerator(self.__hdf5_file,
self.__hdf5_group)
val_generator.configure(sample_length=self.__input_dimension[0],
batch_size=batch_size,
step=step,
section=val_section)
val_data = val_generator.generate_samples(randomise=False)
val_steps = val_generator.get_nbatches_in_epoch()
else:
val_data = None
val_steps = None
callbacks = self.__callbacks if not self.__callbacks == [] else None
print("Fit generator, train section", train_section)
print("validation_steps", val_steps)
self.__generator.configure(sample_length=self.__input_dimension[0],
batch_size=batch_size,
step=step,
section=train_section)
print(self.__generator.get_nbatches_in_epoch())
history = self.__autoencoder.fit_generator(
self.__generator.generate_samples(),
self.__generator.get_nbatches_in_epoch(),
validation_data=val_data,
validation_steps=val_steps,
epochs=epochs,
callbacks=callbacks,
verbose=1
)
if history_file is not None:
pickle(history.history, history_file)
def train_dataset(self, batch_size=100, epochs=1, step=None,
validation=True):
"""Trains the dataset using the train section
Gets the train section from the dataset and trains it with that section
Args:
batch_size (int): size of the batch
epochs (int): number of epochs
step (int): offset between samples
"""
if step == None: step = self.__input_dimension[0]
# get info of the training section
data = self.__generator.h5g["data"]
train_section = data.attrs["train_set"]
train_section = tuple(train_section)
print("Train section", train_section)
train_section = self.song_section_to_chunk_section(data, train_section)
print("Train section", train_section)
if validation:
val_section = data.attrs["val_set"]
val_section = tuple(val_section)
print("Val section", val_section)
val_section = self.song_section_to_chunk_section(data, val_section)
print("Val section", val_section)
else:
val_section = None
# train
self.fit_generator(batch_size=batch_size, epochs=epochs, step=step,
train_section=train_section, val_section=val_section)
def validate_dataset(self):
pass
def test_dataset(self):
pass
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Autoencoder with generator")
# arguments for gather_dataset_online
parser.add_argument("hdf5_file", help="File containing the dataset file", type=str)
parser.add_argument("--hdf5-group", help="Group name with the dataset", type=str)
parser.add_argument("--dim", help="Input dimensions. Number of audio "
"samples per sample", type=int,
required=True)
parser.add_argument("--encoded_size", help="The encoded size", type=int,
default=32)
dargs = parser.parse_args()
hdf5_file = dargs.hdf5_file
hdf5_group = dargs.hdf5_group
dimension = dargs.dim
encoded_size = dargs.encoded_size
autoencoder = AutoencoderWithGenerator(hdf5_file, hdf5_group,
input_dimension=(dimension, 2),
encoding_dim=encoded_size)
|
num1=int(input("Enter The First Number :: "))
num2=int(input("Enter The Second Number :: "))
reminder=0
if num1>num2:
reminder=num1%num2
else:
reminder=num2%num1
temp=reminder
while reminder!=0:
temp=reminder
if num1>num2:
reminder=num2%reminder
else:
reminder=num1%reminder
if num1>num2:
num2=temp
else:
num1=temp
if reminder==0:
if num1>num2:
print("GCD = ",num2)
else:
print("GCD = ",num1)
else:
print("GCD = ",temp)
|
num = input("Enter the number : ")
sum1 = 0
for itr in range(1,num+1):
sum1=0
for jtr in range(1,itr/2+1):
if itr%jtr==0:
sum1 = sum1 + jtr
if itr == sum1 or itr ==1:
print(itr)
|
"""*Program 3: Write a Program to print table of 2.
Output: 2 4 6 8 10 12 14 16 18 20"""
for itr in range(1,11):
print(itr*2)
|
'''
Problem Statement
Write a Program to calculate Velocity of particle in the space having Distance & Time Entered By User
'''
dist = int(input("Enter distance in metres \n"))
time = int(input("Enter time in seconds \n"))
vel = dist//time
print("The Velocity of a Particle roaming In space is ",vel," m/s")
|
''' Program 3: Write a Program to calculate Velocity of particle in the space having
Distance & Time Entered By User.'''
Distance = int(input("Distance : "))
Time = int(input("Time : "))
Velocity = Distance/Time
print("The Velocity of particle moving in space ",Velocity, " m/s") |
try:
n = int(input("Enter Size "))
except ValueError as e:
exit(0)
if(n <= 0):
exit(0)
for i in range(1,n+1):
for j in range(1,n-i+2):
print(chr(64 + i), end = "\t")
print()
|
'''
Problem Statement
Write a Program that accepts Two integers from user and prints the series of factorial of all numbers between those two inputs
A factorial is calculated by multiplying all the numbers including the number itself till 1
Example Factorial of 4 = 4*3*2*1 = 24
'''
start = int(input("Enter start value\n"))
end = int(input("Enter end value\n"))
print("Series of Factorial of numbers in the range is")
for x in range(start,end+1):
fact = 1
for y in range (1,x+1):
fact = fact * y
print("Factorial of ",x," : ",fact)
|
''' Run this program with python3'''
try:
a = int(input("Enter Size : "))
except ValueError:
print('Not a Number')
exit(0)
if a < 0:
print("Not allowed");
else :
for i in range(1 , a * a + 1):
if i % a == 0 :
print(0)
else:
print(0, end="\t")
|
"""
/*
*
Program 1: Write a Program to Find Maximum between two numbers
Input: 1 2
Output: 2 is Max number among 1 & 2
*
*/
"""
a = 2
b = 3
if a>b:
print(str(a)+" is greater then "+str(b))
else:
print(str(b)+" is greater then "+str(a))
|
num = 1;
for i in range(4):
for j in range(i + 1):
print(num * num, end = " ")
num += 1;
print()
|
'''Program 5: Write a Program that accepts Two integers from user and prints
maximum number from them.'''
num1, num2 = [int(i) for i in input("Input : ").split()]
if(num1 > num2):
print("Max : ", num1)
elif(num1 == num2):
print("Equal")
else:
print("Max : ", num2)
|
''' Program 4: Write a Program that accepts an integer from user and print table
of that number.'''
tableof = int(input("Enter a Number : "))
for num in range(1,11):
print(tableof * num,end =" ")
print()
|
var1=int(input("enter first integer "))
var2=int(input("enter second integer "))
mul=var1*var2
print("Multiplication is ",mul)
if(var1 > var2):
div=var1//var2
print("Division is ",div)
elif(var2>var1):
div=var2//var1
print("Division is ",div)
|
fact = 1
num1 = int(input("Input : "))
for i in range(num1):
fact *= i + 1
print("Fact : ", fact) if num1 >= 0 else print("Enter valid num.")
|
"""
Program 4 : Write a Program to print First 50 Even Numbers
Output: 2 4 6 . . . 100
"""
print("First 50 even numbers")
for itr in range(101):
if itr%2==0:
print(itr)
|
'''
Write a Program to that prints series of Even numbers in reverse
order from the limiting number entered by user.
'''
num=int(input("Enter the number:"))
for x in range(num,-1,-1):
if(x % 2 == 0):
print(x,end=" ")
print()
|
''' Program 3: Write a Program to Print following Pattern.
A A A A A
B B B B
C C C
D D
E
'''
a = 64
for i in range(1,6):
a+=1
for j in range(1,6):
if i + j >= 7:
print(" ",end=" ")
else:
print(chr(a),end=" ")
print() |
'''
Program 1: Write a program that accepts two integers from user and prints
addition & Subtraction of them.
{Note: checks for greater number to subtracts with while subtracting numbers}
Input: 10 20
Output:
Addition is 20
Subtraction is 10
'''
var1=int(input("enter first integer "))
var2=int(input("enter second integer "))
add=var1+var2
print("Addition is ",add)
if(var1 > var2):
sub=var1-var2
print("Subtraction is ",sub)
elif(var2>var1):
sub=var2-var1
print("Subtraction is ",sub)
|
def gcd(n1 : int, n2: int)-> int:
if(n2 != 0):
return gcd(n2, n1 % n2)
else:
return n1
try:
n1 = int(input("Enter Number : "))
n2 = int(input("Enter Number : "))
except ValueError as e:
exit(0)
if(n1 < 0 or n2 < 0):
exit(0)
print("The GCD of {} and {} is {}".format(n1,n2,gcd(n1, n2)))
|
''' Program 4: Write a Program to Print following Pattern.
1
8 27
64 125 216
343 512 729 1000 '''
a = 1
for i in range(1,5):
for j in range(1,5):
if j <= i:
print(a * a * a,end=" ")
a+=1
print() |
"""
Program 3: Write a Program to Find whether the number Is Even or Odd
Input: 4
Output: 4 is an Even Number!
"""
a = 8
if a%2==0:
print(str(a)+" is even number")
else:
print(str(a)+" is odd number")
|
num = int(input("Input : "))
sum = 0
for i in range(num):
sum += i + 1
print("Sum : ", sum)
|
"""
Program 2: Write a Program to check whether the number ins Negative,
Positive or equal to Zero.
Input: -2
Output: -2 is the negative number
"""
a = -2
if a<0:
print(str(a)+" is negative")
else:
print(str(a)+" is positive")
|
n = 0
try:
n = int(input("Enter Size : "))
if(n < 0):
print("Enter Positive Number")
exit(0)
except ValueError as e:
print("Enter valid Number")
pass
flag = 1
for i in range(n, 0, -1) :
for j in range(0, n-i+1):
print(flag*flag, end = "\t")
flag+=1;
print()
|
''' Program 3: Write a Program to that accepts two integers from user and
calculates the Quotient & Reminder from their division '''
a,b = input("Input : ").split()
c = int (a)
d = int (b)
print("Quotient : ",c/d)
print("Remainder : ",c%d) |
'''
Problem Statement
Write a Program that accepts an integer from user and prints its second successor and second predecessor.
'''
num = int(input("Enter a number \n"))
print("The Second Predecessor = ",num-2)
print("The Second Successor = ",num+2)
|
try:
a = int(input("Enter Size : "))
except ValueError as e:
print("Invalid")
exit(0)
pass
k = 1
for i in range(1, a + 1):
for j in range(1, i + 1):
print(k, end = ' ')
k+=1
print()
|
try:
l = int(input("Enter length : "))
b = int(input("Enter breadth : "))
except ValueError as e:
exit(0)
if(l < 0 or b < 0 or l < b):
exit(0);
print("Area Of Rectangle = ",l * b, "sq unit")
|
"""
/*Program 5: Write a C program to calculate the factorial of a given number.
Input: 5
Output:
The Factorial of 5 is: 120*/
"""
num = 5
fact = 1
for itr in range(2,num+1):
fact = fact*itr
print("The Factorial of 5 is "+str(fact))
|
'''Run using python3'''
for i in range(3,101) :
if(i % 4 == 0 and i % 7 == 0):
print(i, end = ' ')
print() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.