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 |
|---|---|---|---|---|---|---|
84b5cff94bcf6c4010f5d74a877658eb01203ef5 | jdanray/leetcode | /reverseWords3.py | 247 | 3.671875 | 4 | # https://leetcode.com/problems/reverse-words-in-a-string-iii/
class Solution:
def reverseWords(self, s):
blank = ' '
r = ''
w = ''
for c in s:
if c == blank:
r += w
r += blank
w = ''
else:
w = c + w
return r + w
|
eb0a5a81e3a2f6f476c0faa670cc17fd0cc2218f | jdanray/leetcode | /gcdOfStrings.py | 1,332 | 3.84375 | 4 | # https://leetcode.com/problems/greatest-common-divisor-of-strings/
"""
Definitions:
T divides S iff S = T*
Preconditions:
str1 and str2 are strings
Postconditions:
X is the largest string that divides both str1 and str2
Thoughts:
X divides str1. So, str1 = X*.
X divides str2. So, str2 = X*.
If X divides str1,... |
f221f15ece742f9a3d60b7dcaf7826cddf5ec938 | jdanray/leetcode | /MyQueue.py | 481 | 3.984375 | 4 | # https://leetcode.com/problems/implement-queue-using-stacks/
class MyQueue(object):
def __init__(self):
self.A = []
self.B = []
def push(self, x):
self.A.append(x)
def pop(self):
if not self.B:
self.transfer()
return self.B.pop()
def peek(self):
if not self.B:
self.transfer() ... |
c50a52df43a58af53bac19262f19506b46557fca | jdanray/leetcode | /canPlaceFlowers.py | 384 | 3.9375 | 4 | # https://leetcode.com/problems/can-place-flowers/description/
class Solution:
def canPlaceFlowers(self, flowerbed, n):
i = 0
while n > 0 and i < len(flowerbed):
if flowerbed[i] == 1:
while i < len(flowerbed) and flowerbed[i] == 1:
i += 1
i += 1
elif i + 1 >= len(flowerbed) or flowerbed[i + 1] ... |
da498bffb88b6386ff9c2f62924ca5f57c1d649a | jdanray/leetcode | /canJump.py | 741 | 3.5 | 4 | # https://leetcode.com/problems/jump-game/
class Solution(object):
def canJump(self, nums):
if len(nums) == 1:
return True
maxJump = 0
for i, n in enumerate(nums):
if n == 0 and maxJump <= i and i < len(nums) - 1:
return False
else:
maxJump = max(maxJump, i + n)
return True
"""
After I so... |
5f092b282ecd8c0ccd7bb3c6cb50e62d45f0e404 | jdanray/leetcode | /nodesBetweenCriticalPoints.py | 660 | 3.5 | 4 | # https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/
class Solution(object):
def nodesBetweenCriticalPoints(self, head):
preVal = -1
firstCrit = -1
preCrit = -1
minDist = float('inf')
idx = 0
while head and head.next:
if preVal != -1 and (preVal < head... |
8ae31abd05f077b58e7a287ce4c81ddaf5063228 | jdanray/leetcode | /judgeSquareSum.py | 262 | 3.6875 | 4 | # https://leetcode.com/problems/sum-of-square-numbers/
class Solution:
def judgeSquareSum(self, c):
a = 0
b = int(c ** (1/2))
while a <= b:
d = a ** 2 + b ** 2
if d < c:
a += 1
elif d > c:
b -= 1
else:
return True
return False
|
01b57adc5dc36af2f8dd27cfdf88beffd9239f25 | jdanray/leetcode | /intersect.py | 602 | 3.5 | 4 | # https://leetcode.com/problems/intersection-of-two-arrays-ii/
class Solution(object):
def intersect(self, nums1, nums2):
N = len(nums1)
M = len(nums2)
nums1 = sorted(nums1)
nums2 = sorted(nums2)
i = 0
j = 0
res = []
while i < N and j < M:
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > n... |
293ada38e6c79fa8923dbf460d48b1a24b33f9d6 | jdanray/leetcode | /evenOddBit.py | 209 | 3.546875 | 4 | # https://leetcode.com/problems/number-of-even-and-odd-bits/
class Solution(object):
def evenOddBit(self, n):
res = [0, 0]
i = 0
while n > 0:
res[i] += (n & 1)
i = 1 - i
n >>= 1
return res
|
37a3ca504fb636c7a41c07405874141fd2249c58 | jdanray/leetcode | /ParkingSystem.py | 298 | 3.765625 | 4 | # https://leetcode.com/problems/design-parking-system/
class ParkingSystem(object):
def __init__(self, big, medium, small):
self.slots = [big, medium, small]
def addCar(self, carType):
if self.slots[carType - 1] == 0:
return False
else:
self.slots[carType - 1] -= 1
return True
|
e79e5182efa8f12557046769e9e24e69ad2097fc | jdanray/leetcode | /swapNodes.py | 976 | 3.671875 | 4 | # https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
class Solution(object):
def swapNodes(self, head, k):
n = 0
left = None
dummy = head
while dummy:
n += 1
if n == k:
left = dummy
dummy = dummy.next
i = 0
dummy = head
while dummy:
if i == n - k:
dummy.val, left.val = ... |
74ec1b572a4194196d07e34c3e8adc3cef7572e0 | jdanray/leetcode | /sumBase.py | 174 | 3.53125 | 4 | # https://leetcode.com/problems/sum-of-digits-in-base-k/
class Solution(object):
def sumBase(self, n, k):
res = 0
while n > 0:
res += n % k
n //= k
return res
|
b280a942fee3a44d22b764154420cfb8fd2a53fd | jdanray/leetcode | /numOfPairs.py | 291 | 3.65625 | 4 | # https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/
class Solution(object):
def numOfPairs(self, nums, target):
N = len(nums)
count = collections.Counter(nums[i] + nums[j] for i in range(N) for j in range(N) if i != j)
return count[target]
|
8d81f307df27d772183450c9054e62a21ab93c9e | jdanray/leetcode | /FrequencyTracker.py | 605 | 3.5625 | 4 | # https://leetcode.com/problems/frequency-tracker/
class FrequencyTracker(object):
def __init__(self):
self.count = collections.Counter()
self.freqs = collections.Counter()
def add(self, number):
if self.count[number] > 0:
self.freqs[self.count[number]] -= 1
self.count[number] += 1
self.freqs[self.co... |
6dfdbcbc394f5f315461ef87308ce29d95284ca3 | jdanray/leetcode | /numberOfSteps.py | 236 | 3.515625 | 4 | # https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
class Solution(object):
def numberOfSteps(self, num):
s = 0
while num > 0:
if num % 2 == 1:
num -= 1
else:
num //= 2
s += 1
return s
|
6ac97309f202d3a8e71df2269fc262aac082285e | jdanray/leetcode | /isBipartite.py | 358 | 3.625 | 4 | # https://leetcode.com/problems/is-graph-bipartite/
class Solution:
def isBipartite(self, graph):
colors = [0 for _ in range(len(graph))]
def dfs(u, col):
if colors[u] != 0:
return colors[u] == col
colors[u] = col
return all(dfs(v, -col) for v in graph[u])
return all(colors[u] != 0 or d... |
d7e3e714edf20c9362ab1169bfb9a125d5c12bc5 | jdanray/leetcode | /sortSentence.py | 211 | 3.625 | 4 | # https://leetcode.com/problems/sorting-the-sentence/
class Solution(object):
def sortSentence(self, s):
s = s.split()
s = sorted(s, key=lambda w: int(w[-1]))
s = " ".join(w[:-1] for w in s)
return s
|
013fafd59c7e013156037bba6ceb8bc8651fd554 | jdanray/leetcode | /buildTree2.py | 452 | 3.703125 | 4 | # https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
class Solution(object):
def buildTree(self, inorder, postorder):
if not inorder or not postorder:
return None
rootVal = postorder[-1]
r = 0
while inorder[r] != rootVal:
r += 1
root = TreeNode(rootVal)
ro... |
b6b517d6f1e50cfd8f287966776deb38ccd281d2 | jdanray/leetcode | /hIndex.py | 345 | 3.609375 | 4 | # https://leetcode.com/problems/h-index-ii/
class Solution(object):
def hIndex(self, citations):
N = len(citations)
lo = 0
hi = N - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if citations[mid] == N - mid:
return citations[mid]
elif citations[mid] > N - mid:
hi = mid - 1
else:
lo = mid... |
618d63103eac13c9cf576439d3c5ef9a9c41691c | jdanray/leetcode | /solveEquation.py | 715 | 3.828125 | 4 | # https://leetcode.com/problems/solve-the-equation/
class Solution(object):
def parse(self, symbols):
n = ""
nums = 0
xs = 0
for s in symbols:
if s == 'x':
if not n or n == '+':
n = 1
elif n == '-':
n = -1
xs += int(n)
n = ""
continue
if n and (s == '-' or s == '+'):
... |
0b5fc7fcd642fa776868de75ae7a4d8461c31429 | jdanray/leetcode | /isEvenOddTree.py | 589 | 3.75 | 4 | # https://leetcode.com/problems/even-odd-tree/
class Solution(object):
def isEvenOddTree(self, root):
prevnode = None
level = -1
queue = [[root, 0]]
while queue:
node, curlvl = queue.pop(0)
if not node:
continue
if curlvl % 2 == node.val % 2:
return False
if level == curlvl:
if lev... |
03b8df427940ba415d80f73991a201906e80bf97 | jdanray/leetcode | /smallerNumbersThanCurrent.py | 303 | 3.515625 | 4 | # https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
class Solution(object):
def smallerNumbersThanCurrent(self, nums):
res = []
for i, m in enumerate(nums):
res.append(0)
for j, n in enumerate(nums):
if i != j and n < m:
res[-1] += 1
return res
|
872601aa9b1be13f20b1cb28f35d8b3a1d91e326 | jdanray/leetcode | /canBeTypedWords.py | 290 | 3.5625 | 4 | # https://leetcode.com/problems/maximum-number-of-words-you-can-type/
class Solution(object):
def canBeTypedWords(self, text, brokenLetters):
broken = set(brokenLetters)
words = text.split()
res = 0
for w in words:
if all(c not in broken for c in w):
res += 1
return res
|
f6dd8604be2051b1756bdf56a1b6b6e9732aefee | jdanray/leetcode | /minFlipsMonoIncr.py | 874 | 3.6875 | 4 | # https://leetcode.com/problems/flip-string-to-monotone-increasing/
class Solution(object):
def minFlipsMonoIncr(self, S):
memo = {}
def solve(i, ones):
if i >= len(S):
return 0
if (i, ones) not in memo:
if S[i] == '0' and ones == True:
memo[i, ones] = 1 + solve(i + 1, ones)
elif S[i] == '... |
55a50580f889cdd98964061cfdd0699b6ac5f8a7 | jdanray/leetcode | /minOperations4.py | 3,786 | 3.59375 | 4 | # https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/
"""
Let s1 be sum(nums1), s2 be sum(nums2).
Some possibilities:
s1 == s2
Return 0
s1 > s2
Decrease s1 and/or increase s2
s1 < s2
Increase s1 and/or decrease s2
Idea. Swap s1,s2 and run s1>s2 procedure on this case
The problem is... |
3dc48ac344d99fff7d97ea3463e9ddd9748f6bd0 | jdanray/leetcode | /isCompleteTree.py | 1,222 | 3.609375 | 4 | # https://leetcode.com/problems/check-completeness-of-a-binary-tree/
class Solution(object):
def isCompleteTree(self, root):
if not root:
return True
curlevel = 0
full = 1
count = 0
queue = [[root, 0, 0]]
while queue:
node, label, lvl = queue.pop(0)
if lvl > curlevel:
if count != full:
... |
0c873beb0fdbce1342c4550173985dd86f91b1ed | jdanray/leetcode | /digitCount.py | 241 | 3.609375 | 4 | # https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/
class Solution(object):
def digitCount(self, num):
count = collections.Counter(num)
return all(int(d) == count[str(i)] for i, d in enumerate(num))
|
025c56c6273f477c1e72b87de50bd9b95e6c4430 | jdanray/leetcode | /flipgame.py | 4,019 | 3.984375 | 4 | # https://leetcode.com/problems/card-flipping-game/
"""
There are N cards. There are positive integers printed on the fronts and backs of the cards.
We flip a subset of cards.
for each i in flips:
backs[i], fronts[i] = fronts[i], backs[i]
We choose one card. Let c be the index of the chosen card.
Consider backs[c]... |
3f7d39024f47a36d75f209c2a38398424d6da48d | jdanray/leetcode | /greatestLetter.py | 339 | 3.5625 | 4 | # https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/
class Solution(object):
def greatestLetter(self, s):
lower = string.ascii_lowercase
upper = string.ascii_uppercase
seen = set(s)
for i in range(len(upper) - 1, -1, -1):
if lower[i] in seen and upper[i] in seen:
return upp... |
68e6f4a8f49bab145d2d01d2ce9752dab982a937 | jdanray/leetcode | /isSubPath.py | 1,814 | 3.53125 | 4 | # https://leetcode.com/problems/linked-list-in-binary-tree/
class Solution(object):
def isSubPath(self, head, root):
stack = [[root, [head]]]
while stack:
node, links = stack.pop()
if not node:
continue
newlinks = [head]
for l in links:
if node.val == l.val:
if not l.next:
return ... |
b083bf71073c4e96a48cc51b17fbd774aae692f7 | jdanray/leetcode | /isPalindrome2.py | 287 | 3.640625 | 4 | # https://leetcode.com/problems/palindrome-linked-list/
class Solution(object):
def isPalindrome(self, head):
nums = []
while head:
nums.append(head.val)
head = head.next
i = 0
j = len(nums) - 1
while i < j and nums[i] == nums[j]:
i += 1
j -= 1
return i >= j
|
27afe4bc55fc8828d81a7a2cc48521cc999744d9 | jdanray/leetcode | /isFascinating.py | 468 | 3.8125 | 4 | # https://leetcode.com/problems/check-if-the-number-is-fascinating/
class Solution(object):
def isFascinating(self, n):
n2 = n * 2
n3 = n * 3
seen = set()
while n or n2 or n3:
d1 = n % 10
d2 = n2 % 10
d3 = n3 % 10
if d1 in seen or d2 in seen or d3 in seen:
return False
elif d1 == 0 or d2... |
0d5dcfae0f9755e7f235494a735404cbc7fe7c4e | jdanray/leetcode | /findLongestWord.py | 736 | 3.640625 | 4 | # https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/
class Solution:
def findLongestWord(self, s, d):
d = sorted(d)
longest = ''
for w in d:
if len(w) < len(longest) or len(w) > len(s):
continue
i = 0
for c in s:
if i < len(w) and w[i] == c:
i += 1
if i == len(... |
7f13717fa8a7d98f3832f4978841e6cfbac37a68 | jdanray/leetcode | /numSmallerByFrequency.py | 2,500 | 3.515625 | 4 | # https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/
class Solution(object):
def numSmallerByFrequency(self, queries, words):
def freq(s):
s = sorted(s)
f = 0
i = 0
while i < len(s) and s[i] == s[0]:
f += 1
i += 1
return f
fqueries = [freq(q) for q in que... |
3c5f23193a4042c890ca6d4b080c192fc367e788 | jdanray/leetcode | /sortList.py | 707 | 3.765625 | 4 | # https://leetcode.com/problems/sort-list/
class Solution(object):
def merge(self, left, right):
fakeHead = ListNode(0)
p = fakeHead
while left and right:
if left.val < right.val:
p.next = left
left = left.next
else:
p.next = right
right = right.next
p = p.next
if left:
p.next = ... |
69dce2de00b2de79a3c7b476fa2efe8e528d5a9b | jdanray/leetcode | /isPowerOfThree.py | 193 | 3.984375 | 4 | # https://leetcode.com/problems/power-of-three/description/
class Solution:
def isPowerOfThree(self, num):
if num <= 0:
return False
f = 1
while f < num:
f *= 3
return f == num
|
1be0c5bafb58a72ab8c46ce58997bbebe34d651f | jdanray/leetcode | /floodFill.py | 483 | 3.59375 | 4 | # https://leetcode.com/problems/flood-fill/
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
M = len(image)
N = len(image[0])
oldColor = image[sr][sc]
seen = set()
def fill(i, j):
if i >= 0 and i < M and j >= 0 and j < N and (i, j) not in seen and image[i][j] == oldColor:
image... |
79ac07be07c385c364eaf58558c84f6833d909c3 | jdanray/leetcode | /findDifferentBinaryString.py | 344 | 3.5 | 4 | # https://leetcode.com/problems/find-unique-binary-string/
class Solution(object):
def findDifferentBinaryString(self, nums):
N = len(nums)
nums = set(nums)
def genString(s):
if len(s) >= N:
if s not in nums:
return s
else:
return False
return genString(s + '1') or genString(s + '0')
... |
46c29d4e1df4c3398fc445c4a96835fd7dfe548a | jdanray/leetcode | /totalMoney.py | 269 | 3.5 | 4 | # https://leetcode.com/problems/calculate-money-in-leetcode-bank/
class Solution(object):
def totalMoney(self, n):
W = 7
res = 0
pay = 0
start = 0
for d in range(n):
if d % W == 0:
start += 1
pay = start
res += pay
pay += 1
return res
|
6db5e41801decf3b5edf7708c25579b3fcb75141 | jdanray/leetcode | /averageWaitingTime.py | 285 | 3.625 | 4 | # https://leetcode.com/problems/average-waiting-time/
class Solution(object):
def averageWaitingTime(self, customers):
start = 1
wait = 0.0
for (a, p) in customers:
start = max(start, a)
end = start + p
wait += (end - a)
start = end
return wait / len(customers)
|
5eaaa4ff552f88e0c14c490f80c0ec9d26917590 | jdanray/leetcode | /longestCommonSubsequence.py | 469 | 3.5 | 4 | # https://leetcode.com/problems/longest-common-subsequence/
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
M = len(text1)
N = len(text2)
longest = [[0 for _ in range(N + 1)] for _ in range(M + 1)]
for i in range(1, M + 1):
for j in range(1, N + 1):
if text1[i - 1] == text2[j ... |
334cb0074443dbb14824dd70cc700947e3f36355 | jdanray/leetcode | /longestSubarray.py | 3,784 | 3.703125 | 4 | # https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/
"""
The basic idea for the following program is that deleting an element can increase the length of the longest subarray of 1s only if
(1) the element is a 0, and
(2) there are two subarrays of 1s to the left and right of the 0.
... |
e7eb8a40e8f8e8c16ca5d2a36a1e6c2728a5a9da | jdanray/leetcode | /eraseOverlapIntervals.py | 505 | 3.75 | 4 | # https://leetcode.com/problems/non-overlapping-intervals/
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def eraseOverlapIntervals(self, intervals):
if not intervals:
return 0
n = 1
o = 0
... |
03654b3189e787df6b87e3b3e21ad4a6b0f682a8 | jdanray/leetcode | /backspaceCompare.py | 281 | 3.75 | 4 | # https://leetcode.com/problems/backspace-string-compare/
class Solution:
def backspaceCompare(self, S, T):
return self.backspace(S) == self.backspace(T)
def backspace(self, chars):
b = []
for c in chars:
if c != '#':
b.append(c)
elif b:
b.pop()
return b
|
1ad3d1f56f36324836e91b927bf9368d2bb8ecc5 | jdanray/leetcode | /findOcurrences.py | 252 | 3.609375 | 4 | # https://leetcode.com/problems/occurrences-after-bigram/
class Solution(object):
def findOcurrences(self, text, first, second):
text = text.split()
return [text[i + 2] for i in range(len(text) - 2) if text[i] == first and text[i + 1] == second]
|
464d093325627385398a4a195999731efa57b740 | jdanray/leetcode | /maskPII.py | 543 | 3.5625 | 4 | # https://leetcode.com/problems/masking-personal-information/
class Solution(object):
def maskPII(self, s):
def maskEmail(s):
s = s.lower()
name, domain = s.split("@")
return name[0] + "*****" + name[-1] + "@" + domain
def maskPhone(s):
sep = {"+", "-", "(", ")", " "}
num = "".join(c for c in s i... |
90006baf9f3b6608c6481aa2dca22a43b1de6722 | jdanray/leetcode | /finalString.py | 216 | 3.59375 | 4 | # https://leetcode.com/problems/faulty-keyboard/
class Solution(object):
def finalString(self, s):
FAULTY = 'i'
res = ''
for c in s:
if c == FAULTY:
res = res[::-1]
else:
res += c
return res
|
46378f6be5e61ef82d4d6135dbc16bd12e15a274 | selincifci/bby162 | /uygulama05.py | 1,230 | 3.671875 | 4 | __author__="selin ÇİFCİ
import random
ülkeler=random.choice(["türkiye","rusya","amerika","almanya","fransa","çin","japonya"])
harfhavuzu=[]
deneme=5
karaktercizgisi='_'
yazi=list(karaktercizgisi)*len(ülkeler)
dongu=1
while dongu:
print(' '.join(yazi),end='\n\n')
harf=input("harf giriniz:")
try:
int... |
a64e7f528a5479d2625d9f181d715bdc1e0f6ddd | burnin7/OtimizacaoGrafos20191 | /trab2.py | 5,894 | 3.6875 | 4 | print ("Hello Word")
import json
g = json.load(open('data5.json'))
def rotula(a):
if not(visitado[a]):
visitado[a] = True
def geraListaAdjacencia(grafo):
vertices = grafo["vertices"]
arestas = grafo["arestas"]
lista = []
for i in vertices:
aux = []... |
5264f888fa466529479f66e7bc2420689ae02394 | ianarmstrong66/python | /second.py | 304 | 3.53125 | 4 | physics=80
chemistry=99
math=87
total=physics+chemistry+math
per=total*100/150
print("\n\nPhysics:\t{0} \nChemistry:\t{1} \nMath:\t\t{2}".format(physics,chemistry,math))
print("SUMMARY".center(40,'-'))
print("Result of your marks is {0} \nPercentage: \t{1}".format(total,per))
print("END".center(40,'-')) |
bd184261cf96d05223417da79daf33431e6f950f | ianarmstrong66/python | /codeword.py | 390 | 3.6875 | 4 | msg=input("Enter your string here (include all case, numbers and symbols:\t")
word=""
for a in range(0,len(msg)):
if ord(msg[a]) >=65 and ord(msg[a]) <=90:
word+=chr(ord(msg[a])+32)
elif ord(msg[a]) >=97 and ord(msg[a]) <=122:
word+=chr(ord(msg[a])-32)
elif ord(msg[a]) >=48 and ord(msg[a]) <=57:
b=int(msg[a])*... |
c85f1e9d5aef955316b9b0e1d562d90fe930871f | yshaqalle/Tarteel-ML | /utils/file_helper.py | 1,392 | 3.90625 | 4 | """Utility funtions for reading from and writing to JSON, CSV, and other file types."""
import csv
import json
import os
from typing import Any
from typing import List
from typing import Union
def open_csv(csv_file: str, dict_reader: bool = False, delimiter: str = ',') -> List:
"""Delimiter can also be a pipe (|... |
b0ba5d0aabe5200a5dbd544708be7772d1e5844d | dearamerican/python-practice | /ex40.py | 680 | 3.65625 | 4 | class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_par... |
8007a3ce8c7656ef2b23774e60ad64f1f2297276 | dgorshkov/python-learning | /hangman.py | 3,231 | 3.765625 | 4 | import random
import re
def chooseword(wordlist, finder):
return finder(wordlist)
def getWordStateForPrint(wordList):
blankOrHash = [letter if letter in guessLetters else '_' for letter in wordList]
return ' '.join(blankOrHash)
fruitwords = ['apple', 'banana', 'pineapple']
word = chooseword(fruitwo... |
0220158c88da599affe14f38646195a50b21c02a | aburasali/PyhtonClass | /Lists/Exercise-2.py | 246 | 3.875 | 4 | letters = ['a', 'b', 'c', 'd', 'e', 'f']
print(letters.index('a'))
print(max(letters))
print(min(letters))
print(letters.count('a'))
print(len(letters))
letters.append('a')
print(len(letters))
print(letters.count('a'))
print(letters.index('a'))
|
df0c6def5c7957eab090afe46bcd92dae1b68920 | giadainnocenti/Python-challenge | /PyPoll/main.py | 1,998 | 3.9375 | 4 | import os
import csv
#defining a function to print the delimiter string
def delimiter(filename, string):
print(string)
filename.write(string)
filename.write('\n')
return()
def divider():
return ("-------------------------")
csvpath = os.path.join('.','Resources','election_data.csv')
with open(csv... |
f9af2be00ded5840b7dafc71f80ee0f51dd374ad | nirupaangelin/codepython | /sum of odd numbers till n.py | 110 | 3.671875 | 4 | n=int(input())
sum=0
for counter in range(1,n+1):
if(counter%2!=0):
sum=sum+counter
print(sum) |
1f500cc86261236add146bc74793ee2405ea90cc | kev246/python_correyS | /instanceVeriables.py | 889 | 4.09375 | 4 | class Employee:
def __init__(self, firstname, lastname, pay):
self.fname = firstname
self.lname = lastname
self.pay = pay
self.mail = self.fname + "." + self.lname + "@gmail.com"
def fullname(self):
return "{} {}".format(self.fname, self.lname)
emp1 = Employee("karthik... |
37c0516c626d98252f3555d93533ed657cce3a0c | adamczheng/tractor-client | /single_player/player.py | 3,896 | 4.09375 | 4 | """
Keep track of:
player's hand
"""
class Player(object):
"""
name = Player's name (string)
trump_rank = trump rank (string)
trump_suit = trump suit (string)
is_zhuang_jia = (True if player is zhuang jia, False otherwise) (boolean)
is_attacker = (True if player is an attacker, False otherwise... |
efbd2b205473a1ce65fb1635dd1496893bc96bcc | adamczheng/tractor-client | /single_player/round_functions/outdated_functions.py | 10,060 | 3.5625 | 4 | """
def liang_query(self, current_drawer):
# format is "suit cnt" or "SJo 2" or "BJo 2"
print("Liang?")
response = input().split()
# "n" "no" or nothing means no liang
if len(response) == 0 or response[0] == "n" or response[0] == "no":
print("No liang, continuing")
return
# check... |
da7c35d587d61043272934e81fefb98f354c7d45 | Ramyashree13/python1BM18CS416 | /program6.py | 422 | 3.890625 | 4 | class py_solution:
def is_valid(self,str1):
stack,pchar = [],{"(":")","{":"}","[":"]"}
for parenthese in str1:
if parenthese in pchar:
stack.append(parenthese)
elif len(stack)==0 or pchar[stack.pop()] !=parenthese:
return False
... |
a7e3636657fe09d067c52b243126688fbc5e2d11 | MSokol00/udemy | /challenges/PART2.py | 1,059 | 3.796875 | 4 | def titleize(item):
words = item.split(' ')
titleized_words = [w[0].upper()+w[1:] for w in words]
return ' '.join(titleized_words).strip()
def find_factors(num):
result = []
for i in range(1, num+1):
if num % i == 0:
result.append(i)
return result
def find_factors_comp(nu... |
6d0f42d62e9561beda968d59d840080411977dbb | MSokol00/udemy | /ascii_exercise/ascii.py | 784 | 3.625 | 4 | from termcolor import cprint
from pyfiglet import Figlet
def ascii_art():
colors = ['grey', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white']
text = input('What message do You want to print?')
colorsText = 'In what color? (select number):'+'\n'.join(
f'{n}-{value}'for n, ... |
3fdb8204bdd25260f9d501494729649799ad8d1a | arvindaggmca/pyspark_docker | /code/spark_json_file.py | 921 | 3.5 | 4 | """
This is a copy from official example src/examples/python
How to use it:
spark-submit /code/spark_json_file.py /data/people.json
"""
import sys
from pyspark.sql import SparkSession
from pyspark.sql.types import *
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: spark_json_file.py <file>... |
f69df9cf0ead6e28ca9d56cb181d95f893416f80 | grudus/AdventOfCode2020 | /src/main/python/day03.py | 1,002 | 3.53125 | 4 |
from operator import mul
from functools import reduce
def first_star(forest):
return traverse_forest(forest, (3, 1))
def second_star(forest):
slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
trees = [traverse_forest(forest, slope) for slope in slopes]
return reduce(mul, trees)
def traverse_forest... |
2dc556143d1934db36ac5ffe29124456e6afd4d3 | nitintr/CodeChef-Programming | /1.Sum-of-Digits-using-char.py | 172 | 3.59375 | 4 | def func():
t=int(input(""))
while t > 0:
n=input("")
ans=0
for x in n: ans+=( ord(x) - ord('0') );
print(ans)
t=t-1
func()
|
a1de6e3402e992ba1cb9503dd3308d1c6fa31c38 | yourback/OfflineDataConversionAndDrawingSoftware | /clac_module/rangecalc.py | 1,171 | 4.125 | 4 | # 区间数据计算
# 获取最小值
def max_calc(list_data):
i = list_data[0]
for d in list_data:
if i < d:
i = d
return i
def min_calc(list_data):
i = list_data[0]
for d in list_data:
if i > d:
i = d
return i
def average_calc(list_data):
i = 0
for d in list_dat... |
d92ab7b49f14a163bd03fc9e25208a3699d5a951 | AbdullahMohammad/Numberjack | /examples/NumberPartitioning.py | 1,631 | 3.84375 | 4 | # Number Partitioning
#
# In this problem, the numbers 1 to N must be arranged in two
# different groups A and B in such a way that:
# 1. A and B have the same cardinality.
# 2. The sum of numbers in A equals the sum of numbers in B.
# 3. The sum of the squares of numbers in A equals the sum of
# the squares of ... |
bb3cfb1c63d7a005162f83f92529d7671e8dc422 | apavluck/GWU | /scratch_pad.py | 755 | 3.671875 | 4 | '''
#fibonacci
def fib (x):
a = 0
b = 1
f = [1,1]
while a < x:
q = f[a] + f[b]
f.append(q)
a += 1
b += 1
return f
k = fib(10)
print k
z = 55
for items in k:
if items == z:
print items, z
j = True
break
else:
print items, z
... |
392c4bcffb54aaff26ea77f6be1622e9980ade1c | wangwalton/OrbisChallenge2017 | /LUMINIS/Bots/PythonAI/PythonClientAPI/DataStructures/Collections.py | 814 | 3.796875 | 4 | import heapq
class PriorityQueue:
def __init__(self):
self.count = 0
self.items = []
def is_empty(self):
return len(self.items) == 0
def poll(self):
return heapq.heappop(self.items)[2]
def add(self, item, priority):
heapq.heappush(self.items, (priority, self.c... |
03b0bfd08614659d0d8af29e27fe7fc0fca9b1de | chenfeizhang/Brette | /Code_git/scripts/addparam.py | 1,120 | 3.71875 | 4 | '''
Function addparam searches for the line that contains the expected parameter data in IparamTable.txt, then adds these data to dictionary param.
'''
def addparam(param, IparamTableFile):
fItable = open(IparamTableFile,'r')
data_exist=0 # number of data lines that fits searching criterion
fItable.readline()... |
1d2483a04940fb52aaaca185f5ac60158570c315 | maia1220/3-Python-FinancialAnalysis | /PyPoll/main.py | 3,005 | 3.5 | 4 | ## PyPoll
import os
import csv
# Absolute Path
# csvpath = "/Users/aq/Documents/Classwork/vu-nsh-data-pt-02-2020-u-c/03-Python/Homework/Instructions/PyPoll/Resources/election_data.csv"
# Relative Path
csvpath = os.path.join(os.path.expanduser('~'),"Documents/Classwork/vu-nsh-data-pt-02-2020-u-c", "03-Python/Homewor... |
c07f67014e7cd7ba0b2f8c1ea55b6f2bb226dacf | DarrenZheng/python3_base | /firstday/continue.py | 170 | 4.0625 | 4 | while True:
guess = input("input something")
if guess == 'quit':
break
if len(guess) < 3:
continue
print("bigger than 2")
print("done!") |
b852c344903db55528a0b4816aa79e49d5a7d3ad | DarrenZheng/python3_base | /fifthday/faceObject2.py | 441 | 3.953125 | 4 | class Person:
population = 0
def __init__(self, name):
Person.population += 1
self.name = name
def __del__(self):
Person.population -= 1
print("byebye,", self.name)
def say_hi(self):
print("hi, i am", self.name)
def howmany():
print('we have person... |
f3fd302edf9dfb27cd555101827dddc7c177a247 | lakshay123-ctrl/100-class | /100.py | 496 | 3.609375 | 4 | class Car(object):
def __init__ (self,model,color,company,speedlimit):
self.color = color
self.model = model
self.company = company
self.speedlimit = speedlimit
def start(self):
print("started")
def stop(self):
print("stopped")
def accelerat... |
c7274f9fc509978e76b341e0c07a48184ad551f4 | rohw/CS362_HW4 | /volume.py | 146 | 3.515625 | 4 | def vol(x):
if (type(x) is str):
return "Numbers only"
if (x <= 0):
return "Positive numbers only"
return x * x * x
|
bca620be2ddea7310a31a7f6a6515551e287ff2c | s1k1rao/project1 | /Game code.py | 2,457 | 3.953125 | 4 |
# coding: utf-8
# #date:13TH OCT 2018
# #DISCRIPTION:SPACE ADVENTURE GAME
# In[2]:
import random
import time
check2=True
while check2==True:
name=input("enter your name")
print("hey",name,"welcome to the inter galaxy headquarters")
time.sleep(2)
print("we are facing a serious trouble due to al... |
9b238199b557317bd5a61040dc814babd32d193b | dharam1/Python | /Practice_Minions.py | 1,156 | 3.90625 | 4 | /* Kevin and Stuart want to play the 'The Minion Game'.
Game Rules
Both players are given the same string, .
Both players have to make substrings using the letters of the string .
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have mad... |
f04a47dd64a1cae114c053e53a1ce85533fec5e9 | mrggaebsong/Python_DataStructure | /PythonSort.py | 2,576 | 4.125 | 4 | def bubble_sort(list):
for last in range(len(list)-1,-1,-1):
swap = False
for i in last:
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
swap = True
if not swap:
break
return list
l = [5,6,2,3,0,1,4]
print("Bubble Sort")
print(l)
bub... |
8412558cbb33b6952b75d53522730e0b27ff8b61 | mrggaebsong/Python_DataStructure | /BST_2.py | 4,298 | 3.8125 | 4 | class node:
def __init__(self,data,left=None,right=None):
self.data = data
self.left = left
self.right = right
def inOrder(root):
if root:
inOrder(root.left)
print(root.data, end=' ')
inOrder(root.right)
def preOrder(root):
if root:
print(root.data, ... |
bd1aea994865365f13c7e0cc6d815e63dd33d6a5 | Yash25gupta/Python | /Tutorial_Codes/18 Chapter - Working with files.py | 4,382 | 4.15625 | 4 | # Tutorial 213 - Read Text Files
# read file
# open function # open file
# read method # read file
# seek method # to change position of curser
# tell method # tell position of curser
# readline method # read 1 line
# close method # close file
... |
ec9d6f83ed95af87724cc60be71c9c14d3b1ae3a | Yash25gupta/Python | /Tutorial_Codes/12 Chapter - Lambda Expressions.py | 765 | 4.21875 | 4 | # Tutorial 150 - Lambda Expression
# anonymous function
def add(a,b):
return a+b
add2 = lambda a,b : a+b
print(add2(2,3))
multiply = lambda a,b : a*b
print(multiply(2,3))
print(add)
print(add2)
print(multiply)
# Tutorial 151 - Lambda Expression Practice
def is_even(a):
return a % 2 ==0
p... |
c605f75810eda5a8da7cc489a4b31785324efc2c | Yash25gupta/Python | /Tutorial_Codes/16 Chapter - OOP Basics.py | 15,916 | 4.1875 | 4 | # Tutorial 183 - Object Oriented Programming Intro
# common topic in all popular Programming language(ptyhon, c++, java)
# with common idea but with different syntax
# OOP is just a style/way to write a code
# Very helpful in creating real life program
# class, object(instance), method
# list class # i... |
d6c15e7a93c03999e965f7b70e3481c621c182e0 | Yash25gupta/Python | /Tutorial_Codes/17 Chapter - OOP Advanced.py | 6,669 | 4 | 4 | # Self
class Enemy(object):
# instances = [] # e0, e1, ....
def __init__(self, x):
# self.__class__.instances.append(self)
self.x = x
def show(self):
print(f'hi {self.x}')
# Create multiple instances of a class
n = 5 # Numbers of enemy
enemys = {f'e{i}': Enemy(50 +... |
d6767bdd4b575a80c547ce61aec3c7e4477809fa | Yash25gupta/Python | /Tutorial_Codes/7 Chapter - Dictionaries and data modeling.py | 5,608 | 4.40625 | 4 | # Tutorial 114 - Intro to dictionaries
# lists are not enough to represent real data
# user = ['Yash', 20, ['Avengers', 'MIB'], ['SAO', 'death note']]
# This list contain data but not in good way. So we use dictionaries
# dictionaries : unordered collection of data in key : value pair.
# We can store anything in... |
0fb81f42d4db6e2b7d0c3f1930f2eaef1d6a5488 | Yash25gupta/Python | /Tutorial_Codes/10 Chapter - Dictionary comprehension and sets comprehension.py | 668 | 4.03125 | 4 | # Tutorial 137 - Dictionary Comprehension
# square = {1:1, 2:4, ...}
# square = {i:i**2 for i in range(1,11)}
square = {'square of {} is'.format(i): i**2 for i in range(1, 11)}
for k, v in square.items():
print('{} : {}'.format(k, v))
txt = 'Yashgutaup'
word_count = {char: txt.count(char) for char in txt}
... |
c97314c42503fc14a3f2434a1e6baa94271b1596 | 01chernov/OOP-YouTube-1 | /Lesson 1.py | 401 | 4.03125 | 4 | print('Hello, Dasha!')
num1 = 20
num2 = num1
corteg1 = 1, 2, 3, 4
corteg2 = (10, 20, 30, 40)
num3 = int(input('Введите третье число: '))
word = 'слово'
print (num1)
print (num3)
print (num2 + num3)
print ('\nКортеж первый:', corteg1)
print('\nКортеж второй:', corteg2)
print('Второе число из второго кортежа:', corte... |
f09002cce1a32a8d7cc25abc367bad7bbba0baae | lamendola27/Final_Project | /_final_exercises_.py | 2,711 | 3.5 | 4 | # Final Project Exercises
## Lindsay Amendola
## Carli Peters
## 22 December 2020
### Exercise 1
import numpy as np
import matplotlib as plt
def tentmap(y, n):
# need to create lists for input and output
inp = np.array([])
out = np.array([])
for i in range(1, n):
inp = np.append(inp, y)
if y < 0.5:
y = 2*y... |
a644ddc635946508ba84ef487b1668a15d509a4d | bharathikambli/pythonprograms | /sort_4.py | 232 | 3.8125 | 4 | #Task-4
===============================================
#Using inbuilt functions
print "==List sorting=="
lists = [123, 'xyz', 'zara', 'abc', 'def']
print "Given list is :",lists
lists.sort()
print "Sorted list is :",lists
|
61d2270cb1d8ec5d886519f55b944b09016dc901 | dowookims/ProblemSolving | /swea/queue/bit_operator.py | 175 | 3.53125 | 4 | arr = [3,6,7,1,5,4]
n = len(arr)
a = 0
for i in range(1<<n):
for j in range(n+1):
if i & (1<<j):
print(arr[j], end=", ")
print()
a+=1
print(a) |
eb6861d4124f79e4b69b73f8375d52b74f69f064 | dowookims/ProblemSolving | /swea/str/4865_letter_length.py | 349 | 3.671875 | 4 | import sys
sys.stdin = open("sample_input3.txt","r")
for TC in range(1, int(input())+1):
case = set(input())
exam = input()
count = {}
for item in case:
count.update({item:0})
for letter in exam:
if letter in count:
count.update({letter:count.get(letter)+1})
print(f"... |
79b6577dfa797276c5b3a2c55620ce5286ff9944 | dowookims/ProblemSolving | /swea/stack2/stack2_2.py | 1,687 | 3.546875 | 4 | class Stack:
def __init__(self):
self.stack = [None] * 250
self.top = -1
def pop(self):
if self.top == -1:
return None
result = self.stack[self.top]
self.stack[self.top] = 0
self.top -= 1
return result
def push(self, item):
self.t... |
e22d09d730393c6a98813fef3ff518d3c74dd95d | dowookims/ProblemSolving | /boj/5688.py | 132 | 3.515625 | 4 | t = int(input())
for i in range(1,t+1):
n = int(input())
print(f"#{i} {int(n**(1/3) if int(n**(1/3)) == n**(1/3) else -1)}") |
2be64ce356d36c3ca22944564ae5f947e010dd49 | garethgeorge/cs130g-music | /py-fft-derivation-v2/main.py | 745 | 3.53125 | 4 | import cmath
import numpy as np
# https://jeremykun.com/2012/07/18/the-fast-fourier-transform/
# note that omega is that expression we factored out in our derivation before!!!
def omega(p, q):
return cmath.exp((2.0 * cmath.pi * 1j * q) / p)
def fft(signal):
n = len(signal)
if n == 1:
return signal # nothing to ... |
5aca136caa0ec6c1a87de21f2a56ebe6d296ba83 | bazitur/my-euler-solutions | /problem_3.py | 311 | 4 | 4 | #/usr/bin/env python3
def factorize(n):
for i in range(2, int(n ** 0.5+1)):
if n == 1:
break
while n % i == 0:
yield i
n /= i
else:
if n != 1: yield int(n)
if __name__ == "__main__":
print(max(factorize(int(input("Enter a number: ")))))
|
1a540a03c7f5bd5b39255ed8fddae6346ac6ba60 | GintasBu/python-code | /MapReduce_matrix_multiplication/multiply.py | 1,943 | 3.78125 | 4 | import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: document identifier
# value: document contents
# enter sizes:
l1=5 # initial number ... |
5bb1fc6afd09d5ffb3e5f722be883e23ab5db60d | GintasBu/python-code | /openbookproject_thinkcs_python/after.py | 1,100 | 3.96875 | 4 | class Time:
def __init__(self, hours=0, minutes=0, seconds=0):
self.hours=hours
self.minutes=minutes
self.seconds=seconds
def time_seconds(time):
seconds=time.seconds
secm=time.minutes*60
sech=time.hours*3600
return seconds+secm+sech
def after(time1, time2):
t1=time... |
a2aaf99fcc1b5ce257d8506092ed273c1fd432a3 | amitsindoliya/datastructureandalgo | /selection_sort.py | 577 | 4.3125 | 4 | ## selection Sort ##
## In selection sort we find the minimum element or maximum element
# of the list and place it at the start
# continue this operation until we have an sorted array
# complexity O(N^2)/2
# unstable
def selection_sort(iterable):
for i in range(len(iterable)-1):
for j in range(i+1,len(... |
8adc142658e49c8f7eb7be4b92856d1bdf4607d5 | yaoguoguo/MathematicalEngineering | /numberThy/Q1/numthy Q1i.py | 1,374 | 3.671875 | 4 | import numpy as np
import math
import random
# This program generates 100 random numbers between 1 and p and compute the Legendre symbol mod p for each of them
# a is a list of 100 randam numbers generated between 1 and 30275233
a = random.sample(range(1, 30275233), 100)
p = 30275233
b = bin((p - 1) / 2)[2:]
# prin... |
fa2fed5a171acbcfbdfb6ffcbfde3203e0250dcc | carlosfieldsierra/Dynamic-programming-Problems | /Memoization/LongestIncreasingSubsequence.py | 316 | 3.734375 | 4 | # Find the longest increasing subsequence
# ex) input: [3,1,8,2,5]
# ans: 3 because 1,2,5
def lis(A):
L = [1]*len(A)
for i in range(1,len(L)):
subproblems = [L[k] for k in range(i) if A[k]<A[i]]
L[i] = 1 + max(subproblems,default=0)
return max(L,default=0)
print(lis([3,1,8,2,5])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.