blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
bee255d036026f1c1aad5b1f77182cbacbaf2639
Andrewlearning/Leetcoding
/leetcode/Array/滑动窗口/古城 - 滑动窗口/1248. 统计优美子数组(exact k).py
1,345
3.65625
4
""" 给你一个整数数组nums 和一个整数 k。如果某个连续子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。 请返回这个数组中 「优美子数组」 的数目。 示例 1: 输入:nums = [1,1,2,1,1], k = 3 输出:2 解释:包含 3 个奇数的子数组是 [1,1,2,1] 和 [1,2,1,1] 。 示例 2: 输入:nums = [2,4,6], k = 1 输出:0 解释:数列中不包含任何奇数,所以不存在优美子数组。 """ class Solution(object): def numberOfSubarrays(self, nums, k): """ ...
020f1651d91b9a89129261f89380c0cc23eebdbf
Andrewlearning/Leetcoding
/leetcode/Tree/501. 二叉搜索树中的众数.py
1,666
3.984375
4
""" 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假如说有多个众数,则要把他们都求出来 """ # 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 findMode(self, root): """ ...
39bf576013051d51bf7239f661cab6c86b5acf59
Andrewlearning/Leetcoding
/leetcode/Graph/277. 搜寻名人.py
1,732
3.859375
4
""" 输入: graph = [   [1,1,0],   [0,1,0],   [1,1,1] ] 输出: 1 解析: 有编号分别为 0、1 和 2 的三个人。graph[i][j] = 1 代表编号为 i 的人认识编号为 j 的人,而 graph[i][j] = 0 则代表编号为 i 的人不认识编号为 j 的人。“名人” 是编号 1 的人,因为 0 和 2 均认识他/她,但 1 不认识任何人。 """ # The knows API is already defined for you. # @param a, person a # @param b, person b # @return a boolean, wheth...
5e842aa1a90f73b74f9d3fedb2cc4eb05281a340
Andrewlearning/Leetcoding
/leetcode/Tree/古城-树的遍历/非递归遍历二叉树/255. 验证前序遍历序列二叉搜索树.py
1,624
3.875
4
""" 给定一个整数数组,你需要验证它是否是一个二叉搜索树正确的先序遍历序列。 你可以假定该序列中的数都是不相同的。 参考以下这颗二叉搜索树: 5 / \ 2 6 / \ 1 3 示例 1: 输入: [5,2,6,1,3] 输出: false 示例 2: 输入: [5,2,1,3,6] 输出: true """ class Solution(object): # 如果出现递减序列,则是左子树 # 否则是右子树,右子树一定是递增的 def verifyPreorder(self, preorder): """ :type preord...
3e287c13b5958f02b1af9c21957225d2b6e801e8
Andrewlearning/Leetcoding
/leetcode/Array/two pointers/392m. 判断子序列.py
833
3.6875
4
""" 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 示例 1: s = "abc", t = "ahbgdc" 返回 true. 示例 2: s = "axc", t = "ahbgdc" 返回 false. """ class Solution(object): def isSubseq...
2943751d99cbd97550c0c00c528f67ed94d64bda
Andrewlearning/Leetcoding
/leetcode/Design/251. 展开二维向量.py
1,776
4
4
""" 请设计并实现一个能够展开二维向量的迭代器。该迭代器需要支持 next 和 hasNext 两种操作。 Vector2D iterator = new Vector2D([[1,2],[3],[4]]); iterator.next(); // 返回 1 iterator.next(); // 返回 2 iterator.next(); // 返回 3 iterator.hasNext(); // 返回 true iterator.hasNext(); // 返回 true iterator.next(); // 返回 4 iterator.hasNext(); // 返回 false """ class Vector2D...
52a534bb412723d27f2e2b0c8d02d8ce587872d6
Andrewlearning/Leetcoding
/leetcode/Array/268. 0~n中缺失的数字(鸽子洞, 贪心).py
1,685
3.546875
4
""" 这个题目说的是,从 0 到 n 这 n+1 个整数中去掉一个,然后把剩下的 n 个整数放进一个长度为 n 的数组,给你这个数组,你要找到那个去掉的整数。 比如说,给你的数组是: 4, 1, 0, 2 这里的数组长度是 4,说明这是从 0 到 4 中去掉一个数字后形成的数组。数组中缺失的数字是 3,因此我们要返回 3。 """ class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ if not ...
b2b94d1baa0160b88b8ac716c27f4bd75a0fe056
Andrewlearning/Leetcoding
/leetcode/BinarySearch/没有明确target,需要返回某个位置(左右区间)/378. 有序矩阵中第K小的元素(左边界, 第k小).py
1,874
3.953125
4
""" Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. "...
9d90c302779994d0c757adec91bdefc70fbeea57
Andrewlearning/Leetcoding
/leetcode/Array/Sort/147. 单链表排序(插入排序).py
1,556
3.90625
4
# Definition for singly-LinkedList. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(0) cur = hea...
5e5094e65cc504a2639fdd1fd7dd52d5484badf8
Andrewlearning/Leetcoding
/leetcode/Array/two pointers/925. 长按键入.py
1,214
3.921875
4
""" 你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。   示例 1: 输入:name = "alex", typed = "aaleex" 输出:true 解释:'alex' 中的 'a' 和 'e' 被长按。 """ class Solution(object): def isLongPressedName(self, name, typed): """ :type name: str...
fc8d8a728e7311da7dcd87a4c640dcde361e95b6
Andrewlearning/Leetcoding
/leetcode/Hashmap/prefixSum + hashmap(一般解决和为某定值的题目)/两数之和类型/525. 0,1数量相等的最长子串.py
1,314
3.6875
4
""" Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 给一个binary数组,找出最长的子数组,0,1数量相等 链接:https://www.jianshu.com/p/7108226dc023 """ class Solution(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ ...
b4e3b80a4505c7b33039388e72433921b2e8ebc2
Andrewlearning/Leetcoding
/leetcode/BinarySearch/有明确target值(左右边界都可)/74. 有序二位数组中的查找(2D转1D).py
764
3.796875
4
""" 题目说明了下一行的所有值比上一行的所有值都要大 这题应该用二分查找来做 """ class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ lr = len(matrix) lc = len(matrix[0]) l = 0 r = lr * lc - 1 ...
aeb4191f91986f04175813557c891acff3bdcaf8
Andrewlearning/Leetcoding
/剑指offer/面试题53 - I. 在排序数组中查找数字 I(34).py
2,281
3.75
4
""" 统计一个数字在排序数组中出现的次数。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: 0 """ class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target not in nums...
78e0cc5170a67bfaf9f3e26ea1e687fd9edfe352
Andrewlearning/Leetcoding
/leetcode/Array/区间(扫描线,堆)/57. 区间插入.py
1,394
3.71875
4
""" Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]] 注意:这题题目给的intervals是排序好的 """ class S...
249e053c9767e74ee17a328edc601e4ccfc153c3
Andrewlearning/Leetcoding
/leetcode/DP/354m. 俄罗斯套娃信封问题(二维最长递增子序列300).py
3,447
4.28125
4
""" You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater(严格大于哦) than the width and height of the other envelope. What is the maximum number of envelopes can you Russian doll? (put...
03c2c60dde50154bef82e146bd5058eb1d39b8fb
Andrewlearning/Leetcoding
/leetcode/Array/滑动窗口/245m. 最短单词距离III(相同单词距离).py
1,151
4.03125
4
""" 给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。 word1 和 word2 是有可能相同的,并且它们将分别表示为列表中两个独立的单词。 示例: 假设 words = ["practice", "makes", "perfect", "coding", "makes"]. 输入: word1 = “makes”, word2 = “coding” 输出: 1 输入: word1 = "makes", word2 = "makes" 输出: 3 """ import sys class Solution(object): def shortestWordDistance...
2b9bc80233c23683b651454f48757a54070abf76
Andrewlearning/Leetcoding
/leetcode/Design/341m. 扁平化嵌套列表迭代器(有点口水).py
1,699
4.09375
4
""" 给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。 示例 1: 输入: [[1,1],2,[1,1]] 输出: [1,1,2,1,1] 解释: 通过重复调用next 直到hasNext 返回 false,next返回的元素的顺序应该是: [1,1,2,1,1]。 示例 2: 输入: [1,[4,[6]]] 输出: [1,4,6] 解释: 通过重复调用next直到hasNext 返回 false,next返回的元素的顺序应该是: [1,4,6]。 """ class NestedIterator...
c528fbb15c54b157065d7403aca165219a32e132
Andrewlearning/Leetcoding
/十大排序/mergeSort.py
564
4.0625
4
def mergesort(data): if len(data) == 1: return data middle = len(data) // 2 left = mergesort(data[:middle]) right = mergesort(data[middle:]) return merge(left, right) def merge(left, right): l = 0 r = 0 result = [] while l <= len(left) - 1 and r <= len(right) - 1: ...
bb75d00ed332a960537fd55e27269bb1c43ddde0
Andrewlearning/Leetcoding
/leetcode/Random/381m. 常数时间插入、删除和获取随机元素II(有重复).py
3,364
4.25
4
""" 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。 注意: 允许出现重复元素。 insert(val):向集合中插入元素 val。 remove(val):当 val 存在时,从集合中移除一个 val。 getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。 / 初始化一个空的集合。 RandomizedCollection collection = new RandomizedCollection(); // 向集合中插入 1 。返回 true 表示集合不包含 1 。 collection.insert(1); // 向集合中插入另一个 1 ...
03767ffc403a8c9491e19135d401ecad787c5b03
Andrewlearning/Leetcoding
/leetcode/BitOperation/477m. 汉明距离总和(分组相乘,省时).py
1,270
4.09375
4
""" 两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中,任意两个数之间汉明距离的总和。 示例: 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中,4表示为0100,14表示为1110,2表示为0010。(这样表示是为了体现后四位之间关系) 所以答案为: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. """ class Solution(object): def totalHammingDistance(self, nums): ...
a21ce8aa0a98e31eb5be4d7e6070a897d2309535
Andrewlearning/Leetcoding
/leetcode/Math/基础/7. 整数反转.py
1,005
3.6875
4
""" 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 示例1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ sign = 1 if x > 0 else -1 x = abs(x) res = 0 while x > 0: res = ...
9caf35d4d8c009c60d85e873bc373b8f18b9aba3
Andrewlearning/Leetcoding
/一些总结/二叉树的三种遍历及非递归写法.py
2,517
3.984375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def pre(node): if node == None: return print(node.val) pre(node.left) pre(node.right) #root left right def preOrder(root): if root == None...
3f7b4c324ed65899c5c1e653b71d566c1ca67e42
Andrewlearning/Leetcoding
/算法基础课/1.基础算法/AcWing 788. 逆序对的数量.py
1,310
3.9375
4
def merge_sort(arr, l, r, temp): if l >= r: return # 1.选取中点 mid = (l + r) // 2 # 2.递归排序 merge_sort(arr, l, mid, temp) merge_sort(arr, mid + 1, r, temp) # 把变量全局化 global res # 3.归并操作,原数组的左右两半指针 i = l j = mid + 1 # temp数组的指针 k = 0 while (i <= mid and j <= r...
a8950e6b5e56dec4407818997c0ae98cb3f577d1
Andrewlearning/Leetcoding
/leetcode/Array/350. 两个数组的交集II(hashmap).py
2,315
3.90625
4
""" 给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 与第一题的差别就是,这里是真的返回相同部分,而不是光返回一个set() 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [4,9] """ import collections class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type n...
b130cb69ff94bf8d1130e9084bc11738c7ffcbe8
Andrewlearning/Leetcoding
/leetcode/Heap/703. 数据流中第 K 大的元素 .py
2,251
3.984375
4
""" Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call t...
28873f92fac95443738abb44fd4000a3451043f2
Andrewlearning/Leetcoding
/算法基础课/3.搜索与图论/AcWing 848. 有向图的拓扑序列.py
585
3.609375
4
""" 有向无环图,被称为拓扑图,一定存在一个拓扑序列 假如我们把一个图按照拓扑序排好,那么一定是从前面指向后面的 度数: 入度:一个点有多少条边指向自己 出度:一个点有多少条边出去 所有入度为0的点都可以作为拓扑排序排最前面的点 queue <- 所有入度为0的点 while queue: tt = queue.popleft() 枚举tt的所有出边: 删除tt -> 下一个点的边 d[j]-- if d[j] == 0: queue <- j 一个有向无环图一定至少存在一个入度为0的点 """
a0c5eea6f57c8b5c3ac522a9b191ced204ad7609
Andrewlearning/Leetcoding
/leetcode/BackTracking(DFS)/47. 全排列 II(有重复).py
1,722
3.625
4
""" 给定一个可包含重复数字的序列,返回所有不重复的全排列。 示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] """ class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [] self.res = [] nums....
3607751cad74e7cdcd16c708ef970f0ebfebaff8
Andrewlearning/Leetcoding
/leetcode/Stack/单调栈(monotonic stack)/42. 接雨水I(单调栈).py
2,617
3.765625
4
class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ # stack只有碰到比stack[-1]小的,才会保留 # 碰到比stack[-1]大的,说明都有可能会构成一个凹槽 stack = [] res = 0 for i in range(len(height)): # 当栈不为空 # 且当前元素高度 >...
31c1e2dc8f1a2469ae4f2c4cf21c3080831e9a7c
Andrewlearning/Leetcoding
/leetcode/Tree/100. 相同的树.py
1,200
4.0625
4
""" 给定两个二叉树,编写一个函数来检验它们是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例 1: 输入: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] 输出: true """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left ...
803bfca8d8dca49e46bce48ced11b16f77908243
Andrewlearning/Leetcoding
/leetcode/Tree/古城-树的遍历/非递归遍历二叉树/285. 二叉搜索树的后继节点(迭代).py
2,084
3.640625
4
""" 给你一个二叉搜索树和其中的某一个结点,请你找出该结点在树 中顺序后继的节点。 结点 p 的后继是值比 p.val 大的结点中键值最小的结点。 """ import sys class Solution(object): def inorderSuccessor(self, root, p): """ :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ # 情况1,p有右子树,我们要找到右子树的最左节点,那么这就是结果了 if p.rig...
550ff45a53e8ad9640676a43b7615c204e9bc176
Andrewlearning/Leetcoding
/leetcode/BitOperation/389. Find the Difference.py
734
3.71875
4
""" 给你两个字符串,让你找到里面多出现的一个字符 Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added. """ class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ res = 0 for char in s + t: ...
ddc89b17a98a81a0e4b2141e487c0c2948d0621a
lfr4704/python_practice_problems
/algorithms.py
1,579
4.375
4
import sys; import timeit; # Big-O notation describes how quickly runtime will grow relative to the input as the input gets arbitrarily large. def sum1(n): #take an input of n and return the sume of the numbers from 0 to n final_sum = 0; for x in range(n+1): # this is a O(n) final_sum += x re...
894247a8aaeb6e40cc91622e9fbf743a8a4e7c81
Perveance/pycalculator
/expression.py
1,274
3.828125
4
#!/usr/local/bin/python3 import sys def calc(val1, val2, op): if op == '+': return val1 + val2 elif op == '-': return val1 - val2 elif op == '*': return val1 * val2 def unwind(operators, operands): while len(operands) > 0 and len(operators) > 0: valr = int(operands...
77eae211ffc3efce65fbf068962e7a2d6edc144f
Nayald/algorithm-portfolio
/leetcode/daily challenges/2020-11/02-insertion-sort-list.py
708
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head: return head dummy = ListNode(float("-inf")...
4a1512fb120f7325b58c13c3a8b61c61e857fc25
Nayald/algorithm-portfolio
/leetcode/daily challenges/2020-12/06-populating-next-right-pointers-in-each-node-ii.py
872
3.8125
4
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ from collections import deque class Solution: def connect(self, root...
76d554da5c5271877b10b96ce759a0ce9e99f969
Nayald/algorithm-portfolio
/leetcode/contests/bi-49/2-sentence-similarity-iii.py
464
3.546875
4
from collections import deque class Solution: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: s1 = deque(sentence1.split()) s2 = deque(sentence2.split()) while s1 and s2 and s1[0] == s2[0]: s1.popleft() s2.popleft() ...
b37e554764d320f28d1ae19d4cbbcb8a9dca1b5b
Nayald/algorithm-portfolio
/leetcode/daily challenges/2020-10/22-minimum-depth-of-binary-tree.py
801
3.765625
4
# 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 minDepth(self, root: TreeNode) -> int: if not root: return 0 min_de...
584a990f37d5f176a1e378c05b6178b575150cab
Nayald/algorithm-portfolio
/leetcode/daily challenges/2020-12/03-increasing-order-search-tree.py
1,344
3.671875
4
# 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 increasingBST(self, root: TreeNode) -> TreeNode: stack = [] head = TreeNode(None) ...
208bb334e55771d63cd228c52f99f76bc3f8ae68
Nayald/algorithm-portfolio
/leetcode/daily challenges/2020-09/21-car-pooling.py
556
3.796875
4
from queue import PriorityQueue class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: if not trips: return True q = PriorityQueue() for num_passengers, start_location, end_location in trips: q.put((start_location, num_passenge...
ed4d64051567535e317ef52489b278f05bf67ca8
starpak1/zadania
/2.py
704
3.859375
4
#!/usr/bin/env python3 import argparse parser = argparse.ArgumentParser(description = 'Simply program , reverse text') parser.add_argument('-n', help='file name', type=str) parser.add_argument('-l', help = 'line number', type=int) parser.add_argument('-v', help = 'file version', type=str) args = parser.parse_args() ...
833354ee5752f728bb19b0dc7adaa396b1f3fd79
rsdenijs/Python-Snippets
/snippets.py
462
3.546875
4
from collections import OrderedDict def partition(iterable,*conditions): '''Returns a list with the elements that satisfy each of condition. Conditions are assumed to be exclusive''' d= OrderedDict((i,list())for i in range(len(conditions))) for e in iterable: for i,condition in enume...
5448334fd7a1312cd047ccc3ce4d6d930ba3e15b
h-ohsaki/dtnsim
/dtnsim/mobility/levywalk.py
2,056
3.578125
4
#!/usr/bin/env python3 # # A mobility class for Levy walk. # Copyright (c) 2011-2015, Hiroyuki Ohsaki. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
03e16458e7104d00390d7c8625c57090b819fe52
yaravind/machine-learning-a-z
/python/logistic-regression.py
1,783
3.859375
4
#!/usr/bin/python # https://machinelearningmastery.com/implement-logistic-regression-stochastic-gradient-descent-scratch-python/ from math import exp # Make a prediction with coefficients def predict(row, coefficients): yhat = coefficients[0] for i in range(len(row) - 1): yhat += coefficients[i + 1] *...
2fdf9fa27eb4263df6753ee0fdc93cd8642eeb01
ankeshrpd/SquadStack_ParkingLot
/lot/car.py
461
3.78125
4
""" Contains the car class and its relevant functionality """ class Car: """ Contains all the attributes for a Car """ def __init__(self, car_id: str, driver_age: int): """ Initializes a new car object """ self.car_id = car_id self.driver_age = driver_age self.slot = None ...
f52d6ce455d14c94c8394cc120c76603379ae903
lingchen1dian21fen/study
/data-structure/python/cbo/my/recursive.py
1,958
3.671875
4
# -*-coding:utf-8 -*- ''' Created on 2020-08-06 14:28 @author: chengbo - 05 递归 问题:编程实现斐波那契数列求值f(n)=f(n-1)+f(n-2) 问题:编程实现求阶乘n! 问题:编程实现一组数据集合的全排列 ''' def fibonacci(n): assert n >= 1 if n < 3: return 1 return fibonacci(n - 1) + fibonacci(n - ...
a9ac31cd7a6543de13c6263553af08d4b4451b1d
PinaevPavel/HomeWorks
/111.py
207
3.71875
4
def fib(): """ :return: 0, 1, 1, 2, 3, 5, 8, 13, 21 ... """ a, b = 0, 1 while True: yield a a, b = b, a + b x = fib() print(next(x)) print(next(x)) # OOPS print(next(x))
c66ddfe603b7cc276ea14278c9af66c93e1fc5f1
PinaevPavel/HomeWorks
/task_31..py
273
3.640625
4
import sys def get_numbers(): start = 0 end = 10 step = 1 while start < end: yield start start += step gen = get_numbers() print(next(gen)) print(next(gen)) print(list(gen)) try: gen = get_numbers() for i in gen: print(i) except StopIteration as e: print(e)
8d5f6b4a0e0fa3955cbd72569f1bdf597382f563
PinaevPavel/HomeWorks
/task_11.py
345
3.546875
4
def error(value=None): x = None import random if value == None: x = random.randint(1, 3) try: if x == 1: raise ValueError elif x == 2: raise TypeError elif x == 3: raise RuntimeError else: 1 /int(value) except ValueError: print('123') except TypeError: print('321') except RuntimeError: ...
c2f622f51bbddc54b0199c4e0e2982bc2ebfa030
qdm12/courses
/Fundamental Algorithms/Lesson-03/algorithms.py
2,479
3.875
4
from operator import itemgetter from math import floor def radix_sort_alpha(words): l = len(words[0]) for w in words: if len(w) != l: raise Exception("All words should be of same length") for i in range(l, 0, -1): words = sorted(words, key=itemgetter(i - 1)) ...
9f74ef1d29bd96097e05c471b6fbf490ffa7908f
james-darpino/Game_Design1
/Ascend_the_Helix/ascend_the_helix.py
24,490
3.8125
4
""" A. Authors: James D'Arpino and Hannah Youssef B. Version: Alpha 1.0 C. Description of code: This displays the player within the brown block(ladder). The player needs to avoid the falling blocks. If the player collides with a falling block, he/she dies. The goal for the alpha, is to get the highest score. D. Desc...
771b737aad1b5cb27ce11ade5e712d9ca7b8c659
Xiaosheng-Zhao/Astro
/Ionization.py
5,155
3.53125
4
import numpy as np import matplotlib.pyplot as plt class non_linear(object): ''' This class contains three non-linear equation solver: Bisection, Secant method, Newton-Raphson method. In order to solve the ionization equilibrium problem. ''' def __init__(self, N = 100, Tor =10**(-15), T=30, n=10**5...
f515d4b7d05a38c542dc8663a78d6d31a83d6fd4
KateKopteva/Lesson_5
/task_5_1.py
549
3.9375
4
while True: x, y = float(input('x= ')), float(input('y= ')) sign = input('Знак операции (+, -, /, *): ') if sign in ('+', '-', '/', '*'): if sign == '+': print(x+y) elif sign == '-0:': print(x-y) elif sign == '*': print(x*y) elif sign == '/...
6872171dfc8095134dc2d5ed117760b0a9a07dc0
amrus/dailydiceroll
/dailydiceroll.py
384
3.734375
4
# Daily Dice Roll (regular 6 die roll) # author: Alana Rust (amrus) # date: 01-20-2021 import random def diceRoll(): playDice = int(input('To play the Daily Dice Roll, press 1 or press 0 to end')) while playDice == 1 | playDice == 0 if playDice == 1: num = random.randint(1, 6) p...
42a2c7a436166da19d58cdebc945b51a1d0aa92d
KratosMultiphysics/Kratos
/applications/OptimizationApplication/python_scripts/utilities/buffered_dict.py
18,108
3.65625
4
from __future__ import annotations from typing import Any class BufferedDict: """Buffered dict container with buffered data ability Instances of this can hold (str, Any) data pairs in hierachychal data structure where each sub item can have their own buffer sizes. Hence, Different sub structures can h...
2e1392edbd5d383346bee81f1d7bb4fb386cc89a
KMFtcy/100examples
/test_18.py
481
4.0625
4
number = int(raw_input("Please input a number:")) repeat_times = int(raw_input("Please imput repeating time:")) sum = 0 digit_num = 0 temp_num = number while temp_num != 0: temp_num /= 10 digit_num += 1 print "sum = ", temp_num = 0 temp_num *= 10**digit_num temp_num += number sum += temp_num print "{}".format(...
c4480347c731cb701a42b4d2ae9279256d30c4c8
KMFtcy/100examples
/test_7.py
189
3.8125
4
L1 = [0,1,2,3,4,5,6,7,8,9] L2 = ['h','e','l','l','o'] print "List 1 is :" print L1[:] print "List 2 is :" print L2[:] print "Copy List 1 to List 2" L2 = L1[:] print "Now List 2 is ", L2
6000ff5aca0d36c1c18d85ce21042cca5c807cfc
ggupta01/ML
/decisionTree.py
1,114
3.796875
4
# Decision Tree # It is a type of supervised learning algorithm that is mostly used for classification problems. Surprisingly, it works for both categorical and continuous dependent variables. In this algorithm, we split the population into two or more homogeneous sets. This is done based on most significant attributes...
7e8d37c9903f02bd3e9726cc068f5a8a7af06cb8
bullet1337/codewars
/katas/Python/6 kyu/Dbftbs Djqifs 546937989c0b6ab3c5000183.py
290
3.578125
4
# https://www.codewars.com/kata/546937989c0b6ab3c5000183 def encryptor(key, message): def encode(l): return chr(ord('A' if l.isupper() else 'a') + (ord(l) - ord('A' if l.isupper() else 'a') + key) % 26) return ''.join(encode(l) if l.isalpha() else l for l in message)
e9800de745aa5d7618e1c5474af290fbbc97afb6
bullet1337/codewars
/katas/Python/4 kyu/Sudoku Solution Validator 529bf0e9bdf7657179000008.py
432
3.625
4
# https://www.codewars.com/kata/529bf0e9bdf7657179000008 import numpy as np def validSolution(board): board = np.array(board) for i in range(9): if len(set(board[i, :])) != 9 or len(set(board[:, i])) != 9: return False for i in range(3): for j in range(3): if len(...
776d53f91fc8223b77345d9b1dc705119018ad95
bullet1337/codewars
/katas/Python/5 kyu/Caesar Cipher Helper 526d42b6526963598d0004db.py
474
3.734375
4
# https://www.codewars.com/kata/526d42b6526963598d0004db class CaesarCipher(object): def __init__(self, shift): self.shift = shift def cipher(self, text, mode): return ''.join(chr(ord('A') + (ord(l.upper()) - ord('A') + self.shift * (1 if mode else -1)) % 26) if l.isalpha() else l for l in ...
78bf8a614d0641f70c656dd281e3bfc6add28497
bullet1337/codewars
/katas/Python/6 kyu/Triple trouble 55d5434f269c0c3f1b000058.py
194
3.859375
4
# https://www.codewars.com/kata/55d5434f269c0c3f1b000058 def triple_double(num1, num2): return any(chr(c) * 3 in str(num1) and chr(c) * 2 in str(num2) for c in range(ord('0'), ord('9') + 1))
dd312825fc5739546c7612f6e89ea07772365b75
bullet1337/codewars
/katas/Python/8 kyu/Are You Playing Banjo 53af2b8861023f1d88000832.py
180
3.640625
4
# https://www.codewars.com/kata/53af2b8861023f1d88000832 def areYouPlayingBanjo(name): return name + (' plays banjo' if name[0].lower() == 'r' else ' does not play banjo')
b51560157eb5b5f155d10f14e899aff73b165ce5
bullet1337/codewars
/katas/Python/3 kyu/GET TO THE CHOPPA 5573f28798d3a46a4900007a.py
997
3.65625
4
# https://www.codewars.com/kata/5573f28798d3a46a4900007a import collections def find_shortest_path(grid, start_node, end_node): if not (grid and start_node and end_node): return [] stack = collections.deque([start_node]) moves = [(0, 1), (1, 0), (0, -1), (-1, 0)] visited = [[False for _ in r...
8302e5c88b9743dfd843008e7e486e1557929223
bullet1337/codewars
/katas/Python/5 kyu/Binary search tree validation 588534713472944a9e000029.py
780
3.578125
4
# https://www.codewars.com/kata/588534713472944a9e000029 class T: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def is_bst(node): def is_bst_asc(node, min=None, max=None): return node is None or (min is None or node.val...
b3b3194ac78d477a79cdd8efb281017b08cb666b
bullet1337/codewars
/katas/Python/7 kyu/Nickname Generator 593b1909e68ff627c9000186.py
183
3.515625
4
# https://www.codewars.com/kata/593b1909e68ff627c9000186 def nickname_generator(name): return name[:3 + (name[2].lower() in 'aioue')] if len(name) > 3 else 'Error: Name too short'
b10921330f23547f44e70830241f1cfdf40fd505
bullet1337/codewars
/katas/Python/6 kyu/1 Strings Find The Longest Substring and Required Data 59167d51c63c18af32000055.py
492
3.65625
4
# https://www.codewars.com/kata/59167d51c63c18af32000055 import itertools def find_longest_substr(s): start = 0 char = None length = 0 current_index = 0 for k, g in itertools.groupby(s): g = list(g) if g[0] not in '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' and len(g) > length: ...
65624b6bd562a6aa25b9d12787c904e09a215c6f
bullet1337/codewars
/katas/Python/4 kyu/Sums of Perfect Squares 5a3af5b1ee1aaeabfe000084.py
483
3.546875
4
# https://www.codewars.com/kata/5a3af5b1ee1aaeabfe000084 from math import sqrt def sum_of_squares(n): n_sqrt = int(sqrt(n)) if n == n_sqrt * n_sqrt: return 1 div, mod = divmod(n, 4) while mod == 0: div, mod = divmod(div, 4) if (div * 4 + mod) % 8 == 7: return 4 for i...
bf8909cbae6c0654e3e00c9f8dde738b3e3aab0e
bullet1337/codewars
/katas/Python/6 kyu/Find the unique number 585d7d5adb20cf33cb000235.py
172
3.5625
4
# https://www.codewars.com/kata/585d7d5adb20cf33cb000235 from collections import Counter def find_uniq(arr): return next(k for k, v in Counter(arr).items() if v == 1)
b78c19de2066a11e1ee0020c50c4d0331b827734
bullet1337/codewars
/katas/Python/6 kyu/Title Case 5202ef17a402dd033c000009.py
404
3.734375
4
# https://www.codewars.com/kata/5202ef17a402dd033c000009 import re def title_case(title, minor_words=''): minor_words = set(map(str.lower, minor_words.split())) def repl(m): if m.start() == 0 or m.group().lower() not in minor_words: return m.group().title() else: return...
d2c60bcbfbabd90debf33dda53a3a9962dad3579
bullet1337/codewars
/katas/Python/7 kyu/Convert a linked list to a string 582c297e56373f0426000098.py
386
3.59375
4
# https://www.codewars.com/kata/582c297e56373f0426000098 class Node(): def __init__(self, data, next = None): self.data = data self.next = next def iter_linked_list(current): while current is not None: yield current.data current = current.next yield None def stringify(lis...
22a87e9a28e90b628d505717e2fb6c6df9ed7614
bullet1337/codewars
/katas/Python/8 kyu/Powers of 2 57a083a57cb1f31db7000028.py
120
3.640625
4
# https://www.codewars.com/kata/57a083a57cb1f31db7000028 def powers_of_two(n): return [2 ** x for x in range(n + 1)]
92753b250d6e965a0f43b46ce32783fa4e4713eb
bullet1337/codewars
/katas/Python/7 kyu/Linked Lists Move Node 55da347204760ba494000038.py
466
3.5
4
# https://www.codewars.com/kata/55da347204760ba494000038 class Node(object): def __init__(self, data): self.data = data self.next = None class Context(object): def __init__(self, source, dest): self.source = source self.dest = dest def move_node(source, dest):...
4e5cf75b27a378aa55056cbe85e97cd5d76226fe
xzsfd2457/python-programming
/Beginner/codekata/set-5/whether it is power of 2.py
97
3.78125
4
n=int(raw_input()) v="no" for i in range(n+1): r=2**i if(n==r): v="yes" print(v)
377b6a84cd10eeaacb7dd2c4f2316f246707e3d7
choupijiang/algorithm
/src/SortSelect/Sort.py
3,257
4.28125
4
#! /usr/bin/env python # -*- coding:utf-8 -*- import sys sys.path.append("../linkedList") from LinkedQueue import LinkedQueue # ------------------Array-Based Implementation of Merge-Sort---------------------- # def merge(S1, S2, S): # """ # Merge two sorted Python lists S1 and S2 into properly sized list S. # :pa...
ae5578df978b375c8dd601b246927d1051c5e89f
choupijiang/algorithm
/src/binary_search.py
698
4.0625
4
# !/usr/bin/env python # -*- coding:utf-8 -*- def binary_search(data, target, low, high): ''' Return True if target is found in indicated potion of a Python list :param data: :param target: :param low: :param high: :return: ''' if low > high: return False else: m...
653e3d0029d4694c211c2ee40bbe3bfc407f9d2d
erfilho/URIjudge
/Iniciante/1004.py
79
3.59375
4
num = int(input()) num2 = int(input()) prod = num*num2 print(f'PROD = {prod}')
f4dde04e2a331780b75392e9811cc989a0ed452f
Schuture/Data-structure
/数据结构/字典树(前缀树).py
2,239
4.0625
4
'''字典树''' class Trie(): def __init__(self): self.root = {} def insert(self, x): p = self.root i = 0 while i < len(x) - 1: if x[i] not in p.keys() and x[i] + '!' not in p.keys(): # 没有标识的边,就添加边 p[x[i]] = {} if x[i] in p.keys(): # 有标识...
dfa1fc250b5e023090418ba0ed9c135adac6ac83
Schuture/Data-structure
/数据结构/堆+优先队列.py
4,545
3.703125
4
import random class Heap(): # 最大堆 def __init__(self, array): self.array = array self.heapsize = len(array) # 这里堆的插入功能尚未实现 self.length = len(array) # 长度大于等于heapsize,有不使用的元素 self.build() def parent(self, i): return (i + 1) // 2 - 1 def left(self, i): ...
edbe86de9667f66d3cdcdcd120ff76986ab4137e
Schuture/Data-structure
/图算法/图搜索.py
2,937
4.125
4
class Node(): # 单向链表节点 def __init__(self): self.color = 'white' self.d = float('Inf') #与中心点的距离 self.pi = None # 图中的父节点 self.next = None # 只能赋值Node() ''' 循环队列,调用方式如下: Q = Queue() Q.enqueue(5) 往队尾加一个元素 Q.dequeue() 删除队头元素''' class Queue(): def __init__(sel...
46c546fa708e20666573afafc0cfa9135ffa305c
ntkjer/ds-algos
/searching/symbol_tables/binary_search_st/binary_search_symbol_table.py
1,602
3.96875
4
__author__ = "niels kjer" class BinarySearchST(object): def __init__(self, k=[], v=[], n=0): self.keys = k self.values = v self.n = n def is_empty(self): return self.n == 0 def size(self): return self.n def get(self, key): if self.is_empty(): ...
770af7281b840c1a2f71733d33af40b31f0e5577
ntkjer/ds-algos
/sorting/merge2.py
1,526
4.09375
4
def sort(arr): #merge_sort_top_down(arr, 0, len(arr)-1) merge_sort_bottom_up(arr) def merge_sort_bottom_up(arr): n = len(arr) length = 1 while length < n: lo = 0 while lo < n-length: merge(arr, lo, lo+length-1, min(lo+length+length-1, n-1)) lo += length + i...
3a98c3b939d18846ea7467ae97b1eaad034330e7
ntkjer/ds-algos
/data_structures/linkedlist.py
11,727
4.09375
4
from node import Node class LinkedList(object): """ A singly-linked list that relies on nodes. """ def __init__(self, head=None): self.head = head self.n = 0 if self.head is not None: self.set_size() def reset_data(self, head : Node): self.delete_list() self.hea...
4459792eff08ed45ddf0bec5cb0337a44e6515ae
olexandrvaitovich/homework
/module7.py
232
4.21875
4
def calculate_sqr(n): """ Calculate squre of a positive integer recursively using n^2 = (n-1)^2 + 2(n-1)+ 1 formula """ if n == 1: return 1 else: return calculate_sqr(n - 1) + 2 * (n - 1) + 1
1328547719c8b34254c5e6201470bceb2adc19d7
MatheusHALeal/LAB01
/maximo.py
191
3.578125
4
def maximo(array): maximo = array[0] for i in range: if i > maximo: maximo = i print maximo def minimo(array): minimo = array[0] for i in range: if i < minimo: minimo = i
032918d534a5521d2ec862a0c0496193f7130c3a
CraigA27/Week_02_Homework
/classes/room.py
1,301
3.53125
4
from classes.guest import Guest from classes.song import Song class Room: def __init__(self, input_room_name, input_room_price, input_room_capacity): self.name = input_room_name self.price = input_room_price self.capacity = input_room_capacity self.till = [] self.guests = ...
0ae3bb49ff61d23b88ab7875f0acc7274b75a1f7
561nano/Udemy_Python
/Section 3/Section 3 Code.py
8,972
4.25
4
x = 7 / 4 print(x) x = 7 // 4 # Floor Division, floor means = truncates the decimal without rounding, and returns an integer result. print(x) x = 7 % 4 # Returns the remainder of division print(f"The remainder of 7/3 is {x}") x = 2 ** 3 # ** = to the power (2^3) print(f"2 to the power of 3 = {x}") x = 100 ** 0.5 ...
a7db0c7ff8613f985b471d9fa48794891a9db2a9
thorakristin/Forritun
/age.py
251
4.0625
4
num = int(input("Enter your age: ")) if num >= 0 and num <=34: print("Young") elif num >= 35 and num <= 50: print("Mature") elif num >= 51 and num <= 69: print("Middle-aged") elif num >= 70: print("Old") else: print("Invalid age")
b094f8b1c23aef31306b49ed856a4f2ce5ab4975
thorakristin/Forritun
/Tímaverkefni/Tímaverk 2-6.py
407
4.09375
4
d1 = int(input("Input first dice: ")) # Do not change this line d2 = int(input("Input second dice: ")) # Do not change this line sum_d = d1 + d2 if (d1 <= 0 or d1 > 6) or (d2 <= 0 or d2 > 6): print("Invalid input") elif sum_d == 7 or sum_d == 11: print("Winner") elif sum_d == 2 or sum_d == 3 or sum_d == 12: ...
998e9c34ff2a760f8a3f08945da25c12dc88fa6e
thorakristin/Forritun
/series.py
251
3.671875
4
first = int(input("First ")) step = int(input("Step: ")) sum = 1 numb = 0 for i in range(first,sum,step): numb = numb + i if numb >= 100: print(numb end" ":) else: print("2") sum +=1
74b3d3d1474611815478c8f6197e99f7508d04da
thorakristin/Forritun
/Glærur-verkefni/Glærur1-rigning.py
221
3.5625
4
inches_str = input("How many inches of rain have fallen: ") inches_int = int(inches_str) volume = (inches_int/12)*43560 gallons = volume * 7,48051945 print(inches_int," inches of rain on 1 acre is", gallons, "gallons")
bd9122c30914b1b2edd8983bb52208c35522bbef
lowieGon/assign1-3
/assign2.py
325
4.03125
4
Apple = float(input("Enter apple quantity: ")) Orange = float(input("Enter orange quantity: ")) AppleCost= 20.00* Apple OrangeCost= 25.00* Orange TotalAmount= AppleCost + OrangeCost format_TotalAmount= "{: .2f}".format(TotalAmount) float_TotalAmount = float(format_TotalAmount) print("Total Amount is: ", format_TotalAm...
350caa2ceff6bd5a7a05be797bd316c736410ffe
richard1230/NLP_summary
/python字符串操作/1清除与替换.py
1,041
4.34375
4
str1 = " hello world, hello, my name is Richard! " print(str1) #去除首尾所有空格 print(str1.strip()) #去除首部所有空格 print(str1.lstrip()) #去除尾部所有空格 print(str1.rstrip()) #也可以去掉一些特殊符号 print(str1.strip().rstrip('!')) #方法可以组合使用 先去掉首尾空格 在去掉尾部! #注意不能直接str.rstrip('!'),因为此时str的尾部是空格,得先去掉空格再去叹号。 #字符串替换 print(str1) print(str1.replace('h...
02c2e47dc242479ec5bfe30f53dbdcb57999cd22
LelsersLasers/Pong
/network.py
1,298
3.640625
4
""" Description: This file allows the server and client to connect with each other and send/receive data on the game. """ import socket import pickle # Sends objects over a network class Network(): def __init__(self, serverIP): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
110606dc8c2150216752c843a0ea816ea19938ef
mmastin/Tutorials
/tutorial1.py
2,052
3.78125
4
nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9] # my_list = [] # for n in nums: # my_list.append(n) # print(my_list) # my_list = [n for n in nums] # print(my_list) # n^2 for each in n in nums # my_list = [n*n for n in nums] # print(my_list) # my_list = map(lambda n: n*n, nums) # print(my_list) # I want n for each n i...
70e1429f2fd18a36738401a7fe733336603f9822
amber1710/File-Handling
/files.py
1,291
3.765625
4
from tkinter import * window = Tk() window.title('Text Files') window.geometry("500x400") window.configure(background="pink") heading=Label(text="My weekend activities" , bg = "light grey" , fg="black") heading.pack() def create(): file=open('/home/user/Desktop/my_weekend_activities.txt','w+') file.write("My w...
6db1ecdd0ad2458bc716f7972a08e86f092ba40b
davidkah/checkpiont
/main4.py
114
3.75
4
char = input("entre un mot:") n = int(input("entre un nombre:")) miss_char = char[0:n]+char[n+1:] print(miss_char)
1a0da078f182418e8d0ecb5605b3406a4f98b3b9
kndidox/project_euler
/tarea_007.py
955
4
4
""" Escriba un programa para simular el tiro de dos dados. El programa debe utilizar rand para tirar el primer dado, y de nuevo para tirar el segundo dado. Después debe calcularse la suma de los dos valores. [Nota: cada dado puede mostrar un valor entero del 1 al 6, por lo que la suma de los valores variará del 2 al 12...
a76cd6ec0488ad80a3782fb07b28aaebda903a05
brett-stephen/NLTK-
/BrownCorpusSummarization.py
1,186
3.546875
4
#import nltk #nltk.download() #https://www.youtube.com/watch?v=FLZvOKSCkxY from nltk.tokenize import sent_tokenize, word_tokenize from nltk.corpus import stopwords from nltk.corpus import brown totalTokens = 0 example_test = "Hello Mr. Smith, how are you doing today? The weather is great and Python is awesom...
01d9030aa89da902667a6ea05a45bbd9761162ef
DerekHunterIcon/CoffeeAndCode
/Week_1/if_statements.py
239
4.1875
4
x = 5 y = 2 if x < y: print "x is less than y" else print "x is greater than or equal to y" isTrue = True if isTrue: print "It's True" else: print "It's False" isTrue = False if isTrue: print "It's True" else: print "It's False"
f2ed037552b3a8fdd37b776d5b9df5709b0e494e
SamWaggoner/125_HW6
/Waggoner_hw6a.py
2,742
4.1875
4
# This is the updated version that I made on 7/2/21 # This program will ask input for a list then determine the mode. def determinemode(): numlist = [] freqlist = [] print("Hello! I will calculate the longest sequence of numbers in a list.") print("Type your list of numbers and then type \"end\"."...