blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b457618da678f79c59ceb9b6e191e5c6a18df933 | Vivekyadv/InterviewBit | /Tree Data Structure/2 trees/1. merge two binary tree.py | 2,064 | 4.15625 | 4 | # Given two binary tree A and B. merge them in single binary tree
# The merge rule is that if two nodes overlap, then sum of node values is the new value
# of the merged node. Otherwise, the non-null node will be used as the node of new tree.
# Tree 1 Tree 2 Merged Tree
# 2 3 ... |
a79248bc4e2ee6c8146f7a292f336ccf6462b721 | Vivekyadv/InterviewBit | /Array/Arrangement/2. rotate matrix.py | 303 | 4.15625 | 4 | # rotate matrix by 90 ° clockwise
def rotate(A):
for i in range(len(A)):
for j in range(i,len(A)):
A[i][j], A[j][i] = A[j][i], A[i][j]
for i in range(len(A)):
A[i].reverse()
return A
arr = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(rotate(arr)) |
735b4385f06c0ec557e4b05f739f74eef00c2f58 | Vivekyadv/InterviewBit | /Tree Data Structure/Tree construction/3. construct BST from inorder and preorder.py | 1,391 | 3.9375 | 4 | # Given preorder and inorder traversal of a tree, construct the binary tree.
# Preorder : [1, 2, 3], Inorder : [2, 1, 3]
# BST = 1
# / \
# 2 3
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def construct(Pre, In,... |
51694b901e24ec8241a68111ad503342974a4e98 | Vivekyadv/InterviewBit | /Binary Search/Search step simulation/1. implement power func.py | 537 | 4.09375 | 4 | # Implement pow(x, n) % d.
def power(x,n,d):
res = 1
while n > 0:
if n % 2 == 1:
res = res * x
res = res % d
n = n//2
x = (x * x) % d
res = res % d
return res
print(power(5,7,7))
# pow(x,n) func ::: just for concept
# def pow(x,n):
# if n == 0:
# ... |
99339c5847a95993a86cf895983c618e36a45fbf | Vivekyadv/InterviewBit | /Array/Array Math/1. min step in infinite grid.py | 675 | 3.8125 | 4 | # You are in an infinite 2D grid where you can move in any of the 8 directions
# left, right, up, down, (x+1, y+1), (x+1, y-1), (x-1, y+1), (x-1, y-1)
# you are given a sequence of points and the order in which you need to cover
# the points.. Give the minimum number of steps in which you can achieve it.
# You start... |
b2ea826d76a8bd621c826ba311b96cb19d9066d6 | Vivekyadv/InterviewBit | /Array/Bucketing/1. triplet with sum btw given array.py | 1,078 | 3.703125 | 4 | # Given an array of real numbers greater than zero in form of strings.
# Find if there exists a triplet (a,b,c) such that 1 < a+b+c < 2 .
# Return 1 for true or 0 for false.
def solve(A):
# A is a list of strings
n = len(A)
arr = [float(i) for i in reversed(A)]
sumi, x, y, z = 0.0, arr[0], arr[1], ar... |
5b99759b8b7ab28ce9b3c53154c13df1809fdc31 | Vivekyadv/InterviewBit | /String/String simulation/2. longest common prifix.py | 400 | 4.09375 | 4 | # Given array of strings, find longest string S which is prifix of all strings in array
# Algorithm: Find smallest and largest string in array and using loop, check the prifix
def longestCommonPrefix(arr):
word1 = min(arr)
word2 = max(arr)
indx = 0
n = min(len(word1), len(word2))
for i in range(n)... |
9f70bf2411625c3df0c63590c31ba8802483e032 | Vivekyadv/InterviewBit | /Hashing/Key formation/1. pair with given xor.py | 607 | 3.609375 | 4 | # Given an array which contain distinct integers. find the no of unique pairs of
# integers in array whose XOR is B
def solve(arr, val):
table = set()
count = 0
for ele in arr:
if val ^ ele in table:
count += 1
else:
table.add(ele)
return count
arr = [3, 6, 8, ... |
cf6f9911b4d1875141bfd0ea625fc5c5c51961b9 | Vivekyadv/InterviewBit | /Tree Data Structure/Trie/1. Hotel Reviews.py | 2,505 | 4.03125 | 4 | # Given a string containing good words and a set of hotel reviews by the customers for
# different hotels. You need to count the good words (including duplicates) in the
# given set of reviews and sort the reviews on this count.
# If review i and review j have the same Goodness Value (count), then their original
# or... |
edcd7c026b3fd1a6122be4e78f13a77516a9c9e2 | Vivekyadv/InterviewBit | /String/String math/4. power of 2.py | 1,531 | 4.25 | 4 | # Find if Given number is power of 2 or not.
# More specifically, find if given num can be expressed as 2^k where k >= 1.
# Method 1: using log func
# 2 ^ k = num
# k*log(2) = log(num)
# k = log(num,2)
# if ceil value of k is equal to k then it can be expressed
num1 = "1024"
num2 = "1023"
from math import log, ceil
... |
e9843e3032517e51a5f625cd3555f75516f96e46 | Vivekyadv/InterviewBit | /Stack and Queue/Stack Math/2. rain water trapped.py | 1,679 | 3.609375 | 4 | # Given array of non -ve integers represents the height of building.
# compute how much water it is able to trap after raining
# Approach: for every element of given array, find highest building on the left
# and highest on the right. Take the smaller of two heights.
# The difference btw smaller height and heigt of c... |
98d596c8c14c9cca5e0caf88724a8434a9333191 | Vivekyadv/InterviewBit | /Array/Arrangement/4. find permutation.py | 693 | 3.53125 | 4 | # Given +ve int n and a string s consisting of letters D or I,
# you have to find any permutation of first n positive integer that
# satisfy the given input string.
# D means next number is smaller, while I means next number is greater.
# Notes
# Length of given string s will always equal to n - 1
# Your solution ... |
36f67dabff4e3046e87f86dc5f6276503e6163a3 | Vivekyadv/InterviewBit | /Two Pointers/Tricks/2. max continuous series of 1's.py | 1,272 | 3.890625 | 4 | # Python3 program to find positions
# of zeroes flipping which produces
# maximum number of xonsecutive 1's
# m is maximum of number zeroes allowed
# to flip, n is size of array
def findZeroes(arr, n, m) :
# Left and right indexes of current window
wL = wR = 0
# Left index and size of the widest window
bestL = ... |
98f59d582c16628f794052c4fde1a6c76c2c8a8a | Vivekyadv/InterviewBit | /Maths/Number theory/3. sorted permutation rank.py | 1,075 | 3.75 | 4 | # Given a string, find the rank of the string amongst its
# permutations sorted lexicographically.
# find rank of bca: ans = 4
# The order permutations with letters 'a', 'c', and 'b' :
# abc --> acb --> bac --> bca --> cab --> cba
def fact(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return... |
0b0a8f01882f4f9398c54a9fce9637094e33049c | Vivekyadv/InterviewBit | /Linked List/List trick/1. kth node from mid.py | 1,276 | 3.8125 | 4 | # Given head of linked list, find the kth value from the middle towards
# beginning of linked list.
# mid = n/2 + 1
# Logic: find the length of linked list
# mid = n/2 + 1 and kth from mid to begin--> mid-k-1 from starting
# so target indx = mid-k-1
class Node:
def __init__(self, data):
self.data = ... |
7a40c80dbda9dc361382b2a03d9c9223784a4384 | Vivekyadv/InterviewBit | /Maths/Adhoc/3. FizzBuzz.py | 505 | 4 | 4 | # Given +ve integer n, return array having element from 1 to n
# but for multiple of 3, print "Fizz"
# for multiple of 5, print "Buzz"
# and for multiple of both 3 and 5, print "FizzBuzz"
def solve(n):
ans = []
for i in range(1,n+1):
if i % 3 == 0 and i % 5 == 0:
ans.append("FizzBuzz")
... |
18ab5be1b4ff66f1fd9be20bfe7c6ec995389272 | Vivekyadv/InterviewBit | /Tree Data Structure/Traversal/3. inorder traversal.py | 1,410 | 3.8125 | 4 | # Given binary tree, return inorder traversal without using recursion
# 22
# / \
# 15 26
# / \ / \
# 12 18 23 28
# / \
# 16 19
#
# return : [12, 15, 16, 18, 19, 22, 23, 26, 28]
class TreeNode:
def __init__(self, x):
self.val = x
... |
d8d03d2315dac9257efe9dccb3eef24571209bc4 | Vivekyadv/InterviewBit | /Array/Array Math/5. partition.py | 1,148 | 3.78125 | 4 | # Given array, Count the number of ways to split all the elements of the
# array into 3 contiguous parts so that the sum of elements in each part
# is the same.
def partition(A,B):
total = sum(B)
if total % 3 == 0:
target = total // 3
else: return 0
ans = 0
f = 0
ele_sum = 0
for ... |
dbeb3aa00708e122e560d9cf19d8b4adc9e56668 | Vivekyadv/InterviewBit | /Hashing/Hashing two pointers/3. longest substring without repeats.py | 1,200 | 3.703125 | 4 | # Given a string, find the length of longest substring without repeating characters
# Approach: using two pointers (i,j)
# inc j if char is not seen, and calculate length (j-i)
# if char is seen, then inc i and remove char from seen
def solve(string):
n = len(string)
i = j = 0
max_len = 0
store = set... |
959b87497d7270e06e326369b8a5dfedeeb65f68 | davidSchuppa/tictactoe | /tic_tac_toe_original _enhanced.py | 1,140 | 3.734375 | 4 | board = list(range(1, 10))
turn_counter = 1
def draw_board():
print("""
{} | {} | {}
---------
{} | {} | {}
---------
{} | {} | {}
""".format(*board))
def win():
for i in range(0, len(board), 3):
if len(set(board[i:i+3])) == 1:
r... |
cb1225395f4f4787d998a299bfa40e077da4421c | hualili/opencv | /deep-learning-2020S/20-2021S-0-2slicing-2021-2-24.py | 2,631 | 4.21875 | 4 | """
Program: 2slicing.py
Coded by: HL
Date: Feb. 2019
Status: Debug
Version: 1.0
Note: NP slicing
Slicing arrays, e.g., taking elements from one given index to another given index.
(1) pass slice instead of index as: [start:end].
(2) define the step like: [start:end:step].
(3) if we don't pass start its considered 0, ... |
bd6e452a27b6cc9a433f357587b4267333b8ed92 | bbuluttekin/MSc-Coursework | /PoPI/mock_one.py | 1,362 | 3.84375 | 4 | # Q1 a
def Fibonacci(n):
numbers = [0, 1]
while len(numbers) != n:
new_num = numbers[-1] + numbers[-2]
numbers.append(new_num)
num_str = " ".join([str(i) for i in numbers])
print(num_str)
# Q1 b
def fib2000(limit=2000):
numbers = [0, 1]
while numbers[-1] < 2000:
new_nu... |
f752294dfcf116a9bf73a9568e40c1aef45dff6c | cpe202spring2019/lab1-smart161 | /lab1.py | 1,206 | 3.9375 | 4 |
def max_list_iter(int_list): # must use iteration not recursion
if int_list == None:
raise ValueError('No list entered')
elif len(int_list) <= 0:
return None
else:
max_val = int_list[0]
for i in int_list:
if i > max_val:
max_val = i
... |
1343ff7e75969f5ca334d57b3210cde1eb58cd9e | salamf/Ferry-Avg-Monthly-Delay-Calculator | /src/decoder.py | 4,147 | 3.890625 | 4 | #!/usr/bin/env python3
from linked_list import LinkedList
from cipher import FileDecoder, DecryptException
from os import path
import string
import re
import calendar
alphabet = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation + " \n"
def main():
# Get required input from us... |
239c92d99414ef234394aeec915b8454c01f986f | gan3i/CTCI-Python | /Revision/TreeAndGraph/LowestCommonAncestor_4.8/solution_one.py | 1,452 | 3.828125 | 4 | # ask can each tree node have a pointer to it's parent node
# is it guaranteed that nodes are present in tree.
# can one of the node be the lCA
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
def common_ancest... |
894e677b208321a842d980a623f9a00bdee2ecea | gan3i/CTCI-Python | /Revision/LinkedList/remove_duplicates_2.1_.py | 2,738 | 4.15625 | 4 |
#ask questions
# 1. is it a doubly linked list or singly linked list
# 2. what type of data are we storing, integer? float? string? can there be negatives,
class Node():
def __init__(self,data):
self.data = data
self.next = None
# in interview do not write the linked list class assume that it's g... |
26803428ab2b2fdf80ce43d4d3c7008b5212ed4b | gan3i/CTCI-Python | /Revision/TreeAndGraph/LinkedList.py | 532 | 3.859375 | 4 | class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
class ListNode:
def __init__(self, data):
self.data = data
self.next = None
def insert(self, data):
if not self.head:
self.head = self.ListNode(... |
7598adc1d04f118407b6dd9ba49b0d4b180fbcc5 | mahadd29/CS441_Checkers | /src/minimax/minimax.py | 8,757 | 4.09375 | 4 | # Minimax algorithm implementation file
# This file takes in a Game and finds the optimal move to make in a game of checkers
# CS 441: Group Project
# Authors: Dominique Moore, Alex Salazar
from checkers.game import Game
import copy
import numpy as np
import time
import random
# minimax(s) =
# {
# Utility(s) ... |
65f61f343a1a513e1ad558f1903aeb85ec028273 | syedmustaqhim/learningPython | /char_detect.py | 660 | 4.09375 | 4 | from pprint import pprint
sentence = str(input(
"Enter a sentence for to count the number of letters in it: "))
char_frequency = {}
for char in sentence:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
char_frequency_sorted = sorted(
char_frequency.i... |
8e521cd62903436c4cee4d2cd6b7d6baf9c80670 | lonely7yk/LeetCode_py | /LeetCode211AddandSearchWord.py | 2,410 | 3.984375 | 4 | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or '.'. A '.' means it can represent any one
letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
... |
c1f38d90b3d78025643e90a85b74acbdf47e7289 | lonely7yk/LeetCode_py | /LeetCode210CourseScheduleII.py | 3,149 | 4.21875 | 4 | """
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you shou... |
c87a0dee0760bb2226ba0d926a580373627a204d | lonely7yk/LeetCode_py | /LeetCode727MinimumWindowSubsequence.py | 3,176 | 3.734375 | 4 | """
Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.
If there is no such window in S that covers all characters in T, return the empty string "". If there are
multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
Inp... |
6169a5437d4ea11923d0857763dbc8c26ab8fc10 | lonely7yk/LeetCode_py | /LeetCode484FindPermutation.py | 2,821 | 4.21875 | 4 | """
By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a
decreasing relationship between two numbers, 'I' represents an increasing relationship between
two numbers. And our secret signature was constructed by a special integer array, which contains
uniquely all the different... |
4bcb9c66c178ae261ff540b37db82294f1736ef2 | lonely7yk/LeetCode_py | /LeetCode431EncodeNaryTreetoBinaryTree.py | 4,164 | 4.25 | 4 | """
Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the
original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children.
Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is
no restrictio... |
00d8ddc62ec42ab684c3eb3844a2e742cd960ff1 | lonely7yk/LeetCode_py | /LeetCode084LargestRectangleinHistogram.py | 3,412 | 4.0625 | 4 | """
Given n non-negative integers representing the histogram's bar height
where the width of each bar is 1, find the area of largest rectangle
in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 uni... |
e8e5b3819dea0aa55969604390c069700a0c5244 | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1277CountSquareSubmatriceswithAllOnes.py | 2,211 | 3.90625 | 4 | """
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 ... |
444f669a453c13309cf614dba60862b2058cafc5 | lonely7yk/LeetCode_py | /LeetCode222CountCompleteTreeNodes.py | 1,548 | 3.984375 | 4 | """
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled,
and all nodes in the last level are as far left as possible. It can have between 1 and 2h
nodes inclusive at ... |
d4601be379a8ee33b2d50d601296325ae79f5371 | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1091ShortestPathinBinaryMatrix.py | 1,594 | 3.890625 | 4 | """
In an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k if and only if it is composed of cells
C_1, C_2, ..., C_k such that:
Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share
an edge or corner)
... |
7368102ebddc06c8e65e546a37a9ad629d392117 | lonely7yk/LeetCode_py | /LeetCode041FirstMissingPositive.py | 3,498 | 3.84375 | 4 | """
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
"""
from typing import List
class Sol... |
6c58e85e38863bb7cb9ba5a2ba9573202f5400f0 | lonely7yk/LeetCode_py | /LeetCode300LongestIncreasingSubsequence.py | 1,910 | 3.734375 | 4 | """
Given an unsorted array of integers, find the length of longest increasing
subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore
the length is 4.
Note:
- There may be more than one LIS combination, it is only necessary for you ... |
0f4fa27557e6b618ba340fc08b2e5348ec9c641b | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1232CheckIfItIsaStraightLine.py | 1,237 | 3.78125 | 4 | """
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],... |
0b84f386e15560beb031f4955d240a43a9f9eb6d | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1404NumberofStepstoReduceaNumberinBinaryRepresentationtoOne.py | 1,621 | 3.84375 | 4 | """
Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It's guaranteed that you can always reach to one for all testcases.
Example 1... |
f849d15124783cbb06b4dba098c880f64cd918e4 | lonely7yk/LeetCode_py | /LeetCode146LRUCache.py | 3,172 | 4.03125 | 4 | """
Design and implement a data structure for Least Recently Used (LRU)
cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key
if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not
alread... |
1ffd9e7ad58b95c2cc0ea50932209de8ce1218c2 | lonely7yk/LeetCode_py | /LeetCode425WordSquares.py | 2,901 | 4.15625 | 4 | """
Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence ["ball","area","lead","lady"] forms a word square bec... |
425cca3ebcc4522cf67e5394685655b9fc3c4244 | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1579RemoveMaxNumberofEdgestoKeepGraphFullyTraversable.py | 5,862 | 3.75 | 4 | """
Alice and Bob have an undirected graph of n nodes and 3 types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can by traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui
... |
48b93455cd4751517ed866b3c809ef2546d1e600 | lonely7yk/LeetCode_py | /LeetCode103BinaryTreeZigzagLevelOrderTraversal.py | 1,228 | 3.828125 | 4 |
from typing import List
import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
... |
0b9533f72888f98b6fb46ebf9287a3df6f76f413 | lonely7yk/LeetCode_py | /LeetCode705DesignHashSet.py | 3,026 | 3.8125 | 4 | """
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value does not e... |
7f8dcc0205d5c9c4674e1ab9292e1507d4b89a19 | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1593SplitaStringIntotheMaxNumberofUniqueSubstrings.py | 1,514 | 4.09375 | 4 | """
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the
original string. However, you must split the substrings such that all of them are unique.
A su... |
fd6b1c63cf2050c042cf93da0cda4bf8904e8d80 | lonely7yk/LeetCode_py | /LeetCode778SwiminRisingWater.py | 2,948 | 3.765625 | 4 | """
On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).
Now rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another
4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can ... |
b336e49c34dff2b02b7fd80f3f1ef8ab12513ec5 | lonely7yk/LeetCode_py | /LeetCode401BinaryWatch.py | 2,155 | 4.1875 | 4 | """
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom
represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the... |
15fb196319acbc9a0b5d01180b2bba79e9277057 | lonely7yk/LeetCode_py | /LeetCode264UglyNumberII.py | 1,956 | 3.984375 | 4 | """
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1 is typically treated as an ugly number.
n does not exce... |
80b8079dfa8dccecc0cd0dd29bc2ffe3e03a8dca | lonely7yk/LeetCode_py | /LeetCode47PermutationsII.py | 1,609 | 3.765625 | 4 | """
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
1 <= nums.l... |
1c18df8d3f07b7b43cbf8e826f6b6714089ae8f2 | lonely7yk/LeetCode_py | /LeetCode369PlusOneLinkedList.py | 1,212 | 3.6875 | 4 | """
Given a non-negative integer represented as a linked list of digits, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list.
Example 1:
Input: head = [1,2,3]
Output: [1,2,4]
Example 2:
Input: head = [0]
Output: [1]
Constraints:
The number of nodes in th... |
8c36c1856f7a002736f85d36d5b6af586b613faf | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1363LargestMultipleofThree.py | 2,572 | 4.25 | 4 | """
Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
Since the answer may not fit in an integer data type, return the answer as a string.
If there is no answer return an empty string.
Example 1:
Input: digits = [8,1,9]
... |
d317c1e6cb1c870f94cdca67df52f9f881757340 | lonely7yk/LeetCode_py | /LeetCode708InsertintoaSortedCircularLinkedList.py | 1,486 | 3.75 | 4 | # Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
# O(n)
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
# 没有元素
if not head:
head = Node(insertVal, None)
head.next = hea... |
b2263def3e4b839be06b495b5d42d645feec73a6 | lonely7yk/LeetCode_py | /LeetCode403FrogJump.py | 3,579 | 4.1875 | 4 | """
A frog is crossing a river. The river is divided into x units and at
each unit there may or may not exist a stone. The frog can jump on a
stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order,
determine if the frog is able to cross the river by landin... |
07f16a7a3c94ffb901cfa58800c1ea6d43c01ba2 | lonely7yk/LeetCode_py | /LeetCode080RemoveDuplicatesfromSortedArrayII.py | 2,097 | 4.125 | 4 | """
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most
twice and return the new length.
Do not allocate extra space for another array; you must do this by modifying the input array
in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an int... |
954e849e37eb25f50e0476f1f6da4d73b4f39bc5 | lonely7yk/LeetCode_py | /LeetCode017LetterCombinationsofaPhoneNumber.py | 2,114 | 4.0625 | 4 | """
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the
number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not
map to any letters.
1 2abc 3def
4ghi 5jkl 6mno
7pqrs 8tuv 9wxyz
Example:
In... |
279f66daf5353d6b066b11c032c49480e6a1beac | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1962RemoveStonestoMinimizetheTotal.py | 1,779 | 3.703125 | 4 | """
You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the
ith pile, and an integer k. You should apply the following operation exactly k times:
Choose any piles[i] and remove floor(piles[i] / 2) stones from it.
Notice that you can apply the operation on the same pile more... |
116d7e766b08858b5f173396f065d9b3e17e6066 | lonely7yk/LeetCode_py | /LeetCode328OddEvenLinkedList.py | 1,262 | 4.0625 | 4 | """
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note
here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes)
time complexity.
Example 1:
Input: 1->2->3->4... |
d751c266a6c98177c147c82387ddc2646d439c2b | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1530NumberofGoodLeafNodesPairs.py | 4,238 | 4.125 | 4 | """
Given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree
is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], dista... |
29e7ec89f7d512267d46fc364c24f6d03ae912aa | lonely7yk/LeetCode_py | /LeetCode652FindDuplicateSubtrees.py | 1,333 | 4.0625 | 4 | """
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4... |
c1d375fb35688c7007f6482bdaa35b90a461376e | lonely7yk/LeetCode_py | /LeetCode340LongestSubstringwithAtMostKDistinctCharacters.py | 1,779 | 3.71875 | 4 | """
Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
"""
# # Sliding window... |
00f987012fc669645f8f6ff4dce0ad55345f84bf | lonely7yk/LeetCode_py | /LeetCode235LowestCommonAncestorofaBinarySearchTree.py | 1,640 | 3.984375 | 4 | """
Given a binary search tree (BST), find the lowest common ancestor
(LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common
ancestor is defined between two nodes p and q as the lowest node in
T that has both p and q as descendants (where we allow a node to be
a de... |
c7c62f6e465fb2d1d1797d171c24c01bee3041dc | lonely7yk/LeetCode_py | /LeetCode416PartitionEqualSubsetSum.py | 2,805 | 3.765625 | 4 | """
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explana... |
ee52bf5179771751d1985612c5e6ba0e9cf3b793 | lonely7yk/LeetCode_py | /LeetCode829ConsecutiveNumbersSum.py | 817 | 3.734375 | 4 | """
Given a positive integer N, how many ways can we write it as a sum of consecutive positive
integers?
Example 1:
Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3
Example 2:
Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + ... |
0b56786b54a2833bceee1c9b85f844721e1d713b | lonely7yk/LeetCode_py | /LeetCode259_3SumSmaller.py | 1,175 | 3.859375 | 4 | """
Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that
satisfy the condition nums[i] + nums[j] + nums[k] < target.
Follow up: Could you solve it in O(n^2) runtime?
Example 1:
Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Beca... |
5e6d19174f78688d3bf5abc2d9b7c1cf8e2233b0 | lonely7yk/LeetCode_py | /MergeSort.py | 866 | 4.15625 | 4 | def mergeSort(nums):
sort(nums, 0, len(nums) - 1)
def sort(nums, left, right):
if left < right:
mid = (left + right) // 2
sort(nums, left, mid)
sort(nums, mid + 1, right)
merge(nums, left, mid, right)
def merge(nums, left, mid, right):
tmp = [0 for i in range(right - left +... |
faebaf230d597eddd9c66e93fa5663e3d3545729 | lonely7yk/LeetCode_py | /LeetCode018_4Sum.py | 1,709 | 3.796875 | 4 | """
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Notice that the solution set must not contain duplicate quadruplets.
Example 1:
Input: nums = [1,0,-1,0,... |
dcc5bc89af7dceee7ea643eb58459e5950599379 | lonely7yk/LeetCode_py | /LeetCode368LargestDivisibleSubset.py | 2,244 | 3.953125 | 4 | """
Given a set of distinct positive integers, find the largest subset such
that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:
... |
6b0fedfa187a96241a82588174e6ae3b32d2cc35 | lonely7yk/LeetCode_py | /LeetCode919CompleteBinaryTreeInserter.py | 3,323 | 4 | 4 | """
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.
Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations:
CBTInserter(TreeNode root) initializes ... |
3ee91b1cf02061bdfad390285b8f5a870abbc0fc | nortonacosta/Exercicios_Condicionais | /ex02.py | 124 | 4.03125 | 4 | import math
n1 = int(input('Digite um número: '))
if n1 > 0:
print(math.sqrt(n1))
else:
print('Número inválido') |
6b577b864a6727b27e171ab6ef37ece15b20eaf4 | nortonacosta/Exercicios_Condicionais | /ex08.py | 257 | 3.84375 | 4 | n1 = float(input('Digite a 1ª nota: '))
n2 = float(input('Digite a 2ª nota: '))
if 0.00 <= n1 <= 10 and 0.00 <= n2 <= 10:
media = (n1 + n2) / 2
print(f'Média: {media:.2f}')
else:
print('Nota não informada corretamente (Nota 0.00 à 10)')
|
7139dc8be40488aea798d7d9e9ae14002dd3b037 | sunnyme/PythonCode | /1027小考4.py | 257 | 3.640625 | 4 | #1027小考4
a = int(input("阿尼斯的分數:\n"))
while True :
b = int(input("猜的分數:\n"))
if b > a:
print("低一點")
elif b < a:
print("高一點")
else:
print("你猜對了")
break
|
480bdc591c8349f887a8a618787be02515bbc47c | Minjae4835/Tech-HW-4 | /Queue.py | 1,342 | 3.953125 | 4 | class Queue(object):
def __init__(self, size=5):
self.array = [None for i in range(size)]
# no python list function calls!
self.front = -1
self.tail = -1
def print(self):
# FIXME
print(self.array)
print("Size:", self.size())
def enq(self, data=None):
# FIXME
return
def... |
5bcd7a69a994303d079bbaefced175a082c9c8aa | Engin-Boot/monitor-pi-board-s1b11 | /meta-stats/recipes-apps/json-report-generator-sources/json-report-generator-sources/package_json_object_creator.py | 1,007 | 3.671875 | 4 | '''
Reads manifest file and creates a JSON object.
Function:
create_package_json_object(str)
'''
import json
from collections import OrderedDict
def create_package_json_object(input_manifest_file):
'''
Reads an input manifest file, creates a python
dictionary containing information about the
pa... |
2ad306d0b108ae285a558caf7a29d762f3a2caee | devendrapansare21/Python-with-Lets-Upgrage | /Assignment_Day-4.py | 693 | 4.1875 | 4 | '''Program to find number of 'we' in given string and their positions in string '''
str1="what we think we become ; we are Python pragrammers"
print("Total number of 'we' in given string are ", str1.count("we"))
print("position of first 'we'--> ",str1.find("we"))
print("position of last 'we'--> ",str1.rfind("we... |
19daa8e21cb04db8e0147f1b6cd35abbacee9e41 | Fekapapa/exam-basics | /copy/copy.py | 1,279 | 3.53125 | 4 | # This should be the basic replica of the 'cp' command
# If ran from the command line without arguments
# It should print out the usage:
# copy [source] [destination]
# When just one argument is provided print out
# No destination provided
# When both arguments provided and the source is a file
# Read all contents from... |
80b421918372330269109f3ff5569989e8aa05b6 | amitsagtani97/My_Codes | /Learning Python/cameraman_salary.py | 349 | 3.671875 | 4 | no_cameras = int(input("Enter the total no. of cameras sold in this month :"))
basic_salary = 1500
camera_price = int(input("Enter the price of each camera :"))
total_sale = no_cameras * camera_price
bonus = total_sale * (2 / 100)
bonus = bonus + (200 * no_cameras)
print ("The salary of the camera man this month is : %... |
e6ba716d7690f13e27f27621701f3ccdf1f96681 | mukheshpugal/EE2703_Applied_Programming_Lab | /exp1/spice.py | 817 | 3.9375 | 4 | import sys
#Reading arguments
if (len(sys.argv) < 2):
print("Enter netlist file name as argument")
exit()
if (len(sys.argv) > 2):
print("Too many arguments")
exit()
#Reading netlist file
try:
with open(sys.argv[1]) as f:
lines = f.readlines()
except FileNotFoundError:
print("File not found")
exit()
#Pars... |
5a989876039788c8ed3ec9f81d40bd0f14bd2e55 | melevittfl/dojo | /July_2013/Team1/Cars/traffic2.py | 2,544 | 3.65625 | 4 | import pygame
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
id = 0
cars = []
moveSize = 5 # Must be the same width as the car
screenWidth = 1024
screenHeight = 640
screen = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption("rdgpydojo traffic simulator")
blac... |
8ab99cc0b4bc3fe5008df7083c77cbfd94be582d | sergelemon/hillel_python_01 | /practice/tasks_06_03.py | 7,608 | 3.703125 | 4 | def count_work_hours(in_time, out_time, rate):
"""
Функция считает оплату за отработанные часы.
:in_time int: время начала, в целых часах, например, 8
:out_time int: время окончания, в целых часах, например, 19
:rate float: стоимость полного часа
Возвращает строку вида "57.63 for 9 hours"
Если количеств... |
48021044a11b7c223777765d4586f343212bc0ac | dasszer/sudoki | /sudoki.py | 2,445 | 4.15625 | 4 | import pprint
# sudoki.py : solves a sudoku board by a backtracking method
def solve(board):
"""
Solves a sudoku board using backtracking
:param board: 2d list of ints
:return: solution
"""
find = find_empty(board)
if find:
row, col = find
else:
return True
for i i... |
2afea3679b7c7b0e0810e872f0d0bb3a721d02fc | rbnpappu/pattern | /pattern3.py | 184 | 3.921875 | 4 | num=int(input("pl enter the height of the triangle:"))
k=1
for i in range(1,num+1):
for j in range(1,(k+1)):
print("*",end="")
k=k+2
print()
|
0935071daf6866a0a6127c3625e9d3a4571d5f89 | heiyanbin/airbinb | /Mouse Eat Cheese.py | 931 | 3.65625 | 4 | import sys
def shortestPath(board):
m, n = len(board), len(board[0])
inPath = [[0] * n for _ in range(m)]
count = 0
for i in range(m):
for j in range(n):
if board[i][j] == 2: count += 1
minLen = [sys.maxint]
def dfs(i, j, pathLen, eaten):
inPath[i][j] += 1
if... |
b7085b976896a8e36a25f5c1263bc93e2d67f1bb | Yuto2511/python_study | /class_03.py | 529 | 3.765625 | 4 | #!/usr/bin/env python3
class Student:
def __init__(self,name):
self.name = name
def calculate_avg(self,data):
sum = 0
for num in data:
sum += num
avg = sum / len(data)
return avg
def judge(slef,avg):
if avg >= 60:
result = "passed"
... |
9894f16bb2d9bffaefe539dff0167559e864e4d3 | Yuto2511/python_study | /logical_operation.py | 137 | 3.71875 | 4 | #!/usr/bin/env python3
x = 8
y = 3
print(x >= 5 and x <= 10)
print(y >= 5 and y <= 10)
print(x == 3 or y == 3)
print(x == 1 or y == 1)
|
c2e634571b87e365ed8970565c1294280d587235 | jordancharest/AI-for-Robotics | /Search/a_star.py | 3,301 | 3.9375 | 4 | # ----------
# Successful search() calls return a list
# in the form of [optimal path length, row, col]
#
# If there is no valid path from the start point
# to the goal, search returns the string
# 'fail'
# ----------
# Grid format:
# 0 = Navigable space
# 1 = Occupied space
delta = [[-1, 0], # go up
[ 0... |
2542933a9c63285c640ac739155a30dddc006e79 | jordancharest/AI-for-Robotics | /Search/stochastic_motion.py | 4,366 | 3.71875 | 4 | # --------------
# USER INSTRUCTIONS
#
# stochastic_value
# returns two grids. The first grid, value, should
# contain the computed value of each cell as shown
# in the video. The second grid, policy, should
# contain the optimum policy for each cell.
#
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
... |
43ced72d7ee4a9dc79cd0494e95ab0869b98907f | dolekapil/PythonAssignments | /MyLinkedList.py | 1,444 | 3.71875 | 4 | __author__ = 'dolek'
from MyNode import LinkedNode
class LinkedList:
__slots__ = 'front'
def __init__(self):
self.front = None
def append(self,value):
if self.front is None:
self.front = LinkedNode(value)
else:
n=self.front
while n.link is not N... |
a1f9631072c3e8da6a46de97db2cb0a3b9bcdb99 | priyatharshini23/2 | /power.py | 217 | 4.4375 | 4 | # 2
num=int(input("Enter the positive integer:"))
exponent=int(input("Enter exponent value:"))
power=1
i=1
while(i<=exponent):
power=power*num
i=i+1
print("The Result of{0}power{1}={2}".format(num,exponent,power)
|
d9ba0b9ab4a57e5ac81fee6643ecd286e344b5ec | stradtkt/Tkinter-File_Sytem | /file_systems.py | 634 | 3.546875 | 4 | from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
root = Tk()
root.title("Learn To Code at gowebkit.com")
root.iconbitmap("c:/gui/gowebkit.ico")
root.geometry("700x300")
def open():
global my_image
root.filename = filedialog.askopenfilename(initialdir="/gui", title="Select a... |
b898ec3ce88f910aed65f8d1e060e1d16b2667d1 | gel13002/EleNa-CS520 | /EleNa/makeNodes.py | 3,451 | 4.3125 | 4 | """
create the connected graph using neighbor information
"""
from EleNa.Node import Node
def makeGraph(locationsAndDistances, elevations=None):
"""
make a connected graph out of 2d list of location and distances
:param locationsAndDistances: list of tuples (location, distance)
:type locationsAndDista... |
158a5c4174cd6cec3ca49069f0402fbfdf927315 | Xitog/teddy | /teddypy/layeredmap.py | 11,551 | 3.671875 | 4 | """A map with different layers."""
import json
from traceback import print_exc
from sys import stdout
def pretty_json(data, level=0, indent=4):
"Pretty print some JSON."
content = ''
if isinstance(data, dict):
content += '{\n'
level += 1
count = 0
for key, val ... |
a7fa356aafe3febcc96e5bd9e95ad2c4aab52a99 | edliaw/mars_rover | /mars | 13,989 | 3.859375 | 4 | #!/usr/bin/env python
"""Solves the Mars rover problem.
Edward Liaw
2014-05-24
Read input O(n)
Sort chunks O(n log(n))
Find fastest path through the chunks O(np)
Where p < n : p is the number of overlapping paths through the chunks.
In the worst case, p ~= n, and complexity is O(n^2).
The worst case ca... |
109da9746c32562b6d50609c6495e543bc5f8d02 | Gess1992/class-in-python- | /object.py | 581 | 3.703125 | 4 | class Animal:
def __init__(self, habitat, diet):
self.habitat = 'habitat'
self.diet = 'diet'
def speak(self):
print(f"I live in the {self.habitat} and eat {self.diet}")
animal_1 = Animal('sea', 'plankton')
animal_1.speak()
class Lion(Animal):
def __init__(self, title, pride_... |
6730b03c1a640ce24dcca9a2a335906295209339 | rajasekaran36/GE8151-PSPP-2020-Examples | /unit2/practice-newton-squareroot.py | 362 | 4.3125 | 4 | print("Newton Method to find sq_root")
num = int(input("Enter number: "))
guess = 1
while(True):
x = guess
f_x = (x**2) - num
f_d_x = 2*x
actual = x - (f_x/f_d_x)
actual = round(actual,6)
if(guess == actual):
break
else:
print("guess=",guess,"actual=",actual)
guess = ... |
f3bf48a3184212792a861b876dcb8b0cc371574e | rajasekaran36/GE8151-PSPP-2020-Examples | /unit3/function-basic.py | 112 | 3.59375 | 4 | def sub(num1,num2):
return num1-num2
a = 30
b = 20
print(sub(a,b))
print(sub(num2=b,num1=a))
print(sub(23)) |
4b3a6a01abb068f932f68cea6f3bf467092703fd | rajasekaran36/GE8151-PSPP-2020-Examples | /unit2/illustrative-exchange-two-variables.py | 178 | 3.953125 | 4 | # exchange the values of two variables
a = 10
b = 20
print("Before Exchange")
print("a=",a,"b=",b)
#b,a = a,b
temp = a
a = b
b = temp
print("After Exchange")
print("a=",a,"b=",b) |
d277b419f1bc31cd2b0c52c9c23aff2e9bf3fcd5 | rajasekaran36/GE8151-PSPP-2020-Examples | /unit2/function-args-and-return-types.py | 341 | 3.671875 | 4 | # with argument and with out return type
def greetPerson(name):
print("Hello "+name+"!")
# with argument and with return type
def add(num1,num2):
return num1+num2
# with out argument and with return type
def piValue():
return 3.14
# with out argument and with return type
def printStar():
print("*****... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.