repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
jsourabh1/6Days6Company | Walmart/Transform_to_sum_tree.py |
'''
# Node Class:
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
'''
class Solution:
def helper(self,root):
if not root:
return 0
left=self.helper(root.left)
right=self.helper(roo... |
jsourabh1/6Days6Company | Intuit/number_of_boomerangs.py | from typing import List
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0
for a, b in points:
counter = {}
for i, j in points:
key = (a-i)**2+(j-b)**2
if key in counter:
ans += 2*coun... |
jsourabh1/6Days6Company | Goldman_Sachs/array_pair_sum_divisibility.py | from collections import defaultdict
class Solution:
def canPair(self, arr, k):
# Code here
for i in range(len(arr)):
arr[i] = arr[i] % k
dict_1 = defaultdict(lambda: 0)
# print(arr)
for i in arr:
if i == 0:
if dict_1[i] > 0:
... |
jsourabh1/6Days6Company | Amazon/ColName.py | <reponame>jsourabh1/6Days6Company<gh_stars>1-10
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
class Solution:
def colName(self, num):
global alpha
# your code here
if num < 26:
return alpha[num-1]
else:
q, r = num//26, num % 26
if r == 0:
... |
jsourabh1/6Days6Company | Goldman_Sachs/Number_following_a_pattern.py | class Solution:
def printMinNumberForPattern(ob, S):
# code here
count = 1
stack = []
ans = ""
for i in S:
if i == "D":
stack.append(count)
count += 1
else:
stack.append(count)
coun... |
jsourabh1/6Days6Company | Microsoft/Stickler_theif.py | <reponame>jsourabh1/6Days6Company
class Solution:
#Function to find the maximum money the thief can get.
def FindMaxSum(self,a, n):
# code here
if n<=2:
ans=0
for i in range(n):
ans=max(ans,a[i])
return ans
... |
jsourabh1/6Days6Company | Goldman_Sachs/gcd_of_string.py | import math
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1+str2 != str2+str1:
return ""
ans = ""
for i in range(min(len(str2), len(str1))):
if str1[i] == str2[i]:
ans += str1[i]
if not ans:
return... |
jsourabh1/6Days6Company | Walmart/Power_of_number.py | # import math
class Solution:
#Complete this function
def power(self,x,y):
#Your code here
if(y == 0): return 1
temp = self.power(x, int(y / 2))
if (y % 2 == 0):
return (temp * temp)%((10**9)+7)
else:
if(y > 0): return (x * temp * ... |
jsourabh1/6Days6Company | Goldman_Sachs/Total_decode_ways.py | #TLE solution
# import sys
start="a"
dict_1={}
for i in range(27):
dict_1[i+1]=chr(ord(start)+i)
print(dict_1)
# class Solution:
# def CountWays(self, str):
# # Code here
# def helper(ans, string, index):
# nonlocal str
# print(string, index, ans)
# if index... |
jsourabh1/6Days6Company | Intuit/construct_the_quad_tree.py | <gh_stars>1-10
class Solution:
def construct(self, grid: 'List[List[int]]') -> 'Node':
root = Node(True, True, None, None, None, None)
if len(set([item for row in grid for item in row])) == 1:
root.val = bool(grid[0][0])
else:
root.isLeaf = False
size = le... |
jsourabh1/6Days6Company | Adobe/ATOI.py | class Solution:
def atoi(self, string):
ans = 0
first = 1
for i in string[::-1]:
if i == "-":
ans = ans-2*ans
elif not i.isnumeric():
return -1
else:
ans += int(i)*first
first *= 10
... |
jsourabh1/6Days6Company | Microsoft/Spiral_matrix.py | <reponame>jsourabh1/6Days6Company
class Solution:
#Function to return a list of integers denoting spiral traversal of matrix.
def spirallyTraverse(self, matrix, r, c):
# code here
row = col = 0
rowend = r-1
colend = c-1
ans = []
while row <= rowend and col <= c... |
jsourabh1/6Days6Company | Microsoft/Stock_span.py | <filename>Microsoft/Stock_span.py
import sys
import io
import atexit
class Solution:
#Function to calculate the span of stock’s price for all n days.
def calculateSpan(self, a, n):
arr = []
for i in a:
arr.append([i, 1])
stack = []
ans = []
for i, cos... |
jsourabh1/6Days6Company | Microsoft/generate_binary_binary_number.py |
#Function to generate binary numbers from 1 to N using a queue.
def generate(N):
# code hereans.append(bin()
ans=[]
for i in range(1,N+1):
ans.append(bin(i)[2:])
return ans
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
i... |
jsourabh1/6Days6Company | Walmart/fint_array_given_subset_Sum.py | class Solution:
def recoverArray(self, n: int, sums: List[int]) -> List[int]:
sums = sorted(sums, reverse=True)
ans = []
def remove(sumset, ele):
if sumset[ele] > 1:
sumset[ele] -= 1
else:
del sumset[ele]
while len(sums) > 2:
... |
jsourabh1/6Days6Company | Intuit/pacific_and_altlantic_water.py | class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
row=len(heights)
col=len(heights[0])
pacific=[[False]*(col) for i in range(row)]
atlantic=[[False]*(col) for i in range(row)]
def dfs(grid,... |
jsourabh1/6Days6Company | Adobe/smallest_range_K_list.py | from heapq import *
class Solution:
def smallestRange(self, arr, n, k):
# code here
# print the smallest range in a new line
maxx=-float("inf")
minn=float("inf")
min_range=[float("inf"),0,0]
heap=[]
heapify(heap)
for i in range(k):
... |
jsourabh1/6Days6Company | Goldman_Sachs/Anagrams.py | <reponame>jsourabh1/6Days6Company<filename>Goldman_Sachs/Anagrams.py
from collections import defaultdict
def Anagrams(words,n):
dict_1=defaultdict(list)
for i in words:
dict_1["".join(sorted(i))].append(i)
return dict_1.values()
#{
# Driver Code Starts
#In... |
jsourabh1/6Days6Company | Adobe/Leaders_in_array.py |
class Solution:
#Back-end complete function Template for Python 3
#Function to find the leaders in the array.
def leaders(self, A, N):
#Code here
stack=[]
ans=[]
for i in range(N-1,-1,-1):
while stack and stack[-1]<=A[i]:
... |
jsourabh1/6Days6Company | Goldman_Sachs/Find_the_position_of_Mth_item.py |
class Solution:
def findPosition(self, N, M, K):
if N == 1:
return N
# code here
temp = (M % N+K-1)
return temp if temp <= N else temp % N
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):
... |
jsourabh1/6Days6Company | Amazon/Maximum_profit.py |
class Solution:
def maxProfit(self, k, n, price):
# code here
# Bottom-up DP approach
profit = [[0 for i in range(n + 1)]
for j in range(k + 1)]
# Fill the table in bottom-up fashion
for i in range(1, k + 1):
prevDiff = float('-inf'... |
jsourabh1/6Days6Company | Goldman_Sachs/Run_length_encoding.py | <reponame>jsourabh1/6Days6Company<filename>Goldman_Sachs/Run_length_encoding.py<gh_stars>1-10
#Function should return complete string
def encode(arr):
# Code here
count=1
ans=""
for i in range(1,len(arr)):
if arr[i-1]!=arr[i]:
ans+=arr[i-1]+str(count)
... |
jsourabh1/6Days6Company | Goldman_Sachs/Decode_the_string.py |
class Solution:
def decodedString(self, s):
# code here
stack = []
curString = ""
curNum = 0
for c in s:
if c == '[':
stack.append(curString)
stack.append(curNum)
curString = ''
curNum = 0
... |
jsourabh1/6Days6Company | Amazon/Nuts_bolts_problem.py | <reponame>jsourabh1/6Days6Company
from typing import List
# Method to print the array
def printArray(arr: List[str]) -> None:
for i in range(6):
print(" {}".format(arr[i]), end=" ")
print()
# Similar to standard partition method.
# Here we pass the pivot element too
# instead of choosing it inside the... |
jsourabh1/6Days6Company | Amazon/Longest_mountain_in_array.py | class Solution(object):
def longestMountain(self, A):
N = len(A)
ans = base = 0
while base < N:
end = base
if end + 1 < N and A[end] < A[end + 1]: # if base is a left-boundary
#set end to the peak of this potential mountain
while end+... |
jsourabh1/6Days6Company | Microsoft/unit_aera.py | class Solution:
#Function to find unit area of the largest region of 1s.
def findMaxArea(self, grid):
#Code here
def dfs(i,j,grid):
if i >=0 and j >=0 and i < len(grid) and j <len(grid[i]) and grid[i][j] == 1:
# return 0
... |
jsourabh1/6Days6Company | Adobe/Next_higher_palindromic_number.py | <gh_stars>1-10
from collections import Counter
class Solution:
def nextPalin(self, N):
#code here
arr = list(map(int, N.strip()))
if len(arr) == 1:
return -1
n = len(arr)
extra = -1
if n % 2 != 0:
extra = arr[n//2]
#make a dupli... |
jsourabh1/6Days6Company | Adobe/subarry_with_given_sum.py | <reponame>jsourabh1/6Days6Company
import math
from collections import defaultdict
#Function to find a continuous sub-array which adds up to a given number.
class Solution:
def subArraySum(self, arr, n, s):
start = 0
curr_sum = arr[0]
for i in range(1, n+1):
while curr_sum > s... |
jsourabh1/6Days6Company | Goldman_Sachs/Find_reapeating_and_missing.py | <gh_stars>1-10
class Solution:
def findTwoElement(self, arr, n):
ans = [False]*(n+1)
first = 0
for i in arr:
if ans[i] == True:
first = i
5
ans[i] = True
second = 0
for i in range(1, n+1):
if ans[i] == Fal... |
jsourabh1/6Days6Company | Intuit/find_the_missing_no_in_string.py | # function should return the missing number
# else return -1
def missingNumber(inp):
# Code here
def startswith(idx, num):
# quick startswith function to avoid string slicing
num = str(num)
if len(num) > len(inp)-idx:return False
i = 0
while idx < len(inp) and ... |
jsourabh1/6Days6Company | Microsoft/Minimum sum partition.py | <gh_stars>1-10
class Solution:
def minDifference(self, arr, n):
ans = (1+sum(arr))//2
dp = [[-1]*(ans+1) for i in range(n+1)]
for i in range(n+1):
for j in range(ans+1):
if i == 0 and j == 0:
dp[i][j] = 1
elif j == 0:
... |
jsourabh1/6Days6Company | Adobe/Compare_versions.py | <gh_stars>1-10
from typing import List
import re
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
list1=list(map(str,version1.split(".")))
list2=list(map(str,version2.split(".")))
# print(list1)
if len(list1)<len(list2):
... |
jsourabh1/6Days6Company | Intuit/Course_schedule_II.py | from collections import defaultdict
class Solution:
def findOrder(self, num: int, prer: List[List[int]]) -> List[int]:
graph = defaultdict(list)
indegree = [0]*num
for first, second in prer:
graph[first].append(second)
indegree[second] += 1
# print(graph... |
jsourabh1/6Days6Company | Goldman_Sachs/ugly_number.py | <reponame>jsourabh1/6Days6Company<filename>Goldman_Sachs/ugly_number.py
class Solution:
def getNthUglyNo(self,n):
# code here
dp=[1]*n
i2=i3=i5=0
for i in range(1,n):
multiple_2=dp[i2]*2
multiple_3=dp[i3]*3
multiple_5=... |
jsourabh1/6Days6Company | Walmart/Stone_game.py | <reponame>jsourabh1/6Days6Company<filename>Walmart/Stone_game.py
# dp approach
class Solution:
def stoneGame(self, piles):
N = len(piles)
def dp(i, j):
# The value of the game [piles[i], piles[i+1], ..., piles[j]].
if i > j:
return 0
pa... |
jsourabh1/6Days6Company | Microsoft/count_the_subtree_with_given_sum.py |
'''
# Node Class:
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
'''
#Function to count number of subtrees having sum equal to given sum.
def countSubtreesWithSumX(root, X):
ans=0
def helper(root,X):
nonlocal ans
... |
jsourabh1/6Days6Company | Microsoft/Alien_dictionary.py | <filename>Microsoft/Alien_dictionary.py
from collections import defaultdict
class Solution:
def findOrder(self,words, n, k):
# code here
graph={c:set() for i in words for c in i}
for i in range(len(words)-1):
w1,w2=words[i],words[i+1]
... |
jsourabh1/6Days6Company | Amazon/Delete_N_nodes_after_M_nodes.py | <reponame>jsourabh1/6Days6Company<gh_stars>1-10
# Function shouldn't return anything
'''
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
'''
class Solution:
def skipMdeleteN(self, head, M, N):
# Code here
... |
jsourabh1/6Days6Company | Walmart/random_points_on_circle.py | class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.RAD = radius
self.XC = x_center
self.YC = y_center
def randPoint(self) -> List[float]:
ang = random.uniform(0, 1) * 2 * math.pi
hyp = sqrt(random.uniform(0, 1)) * self.RAD
ad... |
jsourabh1/6Days6Company | Adobe/Generate_parentheses.py |
# first approach
class Solution:
def generateParenthesis(self, n: int):
def generate(arr):
nonlocal ans, n
if len(arr) == 2*n:
if valid(arr):
ans.append("".join(arr))
return
else:
arr.append("(")
... |
jsourabh1/6Days6Company | Intuit/minimum_swaps_to_binary_grid.py | <gh_stars>1-10
class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
swaps = 0
zeroesNeeded = len(grid)-1
start = 1
for i in range(len(grid)):
temp = i
while temp < len(grid) and grid[temp][start:] != [0]*zeroesNeeded:
temp += 1
... |
jsourabh1/6Days6Company | Intuit/Word_serach.py | <filename>Intuit/Word_serach.py
class Solution:
def isWordExist(self, board, word):
#Code here
def helper(grid,row,col,string):
if not string:
return True
# [[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1]]
... |
jsourabh1/6Days6Company | Goldman_Sachs/count_the_subarray_.py | <filename>Goldman_Sachs/count_the_subarray_.py<gh_stars>1-10
class Solution:
def countSubArrayProductLessThanK(self, a, n, k):
#Code here
i=j=0
product=1
count=0
while i<n:
product*=a[i]
while j<i and product>=k:
product//=a[j]
... |
jsourabh1/6Days6Company | Amazon/IPL2021.py | <reponame>jsourabh1/6Days6Company<gh_stars>1-10
from heapq import *
class Solution:
def max_of_subarrays(self,arr,n,k):
'''
you can use collections module here.
:param a: given array
:param n: size of array
:param k: value of k
:return: A list of required values
... |
jsourabh1/6Days6Company | Intuit/Number_of_provinces.py | from collections import defaultdict
class Solution:
def findCircleNum(self, grid: List[List[int]]) -> int:
graph = defaultdict(list)
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j] == 1:
graph[i].append(j)
# print(graph... |
jsourabh1/6Days6Company | Adobe/minimum_operation_to_convert.py | <gh_stars>1-10
# Python 3
from bisect import bisect_left
# Function to find LIS in O(nlogn) time
def LongestIncreasingSubsequenceLength(nums):
sub = []
for x in nums:
if len(sub) == 0 or sub[-1] < x:
sub.append(x)
else:
# Find the index of the smallest number >= x
... |
jsourabh1/6Days6Company | Adobe/Number_of_distinct_word.py | <reponame>jsourabh1/6Days6Company
def power(x,y,p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if (y & 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
class Solution:
def kvowelwords(self, N, K):
# code here
... |
jsourabh1/6Days6Company | Microsoft/Bridges_in_the_graph.py | <reponame>jsourabh1/6Days6Company<filename>Microsoft/Bridges_in_the_graph.py
import sys
from collections import OrderedDict
class Solution:
#Function to find if the given edge is a bridge in graph.
def bfs(self, vertex, adj, node):
# ans.append(node)
for i in adj[node]:
if i n... |
jsourabh1/6Days6Company | Walmart/maximum_sum_probability.py | <reponame>jsourabh1/6Days6Company
from collections import defaultdict
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
graph=defaultdict(list)
index=0
for i,j in edges:
g... |
jsourabh1/6Days6Company | Amazon/Rotten_oranges.py | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
queue = []
row = [-1, 0, 1, 0]
col = [0, -1, 0, 1]
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 2:
queue.append([... |
jsourabh1/6Days6Company | Goldman_Sachs/Overlapping_rectangles.py | <reponame>jsourabh1/6Days6Company<filename>Goldman_Sachs/Overlapping_rectangles.py<gh_stars>1-10
class Solution:
def doOverlap(self, l1,r1,l2,r2):
#code here
#lower triangle
if l2[1]<r1[1]:
return 0
#upper triangle
if l1[1]... |
jsourabh1/6Days6Company | Walmart/number_of_unique_paths.py |
from ensurepip import version
# Memozation version
class Solution:
#Function to find total number of unique paths.
def NumberOfPaths(self, m, n):
#code here
if m == 1 and n == 1:
return 1
dp = [[-1]*(n+1) for i in range(m+1)]
def helper(first, second):
... |
jsourabh1/6Days6Company | Intuit/Find_in_the_mountain_Array.py | <reponame>jsourabh1/6Days6Company<filename>Intuit/Find_in_the_mountain_Array.py
# """
# This is MountainArray's API interface.
# You should not implement it, or speculate about its implementation
# """
#class MountainArray:
# def get(self, index: int) -> int:
# def length(self) -> int:
class Solution:
def fi... |
jsourabh1/6Days6Company | Adobe/Pots_of_gold_game.py | <reponame>jsourabh1/6Days6Company<gh_stars>1-10
class Solution:
def maxCoins(self,arr, n):
# Code here
dp=[[0]*(n) for i in range(n)]
for k in range(n):
i=0
j=k
while i<n and j<n:
# print(i,j)
... |
jsourabh1/6Days6Company | Walmart/k_th_largest_number_in_array.py | from heapq import *
class Solution:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
heap = []
for i in range(len(nums)):
if k > 0:
heappush(heap, int(nums[i]))
k -= 1
else:
heappushpop(heap, int(nums[i]))
... |
jsourabh1/6Days6Company | Intuit/minimum_partition_sum.py |
# Brute force
class Solution:
def minDifference(self, arr, n):
# code here
ans = float("inf")
def helper(arr, a, b, index):
nonlocal ans
if index == len(arr):
ans = min(ans, abs(a-b))
return
helper(arr, a+arr[index], ... |
jsourabh1/6Days6Company | Intuit/capacity_to_ship_packages.py | class Solution:
def shipWithinDays(self, arr: List[int], m: int) -> int:
low = max(arr)
high = sum(arr)
ans = 0
while low <= high:
mid = (low + high) // 2
count = 1
summ = 0
for i in arr:
if (summ + i) > mid:
... |
jsourabh1/6Days6Company | Microsoft/Possible_words_from_phone.py |
import math
class Solution:
#Function to find list of all words possible by pressing given numbers.
def possibleWords(self, a, N):
#Your code here
dict_1 = {2: "abc", 3: "def", 4: "ghi", 5: "jkl",
6: "mno", 7: "pqrs", 8: "tuv", 9: "wxyz"}
ans = []
def help... |
jsourabh1/6Days6Company | Microsoft/Prerequiste_task.py | from collections import defaultdict
class Solution:
def isPossible(self, num, prer):
#code here
graph = defaultdict(list)
indegree = [0]*num
for first, second in prer:
graph[first].append(second)
indegree[second] += 1
# print(graph)
q = [... |
jsourabh1/6Days6Company | Goldman_Sachs/find_maximum_number.py | # We have given 10Million enteries and we have to find the 10 maximum number so we have different methods
# 1) First Method:- Sorting(O(nlogn))
def solve(arr):
arr.sort(reverse=True)
return arr[:10]
#2) Second Method :- using priority Queue (nlogK) where k=10 is the size of the queue
from heapq import *
de... |
jsourabh1/6Days6Company | Walmart/Maximum_height_of_tee.py |
class Solution:
def height(self, N):
# code here
# Sum of dots for height H <= N
# H*(H + 1)/2 <= N
# H*H + H – 2*N <= 0
# Now by Quadratic formula
# (ignoring negative root)
# Maximum H can be(-1 + √(1 + 8N)) / 2
ans = (-1+int((1+8*N)**0.5))//2
... |
jsourabh1/6Days6Company | Walmart/sorted_subsequence.py |
import sys
class Solution:
def find3number(self, A, n):
# code here
n = len(arr)
# Index of maximum element from right side
max = n-1
# Index of minimum element from left side
min = 0
# Create an array that will store
# index of a smaller element on left s... |
jsourabh1/6Days6Company | Walmart/Removed_colored_pieces.py | <reponame>jsourabh1/6Days6Company
class Solution:
def winnerOfGame(self, colors: str) -> bool:
# print(colors[:-1])
count1, count2 = 0, 0
for i in range(1, len(colors)-1):
if colors[i-1] == colors[i] == colors[i+1] == "A":
count1 += 1
elif colors[i-1... |
jsourabh1/6Days6Company | Intuit/far_from_land.py | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
# if grid.count(1)==0 or grid.count(0):
# return -1
land = []
m = n = len(grid)
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j] == 1:... |
jsourabh1/6Days6Company | Microsoft/find_the_quarduple.py | <filename>Microsoft/find_the_quarduple.py
# arr[] : int input array of integers
# k : the quadruple sum required
from collections import defaultdict
class Solution:
def fourSum(self, nums, target):
ans = []
nums.sort()
n = len(nums)
i = 0
ans = []
nums.sort()
... |
jsourabh1/6Days6Company | Amazon/first_non_repeating.py | from collections import defaultdict
class Solution:
def FirstNonRepeating(self, s):
# Code here
dict_1=defaultdict(lambda:0)
start=[]
res=""
for i in s:
dict_1[i]+=1
if dict_1[i]==1:
... |
jsourabh1/6Days6Company | Microsoft/Minimum_number_of_Steps.py | import math
class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target)
n = math.ceil(math.sqrt(2*target)-1) # n = 1 gives O(sqrt(target)) solution
while True:
upper = n * (n+1) // 2
if upper >= target and (upper - target) % 2 == 0:
... |
jsourabh1/6Days6Company | Intuit/largest_no_after_k_swaps.py | def helper(s, k, maxstr, ctr):
# print("YES")
if k == 0 or ctr == len(s):
return
n = len(s)
maxx = s[ctr]
for i in range(ctr+1, n):
if int(maxx) < int(s[i]):
maxx = s[i]
if maxx != s[ctr]:
k -= 1
for j in range(n-1, ctr, -1):
if int(... |
jsourabh1/6Days6Company | Goldman_Sachs/minimize_subarray_sum.py | <gh_stars>1-10
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
ans=float("inf")
sum=0
i=j=0
while i<len(nums):
sum+=nums[i]
while j<i and (sum-nums[j])>=target:
sum-=num... |
jsourabh1/6Days6Company | Goldman_Sachs/No_of_squares_in_chessboard.py | <gh_stars>1-10
def solve(N):
# // the number of squares will be(N*(N+1)*((2*N)+1))/6
print(f'The number of squares in {N}*{N} chessboard is {(N*(N+1)*((2*N)+1))/6}')
return
for _ in range(int(input("Enter the no of test cases"))):
solve(int(input("Enter the size of the chessboard"))) |
jsourabh1/6Days6Company | Walmart/Pair_with_maximum_prob.py | from collections import defaultdict
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
graph = defaultdict(list)
index = 0
for i, j in edges:
graph[i].append([j, index])
graph[j].append([... |
jsourabh1/6Days6Company | Adobe/Amend_the_sentence.py |
class Solution:
def amendSentence(self, s):
# code here
ans = ""
string = ""
for i in range(len(s)):
if 97 <= ord(s[i]) <= 122:
string += s[i]
else:
if string:
ans += string
ans += "... |
Tyler-Yates/game-box | application/games/common/__init__.py | <reponame>Tyler-Yates/game-box
from flask import Blueprint
common_blueprint = Blueprint("common", __name__)
from . import routes # noqa: F401,E402
|
Tyler-Yates/game-box | application/games/scrambledwords/util/time_util.py | import time
def get_time_millis() -> int:
return int(round(time.time() * 1000))
|
Tyler-Yates/game-box | tests/games/crosswordcreator/test_tiles.py | from application.games.crosswordcreator.data.tiles import Tiles
class TestTiles:
def test_generate_tiles(self):
num_tiles = 20
tiles = Tiles.generate_tiles(num_tiles)
print(f"Tiles: {tiles}")
assert len(tiles) == num_tiles
|
Tyler-Yates/game-box | tests/games/common/accepting_word_manager.py | <filename>tests/games/common/accepting_word_manager.py
from application.games.common.word_manager import WordManager
class AcceptingWordManager(WordManager):
def __init__(self):
super(AcceptingWordManager, self).__init__(set())
def is_word(self, word: str) -> bool:
return True
|
Tyler-Yates/game-box | application/games/scrambledwords/networking/routes.py | <filename>application/games/scrambledwords/networking/routes.py
import logging
from flask import current_app, redirect, render_template, request, url_for
from application import SCRAMBLED_WORDS_GAME_MANAGER_CONFIG_KEY
from ..data.game_manager import ScrambledWordsGameManager
from ..data.scoring_type import ScoringTyp... |
Tyler-Yates/game-box | application/games/common/player.py | import flask
from flask import request
from .routes import PLAYER_ID_KEY, PLAYER_NAME_KEY
def get_player_id() -> str:
if PLAYER_ID_KEY in request.cookies:
return flask.request.cookies[PLAYER_ID_KEY]
else:
raise ValueError("No player_id detected!")
def get_player_name() -> str:
if PLAYER... |
Tyler-Yates/game-box | application/games/common/routes.py | <filename>application/games/common/routes.py
import uuid
from flask import request, redirect, make_response, Response, render_template
from . import common_blueprint
PLAYER_ID_KEY = "player_id"
PLAYER_NAME_KEY = "player_name"
@common_blueprint.route("/")
def index():
return render_template("common/index.html")... |
Tyler-Yates/game-box | application/games/scrambledwords/data/dao.py | from pymongo import ASCENDING, DESCENDING
from pymongo.collection import Collection
from pymongo.database import Database
from application.games.common.database import get_database
MAX_HI_SCORES = 3
# Fields used in the database
PLAYER_FIELD = "player"
SCORE_FIELD = "score"
BOARD_FIELD = "board"
ID_FIELD = "_id"
c... |
Tyler-Yates/game-box | application/games/hiddennames/data/game_state.py | import logging
import random
from typing import List, Dict
from .game_tile import GameTile
from .game_update import GameUpdate
from application.games.common.word_manager import WordManager
WORD_COUNT = 25
BLUE_TEAM_TILES = 9
RED_TEAM_TILES = 8
LOG = logging.getLogger("hiddennames.GameState")
class GameState:
"... |
Tyler-Yates/game-box | application/games/crosswordcreator/networking/routes.py | import logging
from flask import current_app, redirect, render_template, request, url_for
from application import CROSSWORD_CREATOR_GAME_MANAGER_CONFIG_KEY
from application.games.common.player import get_player_id, get_player_name
from . import crossword_creator_blueprint
from ..data.game_manager import CrosswordCrea... |
Tyler-Yates/game-box | config/gunicorn.conf.py | worker_class = 'eventlet'
workers = 1
timeout = 30
|
Tyler-Yates/game-box | application/games/hiddennames/networking/routes.py | from flask import current_app, redirect, render_template, url_for, request
from application import HIDDEN_NAMES_GAME_MANAGER_CONFIG_KEY
from . import hidden_names_blueprint
from ..data.game_manager import HiddenNamesGameManager
@hidden_names_blueprint.route("/")
def index():
return render_template("hiddennames/i... |
Tyler-Yates/game-box | application/games/scrambledwords/data/scoring_type.py | from enum import Enum
class ScoringType(Enum):
CLASSIC = 1
DISTRIBUTED_FRACTIONAL = 2
DISTRIBUTED_INTEGER = 3
|
Tyler-Yates/game-box | application/games/hiddennames/data/game_tile.py | <gh_stars>1-10
class GameTile:
def __init__(self, word: str, hidden_value: int, guessed=False):
self.word = word
self.hidden_value = hidden_value
self.guessed = guessed
def __repr__(self):
return f"{self.word} - {self.hidden_value} - {self.guessed}"
def __str__(self):
... |
Tyler-Yates/game-box | application/games/scrambledwords/networking/events.py | <filename>application/games/scrambledwords/networking/events.py<gh_stars>1-10
import logging
import flask
from flask import current_app
from flask_socketio import emit, join_room
from application import ScrambledWordsGameManager, SCRAMBLED_WORDS_GAME_MANAGER_CONFIG_KEY
from application import socketio
from applicatio... |
Tyler-Yates/game-box | application/games/common/database.py | <filename>application/games/common/database.py
import os
from pymongo import MongoClient
from pymongo.database import Database
def get_database() -> Database:
username = os.environ.get("MONGO_USER")
password = os.environ.get("MONGO_PASSWORD")
host = os.environ.get("MONGO_HOST")
client = MongoClient(f... |
Tyler-Yates/game-box | application/games/common/word_manager.py | import logging
import os
import random
from typing import List, Set
LOG = logging.getLogger("common.word_manager")
FILE_LOCATION = os.path.dirname(os.path.realpath(__file__))
class WordManager:
def __init__(self, words: Set[str] = None, word_file_path: str = ""):
if words is not None:
# If w... |
Tyler-Yates/game-box | application/games/scrambledwords/networking/__init__.py | <filename>application/games/scrambledwords/networking/__init__.py
from flask import Blueprint
scrambled_words_blueprint = Blueprint("scrambled_words", __name__)
from . import events, routes # noqa: F401,E402
|
Tyler-Yates/game-box | application/games/hiddennames/networking/events.py | import logging
import flask
from flask import current_app
from flask_socketio import emit, join_room
from application import HIDDEN_NAMES_GAME_MANAGER_CONFIG_KEY, HiddenNamesGameManager
from application import socketio
LOG = logging.getLogger("hiddennames.events")
@socketio.on("hn-join")
def joined(message):
r... |
Tyler-Yates/game-box | application/games/hiddennames/networking/__init__.py | <gh_stars>1-10
from flask import Blueprint
hidden_names_blueprint = Blueprint("hidden_names", __name__)
from . import events, routes # noqa: F401,E402
|
Tyler-Yates/game-box | application/games/crosswordcreator/networking/events.py | import logging
import flask
from flask import current_app
from flask_socketio import emit, join_room
from application.games.common.player import get_player_id, get_player_name
from ..data.game_manager import CrosswordCreatorGameManager
from application import CROSSWORD_CREATOR_GAME_MANAGER_CONFIG_KEY
from application... |
Tyler-Yates/game-box | tests/games/common/test_word_manager.py | <reponame>Tyler-Yates/game-box<filename>tests/games/common/test_word_manager.py
from application.games.common.word_manager import WordManager
TEST_WORD_SET = {"test", "DOG", "Cat"}
class TestWordManager:
def setup_method(self):
self.word_manager = WordManager(words=TEST_WORD_SET)
def test_valid_word... |
Tyler-Yates/game-box | application/games/crosswordcreator/data/board.py | <reponame>Tyler-Yates/game-box
from typing import List, Optional, Tuple, Set, Dict
from ...common.word_manager import WordManager
class Board:
"""
Represents a board for a single player.
Boards are assumed to be square (equal number of rows and columns).
The board is represented as a two dimensional... |
Tyler-Yates/game-box | application/__init__.py | import logging
from flask import Flask, request, redirect
from flask_socketio import SocketIO
from .games.common import common_blueprint
from .games.crosswordcreator.data.game_manager import CrosswordCreatorGameManager
from .games.common.word_manager import WordManager
from .games.hiddennames.data.game_manager import... |
Tyler-Yates/game-box | application/games/crosswordcreator/networking/__init__.py | from flask import Blueprint, request
crossword_creator_blueprint = Blueprint("crossword_creator", __name__)
from . import events, routes # noqa: F401,E402
def _get_player_id() -> str:
if "playerId" in request.cookies:
return request.cookies["playerId"]
else:
raise ValueError("No playerId de... |
pzaffino/CellService | Analisys_cellService.py | <reponame>pzaffino/CellService<gh_stars>0
import os
import sys
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QDesktopWidget
from PyQt5.QtGui import QColor, QImage, QPixmap, QKeySequence
import numpy as np
import skimage
import skimag... |
pzaffino/CellService | CellService_processing.py | <reponame>pzaffino/CellService<gh_stars>0
from PyQt5.QtWidgets import (QMessageBox, QMainWindow, QDesktopWidget)
from PyQt5 import QtWidgets
from PyQt5 import QtGui, QtCore
import numpy as np
from skimage import filters, morphology
class Processing_cellService(QMainWindow):
def __init__(self, parent):
... |
pzaffino/CellService | CellService.py | <filename>CellService.py
import sys, os
from copy import deepcopy
from PyQt5.QtWidgets import QFileDialog, QMainWindow, QDesktopWidget, QMessageBox
from PyQt5.QtGui import QPixmap, QImage, QKeySequence
from PyQt5 import QtWidgets
import CellService_processing
import Analisys_cellService
from PyQt5 import QtCore, QtGui
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.