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
a3b57807fe3af03d6725d06ef3463cd255f2b85a
jeff007ali/leetcode
/may-leetcoding-challenge/D22-SortCharactersByFrequency.py
397
3.6875
4
def frequencySort(s): freqDict = {} for c in s: if c in freqDict: freqDict[c] += 1 else: freqDict[c] = 1 ans = "" for t in sorted(freqDict.items(), key=lambda x: x[1], reverse=True): # print(t) ans += t[0] * t[1] return ans print(frequ...
32d7020e15c0706b1fa0488749699a23b2573193
jeff007ali/leetcode
/30-day-leetcoding-challenge/D26-LongestCommonSubsequence.py
516
3.65625
4
def longestCommonSubsequence(text1, text2): l1 = len(text1) l2 = len(text2) dp = [[0] * (l2 + 1) for _ in range(l1 + 1)] for i in range(l1): for j in range(l2): if text1[i] == text2[j]: dp[i+1][j+1] = dp[i][j] + 1 else: dp[i+1][j+1] = max...
1f7392fc1b1335b6b41930f87dc98466228a0390
jeff007ali/leetcode
/breakAPalindrome.py
769
3.78125
4
def breakPalindrome(palindrome): palindrome = list(palindrome) l = len(palindrome) if l == 1: return "" for i in range(l): j = l - 1 - i if i == j: continue if palindrome[i] != 'a': palindrome[i] = 'a' return "".join(palin...
ef6e7b14d600f99743a8c8d35e1ac99306a1cb79
jeff007ali/leetcode
/july-leetcoding-challenge/D21-WordSearch.py
1,062
3.9375
4
def exist(board, word): # Helper function to check whether can find word, start at (i,j) position def dfs(board, i, j, word): if len(word) == 0: return True if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[0] != board[i][j]: return False t...
5670dbe222d4e6cfd35d56f20191ca33006896c5
jeff007ali/leetcode
/InsertInterval.py
1,420
3.765625
4
# Same as - https://leetcode.com/problems/merge-intervals/ # just append newInterval and then same as merge intervals # O(nlgn) time, logn because of sort def insert(intervals, newInterval): intervals.append(newInterval) if not intervals: return [] # sort with start intervals = sorted...
810912f2f7b530068dfa948332fc404572c3bb8e
abdulalbasith/python-programming
/unit-3/dict_practice.py
521
4.59375
5
my_name= { "a":1, "b":1, "d":1, "u":1, "l":1 } for letter in my_name: print (f"The letter {letter} appears {my_name[letter]} time in my name") def reverse_lookup(state_capitals,value): result = "" for state in state_capitals: if state_capitals [state] == value: ...
b8d1d4a3facd658685105842d2ba4d25ce3bdd24
abdulalbasith/python-programming
/unit-2/homework/hw-3.py
368
4.25
4
odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar', '123451' , '0.0', 'papa', '-pq-'] number_of_strings = 0 for string in odd_strings: string_length = len(string) first_char= string [0] last_char= string [-1] if string_length > 3 and first_char == last_char: number_of_str...
89d79dc316e679596d8ffe70747316ed83b75442
abdulalbasith/python-programming
/unit-3/sols-hw-pr5.py
1,023
4.125
4
#Homework optional problem #5 def letter_count (word): count = {} for l in word: count[l] = count.get (l,0) +1 return count def possible_word (word_list, char_list): #which words in word list can be formed from the characters in the character list #iterate over word_list valid_words=...
cb8cf9872ec52c2f03d02948491ef1c8c202be30
abdulalbasith/python-programming
/unit-1/groupchallengepig.py
1,475
4.09375
4
import random player1_totalscore = 0 player2_totalscore = 0 player1_turn_score = 0 player2_turn_score = 0 score= 0 command = " " player_turn = 0 #Player 1 rolls the dice #command = input ("command r to roll > ") while (True): if player_turn == 0: command = input ("command r to ro...
55f3de042bd74132c30a98895b7570a25285fba9
Matejhippo/Prvi_python
/Domaca_naloga_13a.py
1,577
3.96875
4
a = 10 b= 15 print (a) if a > b: print ("Deset ni večje od petnajst!") elif b > a: print ("ok") if a < b: print ("Res je") print (a / b) string1 = "Povej, koliko si star!" print (string1) string2 = input ("Vpiši svojo starost: ") print (string2 + " let, a toliko si star?") string3 = int(input("Vpiši s...
1e76b79d122c06f9700ef028634fce733f9961de
Matejhippo/Prvi_python
/Pogoj_neskončno.py
264
3.671875
4
pogoj = 5 while pogoj < 10: print (f"Ponavljam {pogoj}") pogoj += 1 #pogoj = pogoj + 1 if pogoj == 9: # tu rečeš, ko vrednos po preverjanju od 5 naprej doseže 9, se naredi break, to je, zaključi preverjanje break print ("konec")
0c1657b0f331b4acc3e03414352c0f0bbb89c504
WileESpaghetti/learn-yupik
/tests/Test_ApostrophePurpose.py
3,411
3.546875
4
#!python #encoding: utf-8 import unittest import grammar class ApostrophePurposeTest(unittest.TestCase): # TODO might be good to do some permutations of letters and test splitting # TODO write some tests that are supposed to fail # TODO add more test words def setUp(self): self.ngTestWords = ...
c43ea5fb26ba6a59ea3dc32f27b021f7b67baa6b
WileESpaghetti/learn-yupik
/flash_cards.py
1,612
3.65625
4
#!python import random def load_wordlists(yupik, english): ylist = open(yupik) elist = open(english) ywords = ylist.readlines() ewords = elist.readlines() ywords = [x.strip() for x in ywords] ewords = [x.strip() for x in ewords] list = zip(ywords, ewords) #strip commented out lines ...
0765350f4baf8c9290740821aa443d1ba4020053
Xiaoran807/robot-play
/src/ros_tutorials-noetic-devel/rosty_mathematician/src/core/prepare.py
1,096
3.65625
4
import math import rospy from geometry_msgs.msg import Twist # Draws axis x. # # @param pub Publisher instance def prepare(pub): # Size of the field the robot is in divided by two. r = 7 # Moves the turtle forward, drawing one half of the x axis. move(pub, r, 4) # Moves the turtle backwards twice the lengt...
1414d8d43447daac522d046aecf3e3f916cf55c9
jiahenghuang/arrow-offer
/连续子数组的最大和.py
1,298
3.53125
4
#coding:utf-8 ''' 输入一个整型数组,数组里有整数也有负数。 数组中一二或连续的多个整数组成一个子数组。求所有子数组的和的最大值。 要求时间复杂度为O(n) ''' #思路:使用递归的思路比较好理解 class Solution: # def FindGreatestSumOfSubArray(self, array): # if array == None or len(array) <= 0: # return 0 # n_sum = array[0] # largest = n_sum # for i in ra...
41874a4cc3991e9f69680941fa805b45378e08ab
jiahenghuang/arrow-offer
/两数之和.py
845
3.75
4
数组和字符串: 两数之和:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 代码: class Solution:     def twoSum(self, nums, target):         """         :type nums: List[int]         :type target: int         :rtype: List[int]         """         for i in range(len(nums)):             number = target - nums[i]      ...
ecd28bb5b6fa31378207b40b9a6ea0c93db7e2b0
Amaya1998/business_application
/test2.py
565
4.21875
4
import numpy as np fruits= np.array (['Banana','Pine-apple','Strawberry','Avocado','Guava','Papaya']) print(fruits) def insertionSort(fruits): for i in range(1, len(fruits)): # 1 to length-1 item = fruits[i] # Move elements # to right by one...
52c48495d6ce889e5b639e5afd9fbccf45d12d29
kajalchoundiye/Python_programs
/contrived.py
192
3.828125
4
Numbers = [1, 15, 25, 678, 89] for number in Numbers: if number % 8==0: print("The numbers are unaccetable") break else: print("This all numbers are fine..!")
9b4c24baf6b2a851fb83dfe5857aac73a5d3596d
kajalchoundiye/Python_programs
/truefalse2.py
278
4.25
4
if 0: print("True") else: print("False") name=input("please enter your name ") if name: print("hello,{}".format(name)) else: print("are you the man with no name? ") #if name if name != "": print('hiiii' + name) else: print("no name...!")
035e22842749c7c8e4d3cc56b9882e90f9b2dc8b
kajalchoundiye/Python_programs
/hi.py
174
3.640625
4
a = 10 b = 22.75 c = "john" print("value of a is ", a) print ("value of b is ", b) print( "value of c is",c) print("value of a=",a,"value of b=",b," and value of c=",c)
e4ebe02f3a146c0559b8c9ba24d5cf9777a5d24e
lugray/math_toys
/polydivisible.py
2,496
3.59375
4
import itertools as it class PolyCandidate: def __init__(self, digListList): self.digListList = digListList self.position = [None] * sum([len(digList) for digList in digListList]) for i in range(len(digListList)): for j in range(len(digListList[i])): self.positi...
02f1c793357001ac80970005525085111ecff3b8
ShahriarXD/Junks
/12_pr_07.py
197
4.34375
4
str = input("Enter a string") str = str.lower() #here we have to convert it into lower if 'harry' in str : print("harry is present :)") else : print("harry is not present !")
7f5ab1c59e16ff4d4712bb61fdbad4f020275227
ShahriarXD/Junks
/09_pr_04.py
89
3.578125
4
a = str(input("Name: ")) if len(a) >10: print (True) else: print(False)
16b30b1f2f9f76a6028a1cb1bdae95bcfd9548cb
intkhabahmed/PythonProject
/Day1/Assignments/Assignment2.py
109
4.125
4
word = raw_input("Enter a word and we will print it after reversing it") reverse = word[::-1] print(reverse)
a1a09bf2afeae4790b4c405446bdfd4d79c23eea
intkhabahmed/PythonProject
/Day1/Practice/Operators.py
243
4.125
4
num1 = input("Enter the first number") #Taking first number num2 = input("Enter the second number") #Taking second number print("Addtion: ",num1+num2) print("Subtraction: ",num1-num2) print("Multiply: ",num1*num2) print("Division: ",num1/num2)
2c906ba36051972084cde6dd92713a00043ad9ea
HansHoogerwerf/python-klaverjassen
/klaverjassen/Turn.py
2,029
3.609375
4
from Deck import roem_order from util import check_trump, get_highest_trump_card, get_highest_card_color, check_card class Turn: def __init__(self, start_player): self.start_player = start_player self.players = [] self.cards = [] self.points = 0 self.winning_card = None ...
45e051cc382f9ddcbf430948bd5dd0fac3f7a7f0
HansHoogerwerf/python-klaverjassen
/klaverjassen/MinMaxPlayer.py
1,236
3.515625
4
import Player from random import random # http://games.basicflow.net/klaverjas/ai.js class Playable: def __init__(self, name): self.max = [] self.min = [] self.diff = [] self.mean = [] self.risk = [] def add_new_card(self, card): self.max.append(card) s...
6ecbda8afffa2230407cda9d65ed989f05533d76
wang264/JiuZhangLintcode
/AlgorithmAdvance/L1/optional/382_triangle-count.py
1,536
4.0625
4
# 382. Triangle Count # 中文English # Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find? # # Example # Example 1: # # Input: [3, 4, 6, 7] # Output: 3 # Explanation: # They are (3, 4, 6), # (3, ...
4929cfbbabc540052dab741fce63c354ba1e0d9b
wang264/JiuZhangLintcode
/Algorithm/L2/require/120_word-ladder.py
3,260
3.75
4
# 120. Word Ladder # 中文English # Given two words (start and end), and a dictionary, find the shortest transformation sequence from # start to end, output the length of the sequence. # Transformation rule such that: # # Only one letter can be changed at a time # Each intermediate word must exist in the dictionary. (Sta...
89950cbf2afc6bcf1ee9490bfab8649a920a7c51
wang264/JiuZhangLintcode
/DP/L3/151_best-time-to-buy-and-sell-stock-iii.py
3,210
3.75
4
# 151. Best Time to Buy and Sell Stock III # 中文English # Say you have an array for which the ith element is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. You may complete at most two transactions. # # Example # Example 1 # # Input : [4,4,6,1,1,4,2,5] # Output : 6 # Notice # Yo...
78e3d799a21e4cf197833b23e09fe48499d77d04
wang264/JiuZhangLintcode
/AlgorithmAdvance/L2/require/1070_accounts-merge.py
4,841
4.375
4
# Description # # Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a # name, and the rest of the elements are emails representing emails of the account. # Now, we would like to merge these accounts. Two accounts definitely belong to the same person if ther...
5ada27d455d8bf9d51b6e71360ddd85175b0ac95
wang264/JiuZhangLintcode
/AlgorithmAdvance/L2/require/442_implement-trie-prefix-tree.py
1,802
4.3125
4
# Implement a Trie with insert, search, and startsWith methods. # # Example # Example 1: # # Input: # insert("lintcode") # search("lint") # startsWith("lint") # Output: # false # true # Example 2: # # Input: # insert("lintcode") # search("code") # startsWith("lint") # startsWith("linterror") # inser...
c952d98015d0b0bb0618b42780fd18d221b0e408
wang264/JiuZhangLintcode
/AlgorithmAdvance/L3/optional/370_convert-expression-to-reverse-polish-notation.py
1,939
4.15625
4
# 370. Convert Expression to Reverse Polish Notation # 中文English # Given a string array representing an expression, and return the # Reverse Polish notation of this expression. (remove the parentheses) # 370. 将表达式转换为逆波兰表达式 # 中文English # 给定一个字符串数组,它代表一个表达式,返回该表达式的逆波兰表达式。(去掉括号) # # Example # Example 1: # # Input: ["3",...
c547b2db20d700bdc3b0bc06a7193e38e1d92440
wang264/JiuZhangLintcode
/Algorithm/L4/require/480_binary-tree-paths.py
2,826
4.21875
4
# 480. Binary Tree Paths # 中文English # Given a binary tree, return all root-to-leaf paths. # # Example # Example 1: # # Input:{1,2,3,#,5} # Output:["1->2->5","1->3"] # Explanation: # 1 # / \ # 2 3 # \ # 5 # Example 2: # # Input:{1,2} # Output:["1->2"] # Explanation: # 1 # / # 2 class Solution: ""...
48292de617f3eda89c003ac106a37d62e8f445d9
wang264/JiuZhangLintcode
/Algorithm/L7/optional/601_flatten-2d-vector.py
1,398
4.375
4
# 601. Flatten 2D Vector # 中文English # Implement an iterator to flatten a 2d vector. # # 样例 # Example 1: # # Input:[[1,2],[3],[4,5,6]] # Output:[1,2,3,4,5,6] # Example 2: # # Input:[[7,9],[5]] # Output:[7,9,5] from collections import deque class Vector2D(object): # @param vec2d {List[List[int]]} def __init_...
3e8a562902e5092d0922ccd213582ce4c1da5f05
wang264/JiuZhangLintcode
/AlgorithmAdvance/L6/require/125_backpack-ii.py
2,813
3.796875
4
# 125. Backpack II # 中文English # There are n items and a backpack with size m. Given array A representing the size of each item # and array V representing the value of each item. # # What's the maximum value can you put into the backpack? # # Example # Example 1: # # Input: m = 10, A = [2, 3, 5, 7], V = [1, 5, 2, 4] # ...
7fb4c1cab08e8ecb37dee89edf8a47093e54a1b5
wang264/JiuZhangLintcode
/AlgorithmAdvance/L4/require/633_find-the-duplicate-number.py
1,001
4.125
4
# 633. Find the Duplicate Number # 中文English # Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), # guarantee that at least one duplicate number must exist. # Assume that there is only one duplicate number, find the duplicate one. # # Example # Example 1: # # Input: # [5,5,...
f38ddb86d379f0f3ef91a3b368a1b22b469b0c41
wang264/JiuZhangLintcode
/Algorithm/L4/optional/597_subtree-with-maximum-average.py
1,929
3.84375
4
# 597. Subtree with Maximum Average # 中文English # Given a binary tree, find the subtree with maximum average. Return the root of the subtree. # # Example # Example 1 # # Input: # {1,-5,11,1,2,4,-2} # Output:11 # Explanation: # The tree is look like this: # 1 # / \ # -5 11 # / \ / \ # 1 2 4 -2 # ...
4daaf95212a5544b78893c8122596ba5ccb7a27a
wang264/JiuZhangLintcode
/DP/L4/513_perfect-squares.py
987
3.71875
4
# 513. Perfect Squares # Given a positive integer n, find the least number of perfect square numbers # (for example, 1, 4, 9, 16, ...) which sum to n. # # Example # Example 1: # # Input: 12 # Output: 3 # Explanation: 4 + 4 + 4 # Example 2: # # Input: 13 # Output: 2 # Explanation: 4 + 9 import sys class Solution: ...
9539668c96bc480672085947c057285af7b26a6f
wang264/JiuZhangLintcode
/AlgorithmAdvance/L2/optional/432_find-the-weak-connected-component-in-the-directed-graph.py
1,236
4.1875
4
# 找出有向图中的弱连通分量 · Find the Weak Connected Component in the Directed Graph # Union Find # LintCode 版权所有 # 描述 # Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and # a list of its neighbors. (a weak connected component of a directed graph is a maximum subgraph in whi...
c55f839e550c5d851150254ae6f2f151deed02a5
wang264/JiuZhangLintcode
/Algorithm/L7/optional/606_kth-largest-element-ii.py
808
4.21875
4
# 606. Kth Largest Element II # 中文English # Find K-th largest element in an array. and N is much larger than k. Note that it is the kth largest element in the sorted order, not the kth distinct element. # # Example # Example 1: # # Input:[9,3,2,4,8],3 # Output:4 # # Example 2: # # Input:[1,2,3,4,5,6,8,9,10,7],10 # Outp...
c5b84a0f58eb46585231dc71f54a9fd2548befe4
wang264/JiuZhangLintcode
/Algorithm/L6/require/17_subsets.py
2,541
3.84375
4
# 17. 子集 # 中文English # 给定一个含不同整数的集合,返回其所有的子集。 # # 样例 1: # # 输入:[0] # 输出: # [ # [], # [0] # ] # 样例 2: # # 输入:[1,2,3] # 输出: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # 挑战 # 你可以同时用递归与非递归的方式解决么? # # 注意事项 # 子集中的元素排列必须是非降序的,解集必须不包含重复的子集。 # 常規的DFS解法 class Solution: """ ...
dc7a6d1f2e9728299cc92a07466692ac2566094f
wang264/JiuZhangLintcode
/Algorithm/L2/require/7_serialize-and-deserialize-binary-tree.py
6,198
4.21875
4
# 7. Serialize and Deserialize Binary Tree # 中文English # Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'. # Example # Example 1: # Input:{3,...
646d81c42d52b14fd9008775960cdad6d1cce0a8
wang264/JiuZhangLintcode
/AlgorithmAdvance/xxx_quicksort.py
1,562
4.03125
4
# This function takes last element as pivot, places # the pivot element at its correct position in sorted # array, and places all smaller (smaller than pivot) # to left of pivot and all greater elements to right # of pivot def partition(arr, low, high): prev = low - 1 # point to the previous index of the element...
9cb9373d93f1397022e0a1c69c157f18ab984d58
wang264/JiuZhangLintcode
/AlgorithmAdvance/L2/require/434_number-of-islands-ii.py
4,223
3.90625
4
# 434. Number of Islands II # 中文English # Given a n,m which means the row and column of the 2D matrix and an array of pair A( size k). Originally, the 2D # matrix is all 0 which means there is only sea in the matrix. The list pair has k operator and each operator has # two integer A[i].x, A[i].y means that you can chan...
3d2ccb860e30805eed227cbe810a0501e6a16891
wang264/JiuZhangLintcode
/AlgorithmAdvance/L6/optional/91_minimum-adjustment-cost.py
2,232
4.03125
4
# 91. Minimum Adjustment Cost # 中文English # Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater # than a given number target. # # If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of | A[i] - B[i] | # # # Example ...
00470fb1819f97906ca50ea11cfd15a0b931ab4f
wang264/JiuZhangLintcode
/Algorithm/L2/require/137_clone-graph.py
1,837
3.859375
4
# 137. Clone Graph # 中文English # Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. # Nodes are labeled uniquely. # # You need to return a deep copied graph, which has the same structure as the original graph, and any # changes to the new graph will not have any effect on th...
c5f002a5269574e83c4c68498d69881e74549d67
wang264/JiuZhangLintcode
/DP/L5/430_scramble-string.py
3,093
4.03125
4
# 430. Scramble String # 中文English # Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. # # Below is one possible representation of s1 = "great": # # great # / \ # gr eat # / \ / \ # g r e at # / \ # a t # T...
5bfd1442cd937d1eb261060236bfa35bae1179b2
wang264/JiuZhangLintcode
/Algorithm/L2/optional/70_binary-tree-level-order-traversal-ii.py
1,689
4
4
# 70. Binary Tree Level Order Traversal II # 中文English # Given a binary tree, return the bottom-up level order traversal of its nodes' values. # (ie, from left to right, level by level from leaf to root). # # Example # Example 1: # # Input: # {1,2,3} # Output: # [[2,3],[1]] # Explanation: # 1 # / \ # 2 3 # i...
ad621f93d2ca88bbfc707bafa5d6325a6cb774be
wang264/JiuZhangLintcode
/Algorithm/L4/optional/448_inorder-successor-in-bst.py
2,318
3.953125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ #https://www.geeksforgeeks.org/inorder-predecessor-successor-given-key-bst/ # 1. If root is NULL then return # 2. if key is found then # a. If its left subtree is not null ...
31b746ac9fb9c65da02482d67eaa98188db5d624
wang264/JiuZhangLintcode
/SystemDesign/L5/556_standard-bloom-filter.py
1,864
3.859375
4
# Description # Implement a standard bloom filter. Support the following method: # # StandardBloomFilter(k) The constructor and you need to create k hash functions. # add(string) Add a string into bloom filter. # contains(string) Check a string whether exists in bloom filter. # Have you met this question in a real inte...
2aa97182b62f6379071754f52103a7f9bd001e09
wang264/JiuZhangLintcode
/Algorithm/L5/require/607_two-sum-iii-data-structure-design.py
1,513
3.8125
4
# 607. Two Sum III - Data structure design # 中文English # Design and implement a TwoSum class. It should support the following operations: add and find. # # add - Add the number to an internal data structure. # find - Find if there exists any pair of numbers which sum is equal to the value. # # Example # Example 1: # # ...
0448102978e86c39d6223e8b8a5d541c0eff8940
wang264/JiuZhangLintcode
/Intro/L4/optional/223_palindrom_linked_list.py
1,709
3.9375
4
# 223. Palindrome Linked List # 中文English # Implement a function to check if a linked list is a palindrome. # # Example # Example 1: # # Input: 1->2->1 # output: true # Example 2: # # Input: 2->2->1 # output: false # Challenge # Could you do it in O(n) time and O(1) space? from helperfunc import ListNode, build_linked...
5a62c97e37df4c9c48df1103e933441f70869dc6
wang264/JiuZhangLintcode
/Algorithm/L5/require/228_Middle_of_linked_list.py
1,687
4.0625
4
# 228. Middle of Linked List # 中文English # Find the middle node of a linked list. # # Example # Example 1: # # Input: 1->2->3 # Output: 2 # Explanation: return the value of the middle node. # Example 2: # # Input: 1->2 # Output: 1 # Explanation: If the length of list is even return the value of center left one. # Ch...
bba1956cd35e235f5521d9079884ba1ade7ffc8b
wang264/JiuZhangLintcode
/Algorithm/L8/require/109_triangle.py
2,747
4.09375
4
# 109. Triangle # 中文English # Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. # # 样例 # Example 1: # # Input the following triangle: # [ # [2], # [3,4], # [6,5,7], # [4,1,8,3] # ] # Output: 11 # Explanation: The minimum path sum f...
341fc54aefde1e942a2f1fd6aa2dd4bd70d02b62
wang264/JiuZhangLintcode
/Algorithm/L2/require/127_topological_sorting.py
1,764
4
4
# 127. Topological Sorting # 中文English # Given an directed graph, a topological order of the graph nodes is defined as follow: # # For each directed edge A -> B in graph, A must before B in the order list. # The first node in the order can be any node in the graph with no nodes direct to it. # Find any topological orde...
292611d89d8d0c3c87355dd6f5bda5b14476eff6
wang264/JiuZhangLintcode
/DP/L2/515_paint-house.py
3,670
4.21875
4
# 515. Paint House # 中文English # There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. # The cost of painting each house with a certain color is different. You have to paint all the houses such that no # two adjacent houses have the same color, and you need to cost th...
4587f03e8e0258b67d23bee5f044a7e56826b86e
wang264/JiuZhangLintcode
/AlgorithmAdvance/L6/optional/562_bakpack-iv.py
2,671
3.765625
4
# 562. Backpack IV # 中文English # Given an integer array nums[] which contains n unique positive numbers, num[i] indicate the size of ith item. # An integer target denotes the size of backpack. Find the number of ways to fill the backpack. # # Each item may be chosen unlimited number of times # # Example # Example1 # # ...
b20590161658824d6ec48d666ca7dafbb19bcbcd
wang264/JiuZhangLintcode
/Algorithm/L4/require/453_flatten-binary-tree-to-linked-list.py
2,642
4.1875
4
# 453. Flatten Binary Tree to Linked List # 中文English # Flatten a binary tree to a fake "linked list" in pre-order traversal. # # Here we use the right pointer in TreeNode as the next pointer in ListNode. # # Example # Example 1: # # Input:{1,2,5,3,4,#,6} # Output:{1,#,2,#,3,#,4,#,5,#,6} # Explanation: # 1 # /...
383fd740f2137ac1842c8578d8106b65859c2a3b
wang264/JiuZhangLintcode
/AlgorithmAdvance/L2/related/805_maximum-association-set.py
3,101
4.40625
4
# 最大关联集合 · Maximum Association Set # 亚马逊 # Union Find # 描述 # Amazon sells books, every book has books which are strongly associated with it.Given ListA and ListB, # indicates that ListA[i] is associated with ListB[i] which represents the book and associated books. # Output the largest set associated with each other(out...
7c9b307c23b6710832d0cb0b4baebbaca46ef5b7
wang264/JiuZhangLintcode
/Algorithm/L2/optional/598_zombie-in-matrix.py
2,238
3.828125
4
# 598. Zombie in Matrix # 中文English # Given a 2D grid, each cell is either a wall 2, a zombie 1 or people 0 (the number zero, one, two).Zombies can turn # the nearest people(up/down/left/right) into zombies every day, but can not through wall. How long will it take to # turn all people into zombies? Return -1 if can no...
d98e120b8fcd06c7636977ee0f35e26e07d39193
wang264/JiuZhangLintcode
/Algorithm/L2/optional/573_build-post-office-ii.py
3,843
4.25
4
# 573. Build Post Office II # 中文English # Given a 2D grid, each cell is either a wall 2, an house 1 or empty 0 (the number zero, one, two), find a place to # build a post office so that the sum of the distance from the post office to all the houses is smallest. # # Return the smallest sum of distance. Return -1 if it i...
f57677556fda89bbd8c1d007235720b259c875b4
wang264/JiuZhangLintcode
/Algorithm/L4/require/901_closest-binary-search-tree-value-ii.py
2,133
4.03125
4
# 901. Closest Binary Search Tree Value II # 中文English # Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. # # Example # Example 1: # # Input: # {1} # 0.000000 # 1 # Output: # [1] # Explanation: # Binary tree {1}, denote the following structure: # 1 # Ex...
fc326ee21cb8181ee6934b7fd3e13329209daae1
wang264/JiuZhangLintcode
/Algorithm/L4/require/902_kth-smallest-element-in-a-bst.py
2,767
3.859375
4
# 902. Kth Smallest Element in a BST # 中文English # Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. # # Example # Example 1: # # Input:{1,#,2},2 # Output:2 # Explanation: # 1 # \ # 2 # The second smallest element is 2. # Example 2: # # Input:{2,1,3},1 # Output:1 # E...
38c24f5a00db2b70965ed57daefcb4980a3d37af
wang264/JiuZhangLintcode
/Algorithm/L4/require/596_minimum-subtree.py
4,342
4.0625
4
# 596. Minimum Subtree # 中文English # Given a binary tree, find the subtree with minimum sum. Return the root of the subtree. # # Example # Example 1: # # Input: # {1,-5,2,1,2,-4,-5} # Output:1 # Explanation: # The tree is look like this: # 1 # / \ # -5 2 # / \ / \ # 1 2 -4 -5 # The sum of whole tr...
e9f8b128025f9273474c6c0af58541eb9fcf1ae8
wang264/JiuZhangLintcode
/Intro/L5/require/376_binary_tree_path_sum.py
1,969
4.21875
4
# 376. Binary Tree Path Sum # 中文English # Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target. # # A valid path is from root node to any of the leaf nodes. # # Example # Example 1: # # Input: # {1,2,4,2,3} # 5 # Output: [[1, 2, 2],[1, 4]] # Explanation: # The tree is lo...
8cece2f5c2bbbca316e9ba8fe9045ce2b0fbbcd0
Ninjak0/100-Days-of-Code-with-Python
/Days/19-21_itertools/Day21.py
2,294
3.5625
4
import itertools # ---Bite 64. Fix a truncating zip function--- names = 'Tim Bob Julian Carmen Sofia Mike Kim Andre'.split() locations = 'DE ES AUS NL BR US'.split() confirmed = [False, True, True, False, True] def get_attendees(): for participant in itertools.zip_longest(names, locations, confirmed, ...
62f75941b3962b3a6a4838770e672443cbe0f7e0
Ninjak0/100-Days-of-Code-with-Python
/Days/19-21_itertools/Day20.py
626
4
4
import itertools import time import random colours = "Red Green Yellow".split() rotation = itertools.cycle(colours) def rg_timer(): return random.randint(3, 7) def light_rotation(rotation): for colour in rotation: if colour == "Yellow": print(f"Caution! The light is {colour}"...
d941462eef5544a668c0a61726c7a6c531a10667
Ninjak0/100-Days-of-Code-with-Python
/Days/19-21_itertools/Day19.py
494
3.703125
4
import itertools import time import sys symbols = itertools.cycle("-\|/") while True: sys.stdout.write("\r" + next(symbols)) sys.stdout.flush() time.sleep(0.25) for letter in itertools.product("julian", repeat=2): print(letter) friends = "mike bob julian".split() # combinations does...
4625ae6fcb5de10aef9df5bef3204c51e5abe689
walidsharaar/email_merger
/main.py
1,063
3.78125
4
#TODO: Create a letter using starting_letter.txt #for each name in invited_names.txt #Replace the [name] placeholder with the actual name. #Save the letters in the folder "ReadyToSend". #Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp #Hint2: This method will also help yo...
c0adbf2f70b267bae33a44ecf8a010fa697e2964
i9t6/code_school
/t3_w1_generadores.py
1,718
3.625
4
#!/home/paco/py3/bin/python from time import time def read_line(var_archivo): with open(var_archivo,"r") as file: for line in file: yield line def get_even(var_linea): lista = [ i for i in var_linea if i in ["2","4","6","8"]] yield lista csvfile = input(f"Nombre del archiv...
dfb4da9ff2b1ddcbcb8dcabf057ee4c995f25be4
i9t6/code_school
/cuenta_palabras.py
216
3.734375
4
#!/home/paco/ubuntu/py3/bin/python print(f"¿Qué estás pensando? \n>>>>" ,end=" ") var_input = input().split() var_cuenta = 0 for algo in var_input: var_cuenta +=1 print(f"----> fueron {var_cuenta} palabras")
afadac2a3cfdceb25269466c79c2f20f95e95d44
carloscn/ftp_file_md5sum
/ftp_file_list_md5.py
6,356
3.5
4
import os,sys,hashlib,argparse # input python3 ftp_file_list_md5.py [a] [b] [c] # [a] (mode): # 0 is caculate the all files md5 and save the md5 to [b] file # 1 is compared c dir all files with b md5 file. # [b] (md5_file) : save md5 value. # [c] (dir): destnate dir. # example 1: python3 ftp_file_list_md5.py 0 he...
c368a804711ffcf50d6d78f0fd7f01683bddb674
xulu199705/LeetCode
/leetcode_1302.py
725
3.75
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: a = [] deepestRow = 0 def deepestLeavesSum(self, root: TreeNode) -> int: self.scanTree(root, 0) s...
0df2d100ddc1538544f8df45b63df19c6956591d
tyagideepu133/vidmate-namer
/question_paper_rename.py
3,697
3.578125
4
import pandas as pd import os # This function reads all file name an # def read_all_file_names(): # # for name in file_names: # # print(name) class PaperRenamer: file_names = [] processed_codes = [] processed_names = [] excel_output = None df = None path = "C:/Lectures/process"...
82b1a8b11c38482e2641230199e228516283bff5
Helloguytie/Burgers-and-Tacos
/Backup.py
18,857
3.859375
4
def woke_intro(): print('''You leave your bedroom and run into your roommate in the living room. She is your party friend of the group. She’s known for being mildly irresponsible and is VERY go-with-the-flow. She wants you to go out to a new bar with her. She says you could meet guys there, and it sounds like a nic...
028a98a91172181f31d12b78a726847da9b4fa7a
avitalRubin/python-class
/homework.py
317
3.734375
4
list="" for i in range(2000,3201): if((i%7==0)and(i%5!=0)): list+=(str(i)+", ") print(list[0:len(list)-2]) #2 str=input("please enter a string\n") for i in range(len(str)-1): if(i%2==0): print(str[i]) #3 reverse str2=input("enter strin to print in reverse\n") print(str2[len(str2)-1::-1])
c1f06b85127ba3a17b0cecd39705779491be8bb4
jailsonsf/Exercicios
/NepsAcademy/Problemas/Python/medalhas.py
798
3.828125
4
athlete_1 = int(input()) athlete_2 = int(input()) athlete_3 = int(input()) podium = [] if (athlete_1 < athlete_2 and athlete_1 < athlete_3): podium.append(1) if(athlete_2 < athlete_3): podium.append(2) podium.append(3) else: podium.append(3) podium.append(2) elif (athlete...
2e239abfa836c6ec53aa09c0865c9abc3e09f487
hsyv587/LeetCode
/111. Minimum Depth of Binary Tree(1 time, recursively).py
727
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: ...
b5c77d98bc8d0041a953c50268d1edcb998e7b37
hsyv587/LeetCode
/206. reverse Linked List(Iteratively).py
779
3.84375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return No...
343f143eda1110dfa3a6057ca1d8e06cd31680ef
hsyv587/LeetCode
/15. 3 Sum(two pointer, DP, 40%).py
1,213
3.5625
4
#-*- coding:utf-8 -*- import sys import os import time class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] nums.sort() for i in range(0, len(nums) - 2): if i and nums[i] == nums[i - 1...
4bf8ef9821c3d31e1b1dea95dcd2b9af04acb527
umekaiten/MIT-AI-6.034-assignments-sol
/lab0/lab0.py
3,453
3.859375
4
# This is the file you'll use to submit most of Lab 0. # Certain problems may ask you to modify other files to accomplish a certain # task. There are also various other files that make the problem set work, and # generally you will _not_ be expected to modify or even understand this code. # Don't get bogged down with ...
67b68a4104edef825605d7b8bfeceb5400cab448
Gorilla-Programming/Python-Course
/Assignment 5/Ques 8.py
218
4.28125
4
# Program to print Volume of Cuboid a = float(input("Enter 1st number : ")) b = float(input("Enter 2nd number : ")) c = float(input("Enter 3rd number : ")) print("Average of given Number is : %f " %((a+b+c)/3))
fd15c358f1b082929d863136436f817be752d2a1
lkxiaolou/python_test
/hello.py
998
3.953125
4
#coding=utf-8 '测试代码集合' __author__ = 'lkxiaolou' #利用map函数把用户输入的不规范的英文名字,变为首字母大写,其他小写 #处理大小写函数 def first_toupper(str): return str.capitalize(); #测试 name_list = ['lk', 'Lk', 'kSon', 'kHttpD']; print 'before:',name_list; print 'after:',map(first_toupper, name_list); #sum求和 list = [1, 2, 3, 4, 5, 6]; print list,'求和',...
8f2f19d3ab582a58fec80c73bc3d4e280bbb8177
trinahaque/LeetCode
/30day/maxProfit.py
539
3.875
4
# peak valley method # adding the height, not slope #Time Complexity: O(n) --> loops through the whole array #Space Complexity: O(1) --> only one variable created def maxProfit(prices): #max profit will be 0 if stock prices keep going down max_profit = 0 for i in range(1, len(prices)): #it means st...
2e78e062c465ea43cf3797c8b5697d775abeaa3d
trinahaque/LeetCode
/Easy/LinkedList/hasCycle.py
1,424
3.96875
4
class ListNode: def __init__(self, val): self.val = val self.next = None # Space Complexity: Constant since it's only storing two pointers # Time Complexity # No Cycle: O(n) whenever the fast pointer reaches the end (n/2) # Cycle: O(N+K) which is O(n) # Readup LeetCode Time Complexity class Solutio...
344be97dd64ac990f157e8271e6a6904a86b29a4
trinahaque/LeetCode
/Easy/Array/containsDuplicates.py
347
3.9375
4
# Time Complexity: O(n) # Space Complexity: O(n) def containsDuplicates(nums): if len(nums) < 2: return False # O(n) space dict = {} # O(n) time for i in nums: if i in dict: return True else: dict[i] = 1 return False arr = [1, 2, 3, 4] prin...
4924278da3dba92909c099754236d732d5ae6e09
trinahaque/LeetCode
/Easy/String/reverseWordsInString.py
942
4.15625
4
# Given an input string, reverse the string word by word. # Input: "the sky is blue" # Output: "blue is sky the" def reverseWordsInString(s): if len(s) < 1: return "" elif len(s) < 2: if s.isalnum() == True: return s result = "" # splits the words into an array strArr = ...
c9e0ebf8722703eab7d495aa8a8ebc0a877b5f30
trinahaque/LeetCode
/Easy/BinaryTree/insertIntoBST.py
867
4
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self, root): self.root = root def insert(self, root, val, side): node = TreeNode(val) r...
424748284e9e663d72d0cf3c14e095214fd7fea7
trinahaque/LeetCode
/30day/maxSubArray.py
1,101
3.96875
4
# Time Complexity: O(n) --> one loop # Space Complexity: O(1) or Constant --> only storing two variables # Kadane's Algorithm: start a new sum at current index or continue from # previous sum # There is a divide/conquer way def maxSubArray(nums): current_max = nums[0] max_sum = current_max for i in rang...
9f7b34dfd1c32b9d3f4189ee65ba08af90e3799c
trinahaque/LeetCode
/Easy/BinaryTree/maximumDepth.py
505
3.78125
4
# Time Complexity: O(n) --> traverses every node to compare depth # Space Complexity: O(n) --> if tree is linear class Solution: def maxDepth(self, root: TreeNode) -> int: if root == None: return 0 if root.left == None and root.right == None: return 1 leftDepth = sel...
b56bc6e767673ebe602830b6e00e14c666a657a2
PJMantis/Sudoku
/Final_project_2_Multi_Sudoku.py
11,777
4.125
4
''' Project: Sudoku Authors: Xinru Yun, Tianjun Tang(Don) Course: Software Carpentry Johns Hopkins University This is our Final Project of Software Carpentry, in which we decided to apply BFS (Breadth First Search) method to solve various kinds of sudoku games. Our data source is Conceptis, which is a s...
4ff801256dafddb7888bdc4253a8d3cdbef666f4
jaredmoore/Evo_Flex_Quadruped_Code
/Analysis/utilities.py
1,175
3.875
4
""" Utilities for analysis calculations. """ import math def calc_3d_composite_com(coms, masses): """ Calculate the composite center of mass for a group of centers of mass. Assumes that x, y, and z are of interest. Index 1 is vertical axis Formula: com_x = sum(body_x*body_mass)/total_limb_mass (Repeat for e...
0a7f72dcb4a07572426456654cfd4ac3776539ef
maryemguizani/patterns-of-segregation
/bin/plot_ratio_classes.py
3,962
3.6875
4
"""plot_ratio_classes.py Plot the proportion of households that belong to a given class as a function of the total number of households. """ from __future__ import division import csv from math import log10 import math import numpy as np from matplotlib import pylab as plt from scipy.stats import linregress colours ...
3deaeebc3a7a735f3f302d84555c0292ca0a4b20
maryemguizani/patterns-of-segregation
/bin/plot_gini.py
2,505
3.6875
4
"""plot_gini.py Plot the Gini of the income distribution as a function of the number of households in cities. """ from __future__ import division import csv import numpy as np import itertools from matplotlib import pylab as plt # # Parameters and functions # income_bins = [1000,12500,17500,22500,27500,32500,37500,42...
4e1583eba5c9c0b947340c0768ad42fcce2d85f0
maryemguizani/patterns-of-segregation
/bin/analysis/households_per_class.py
952
3.625
4
"""households_per_class.py Count the number of households per class across the US """ from __future__ import division import csv # # Read the data # ## Classes classes = {} with open('extr/classes/msa_average/classes.csv', 'r') as source: reader = csv.reader(source, delimiter='\t') reader.next() for ro...
ef4b15209bf63a6680e787f474ec607ae30514b3
wonbuu/PyIntro
/convertGrade.py
204
4.03125
4
userAnswer = input("Would you like to convert you grade to a letter? Y/N\n:") userNumber = int(input("What is your numerical grade?\n:")) if userAnswer.upper == "Y": #do stuff here if else:
2abe45d23e6c8b5d143a5298c314863db2b6e2c7
wonbuu/PyIntro
/highLow.py
709
3.9375
4
import random num = random.randint(1, 10) winner = False guesses = 0 dif = 0 last = 0 while True: usr = int(input("What number am I thinkiing of?\n:")) guesses = guesses + 1 if usr < num: print("Too low!") elif usr > num: print("Too high") elif usr == num: win...
ae85a1a3655937a5e48dc7a42da9aa2f0f7073c9
Nnevalti/Bootcamp_python_42
/day01/ex00/recipe.py
1,499
3.875
4
class Recipe : """This is a recipe""" name = "" cooking_lvl = 0 cooking_time = 0 ingredients = [] description = "" recipe_type = "" nb_recipe = 0 def __init__(self, name, cooking_lvl, cooking_time, ingredients, description, recipe_type) : if not name == "" : self.name = name else : print("Name is i...
f35555d539781fa04732a6e2e84059cd9fd9237b
Nnevalti/Bootcamp_python_42
/day00/ex09/guess.py
802
4.0625
4
import random print("This is an interactive game!") print("You have to enter a number between 1 and 99 to find out the secret number.") print("Type 'exit' to end the game.") print("Good luck!\n") number = random.randint(1,99) ntry = 0 while 1 : guess = input("What's your guess between 1 and 99?\n") ntry += 1 if (...