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
256c0b12eb2fbd1bade3f09d601b26372863b1c1
cathuan/LeetCode-Questions
/python/q30.py
1,686
3.6875
4
class Solution(object): def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ # trivial case if len(s) == 0 or len(words) == 0: return [] # put words in a set to speed up the lookup process...
7e4abd715327986565da55e0f1018a1b9595e331
cathuan/LeetCode-Questions
/python/q895.py
901
3.5
4
class FreqStack(object): def __init__(self): self.stacks = {} self.freqs = {} self.maxFreq = 0 def push(self, x): """ :type x: int :rtype: void """ if x not in self.freqs: self.freqs[x] = [] freq = len(self.freqs[x])+1 ...
8ad911eb93d0b6371476c751b99c6b530c77a382
cathuan/LeetCode-Questions
/python/q224.py
1,080
3.546875
4
import sys class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ seq = s tokens = [] numSeq = "" for s in seq: if s == " ": continue if s.isdigit(): numSeq += s else: if numSeq != "": tokens.append(int(numSeq)) tokens.append(s) numSeq = ""...
ad35c9a49bc90390113b1a75b6262603def2aeba
cathuan/LeetCode-Questions
/python/q1.py
608
3.65625
4
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ opponents = {} for index, value in enumerate(nums): opponent = target - value if opponent in opponents: ...
a5710b979f3bbfc8e96621e98b2fb8a04866c6bf
cathuan/LeetCode-Questions
/python/q376.py
805
3.53125
4
# 25.93% class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 if len(nums) == 1: return 1 length = 0 sign = None for i in range(1, len(nums)):...
87676e1178049b7a90ec9a854f31b70878b5581d
cathuan/LeetCode-Questions
/python/q146.py
2,672
3.578125
4
class Node(object): def __init__(self, key=None, val=None): self.key = key self.val = val self.prev = None self.next = None class DoublyLinkedList(object): def __init__(self): self.sentinal = Node() self.sentinal.prev = self.sentinal self.sentinal.next =...
83d10891dd52756e3727459b2fd40f36243cb64a
cathuan/LeetCode-Questions
/python/q460.py
3,724
3.59375
4
class Node(object): def __init__(self, key=None, val=None): self.key = key self.val = val self.frequency = 0 self.prev = None self.next = None class DoublyLinkedList(object): def __init__(self): self.sentinal = Node() self.sentinal.prev = self.sentinal ...
3ec22b69c576af4e5141af8cf501e169db9e0f5e
cathuan/LeetCode-Questions
/python/q96.py
624
3.546875
4
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ results = {} for k in range(n+1): if k == 0: result = 1 elif k == 1: result = 1 else: result = 0 ...
8623d9f8378d0f0c0315104d19052064affe58c4
cathuan/LeetCode-Questions
/python/q719.py
1,754
3.78125
4
from collections import deque class SlidingWindow(object): def __init__(self, maxDif): self.data = deque() self.maxDif = maxDif def push(self, value): self.data.append(value) while value - self.data[0] > self.maxDif: self.data.popleft() def getLength(self): ...
6d822ddcc7b4fe31c7cee53debe434ee73dfbbec
cathuan/LeetCode-Questions
/python/q127_unsolved.py
1,101
3.515625
4
class Solution(object): diffs = {} def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ if self.diffCharCount(beginWord, endWord) == 1: return 1 ...
810f38742f094f992871d52538f3e8cf71a9760a
cathuan/LeetCode-Questions
/python/q111.py
751
3.796875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int ...
2b40ac00e24536f975cdf58c9ff3b469a7e0d6eb
iKeepLearn/pyscripts
/rename.py
521
3.84375
4
#!/usr/bin/env python import os,sys def rename(path): for root,dirs,files in os.walk(path): for file in files: if file.endswith('.jpg') or file.endswith('.gif'): newname = file[0:-4] + '101' + file[-4:] oldname = os.path.join(root,file) newname =...
14bd88f8f8fe5c83cf906c4a5583a4f2e0c35e5a
BingxianChen/cell-detection
/cell-detection/slide.py
1,316
3.625
4
from image import Image import numpy as np class Slide(Image): ''' An image of a slide from a microscope. This slide is expected to contain at least some cells and not simply be noise or blank. ''' @classmethod def from_cells(cls, cells, width, height): ''' Creates and returns ...
55ce8ca0f83f1457cf910b4469ee383e6f0a34eb
EthanBechtol/WordSearchOCRSolver
/file_processing.py
1,443
3.921875
4
import os import shutil first_dir_pass = True safe_to_delete = False def prepare_dir(word): """Create a directory if it doesn't already exist to store resources generated in this program""" global first_dir_pass global safe_to_delete try: os.mkdir(os.path.join(os.getcwd(), "words")) exce...
aa5358aa0831a32ce8b9580d7f4b9d4b0872ec5e
Uyadav207/Attendance_AI
/test.py
184
3.78125
4
def listToString(s): str1 = "" for ele in s: str1 += ele return str1 s = ['wow', 'cool', 'damm'] print(listToString(s))
56dac0836a399dfb331f7dad49cde574aea01446
Clobbster/hackerrank
/Python/If_Else/test_sample_code.py
529
4.3125
4
# For a input variable, write if/then ladder for the following: # If is odd, print Weird # If is even and in the inclusive range of to , print Not Weird # If is even and in the inclusive range of to , print Weird # If is even and greater than , print Not Weird N = int(input("Please enter a number: ")) if N % 2 ...
b210549d4b32f01909c03f2a85f0127a3c4c3c1f
Clobbster/hackerrank
/Python/Write_A_Function/test_sample_code.py
406
4.25
4
# Write a function that determines if a given input year is a leap year. def is_leap(year): leap = "" # Write your logic here if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap = True else: leap = False else: le...
9f3743b40f5c259e3c7edd1c64e4e4db2b47e639
bwzhou/misc
/quora/nearby-heap.py
5,909
3.53125
4
#!/usr/bin/env python import sys, math, random, operator def topic_distance(loc1, loc2): return math.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2) class heap: def __init__(self, limit): self.data = [] self.limit = limit def size(self): return len(self.data) def insert(self, e): #print...
a208380a6cc8336d7806386338d378009879d3ec
satishbv79/may8superclass
/venv/Scripts/May16/May20_listb.py
186
3.96875
4
# l=[1,2,3,'Qspiders'] # l.insert(-1,'jspiders') # #print(l[4]) # for var in l: # print(var) l=[1,2,3,'Qspiders'] l.insert(-10,'jspiders') #print(l[4]) for var in l: print(var)
c81412cf368684b7be859802d8b79d423f9b9867
togoh9175/01-Lucky_Unicorn
/05_token_generator_v3.py
503
3.859375
4
import random # main routine goes here STARTING_BALANCE = 100 balance = STARTING_BALANCE # Testing loop to generate 20 tokens for item in range(0,100): chosen_num = random.randint(1,100) # Adjust balance if 1 <= chosen_num <= 5: chosen = "unicorn" balance += 4 elif 6 <= chosen_num <= 36: chosen = "donkey" ...
01e84b7773aa77d01133acddb2b091c4f62fb36d
five3183/change_calculator
/change.py
960
3.984375
4
''' Simple function go get optimal change ''' CURRENCY = [('Hundreds', 100), ('Fifties', 50), ('Twenties', 20), ('Tens', 10), ('Fives', 5), ('Ones', 1), ('Quaters', .25), ('Dimes', .10), ('Knickles', .05), ('Pennies', .01)] def get_change(cost, paid): ''' input = cost of item amount paid outpu...
d2ed8cc164edad96a43a6bf3e2378b06587f1cff
AbuRuqaa/File-Automation
/Findyourfile.py
3,027
4.1875
4
#This project find any png file and put it in a specific folder import os, shutil, re from pathlib import Path as path import pyinputplus as pypi ''' How this script work: 1-First you choose the tree that you want to search for your file in 2-It will copy it to another folder 3-Then It will g...
de7eee460bb9f3637a10d856076033e7806d3760
safelyafnan/Muhammad-Safely-Afnan_I0320070_M-Wildan-Rusydani_Tugas6
/I0320070_Exercise 6.1.py
134
3.5
4
#menentukan banyak pengulangan n=5 #melakukan pengulangan i = 1 while 1 <= n: print(1) i = 1 + 1 #bisa ditulis: i += 1
687ccef9677f9b1e00a388a835bf889eee6b1706
Roma386/TheDiversantGame-1.2.
/div12.py
2,808
3.59375
4
""" The Diversant game, ver. 1.2.0 """ import random import time # Задаем возможные повреждения, которые в случайном порядке будут наноситься персонажу # Как мы видим, 37,5% вероятности, что будет промах dam = (0, 0, 0, 5, 10, 15, 20, 30) # Создаем класс персонажа и его характеристики: позиция, здоровье, цвет class h...
4b9cff0a51b35b1f43e9ef9d4f9fc06fdde5c87c
jadeli1720/Sprint-Challenge--Hash-BC
/hashtables/ex2/ex2.py
4,560
3.703125
4
# Hint: You may not need all of these. Remove the unused functions. from hashtables import (HashTable, hash_table_insert, hash_table_remove, hash_table_retrieve, hash_table_resize) """ UNDERSTANDING: Reconstruct you ...
f3a6e9373450ad0b097ea0910877534bb20d05a8
callmess/Pyth
/practice/second.py
110
3.921875
4
times=input("input the times you want:") if times>"3": print("are you sure?") else: print("ok! let's go!")
c1f4e4ba3b58e1361a4eb4fab346d0a368dfc514
callmess/Pyth
/playground/forin.py
124
3.828125
4
a={'a':12,'b':13} for k,v in a.items(): print(k,v) b=[3,6,9,13] for v in b: print(v) for c in 'asdfgh': print(c)
950af6a1c4cd4ffe12ff99061bb44cfd0104fec6
regismagnus/challenge_python
/is_list_palindrome.py
1,390
4.15625
4
''' Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in l, since this is what you'll be asked to do during an interview. Given a singly linked list of integers, determine whether or not it's a palindrome. Note: in examples below and tests preview linked lists a...
3b4b702a1885fe3f82eca005aa5524d3761c0aa7
regismagnus/challenge_python
/extract_each_k_th.py
357
3.96875
4
''' Given array of integers, remove each kth element from it. Example For inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and k = 3, the output should be extractEachKth(inputArray, k) = [1, 2, 4, 5, 7, 8, 10]. ''' def extractEachKth(inputArray, k): return [inputArray[i] for i in range(len(inputArray)) if (i+1)%k!=0]...
0f9ba273804db8997bd5ec73e7c233c11d58eac5
regismagnus/challenge_python
/longest_word.py
611
4.34375
4
''' Define a word as a sequence of consecutive English letters. Find the longest word from the given string. Example For text = "Ready, steady, go!", the output should be longestWord(text) = "steady". best solution by dnl-blkv: return max(re.split('[^a-zA-Z]', text), key=len) ''' def longestWord(text): rex='[\[...
7c56f6c905277c7ee6422d2da89891c337726309
regismagnus/challenge_python
/sorted_square_array.py
370
3.96875
4
''' You have a sorted array of integers. Write a function that returns a sorted array containing the squares of those integers. input test [-7,-3,-1,4,8,12] output [1,9,16,49,64,144] [1,2,3] output [1,4,9] [-3,-2,-1] output [1,4,9] [] output 'INVALID INPUT' ''' def sortedSquareArray(a): return sorted(list(map(lam...
eb91ccc2550bbe51c9f8c3a4e3cf13094572d2c1
regismagnus/challenge_python
/array_max_consecutive_sum.py
692
3.90625
4
''' Given array of integers, find the maximal possible sum of some of its k consecutive elements. Example For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be arrayMaxConsecutiveSum(inputArray, k) = 8. All possible sums of 2 consecutive elements are: 2 + 3 = 5; 3 + 5 = 8; 5 + 1 = 6; 1 + 6 = 7. Thus, the ...
8dcb77e43063abbcfcdb1013729aa6a0002bf970
lukeSchombert/Memory
/Game.py
2,192
3.984375
4
from app import clickedTile from Tile import tiles incomplete = tiles complete = [] selectedButton = ? matchAttempt = 0 def main(): # A while loop will continuously put the user back after guessing each time # I'm having trouble here 'grabbing' the button to compare their values keepGoing = True whil...
e8050ac995c0cfd39de576c9535aac17e6efd405
Santkey/Python
/Ex6.py
493
3.515625
4
from random import randint los = randint(1,100) #los z przedziału 1 do 100 odp = -1 # aby liczba wykraczała poza podany przedział i = 0 #liczba zgadnięć print("Zgadnij liczbę z przedziału (1 do 10)") while odp != los: i += 1 #dodaj liczbę zgadnięć odp = int(input("Podaj liczbę: ")) if odp > los: ...
1325c5a2f1d2772981fb82faef60cf68d40e32b4
Lor3nzoMartinez/Python
/SPR19/Notes/Chapter 7 notes.py
5,431
3.5
4
import turtle, random wn = turtle.Screen() alex = turtle.Turtle() tess = turtle.Turtle() # Problem 7_0 # def num_ints(n): # mah_nums = [] # for i in range(1, n+1): # if i % 7 == 0 and i % 5 != 0: # mah_nums.append(i) # return mah_nums # # # print(num_ints(500)) # # Problem 7_1 # d...
23e83c99abcd008517eb3dd8898f08673d4275c7
Lor3nzoMartinez/Python
/SPR19/Chapter_2_Homework/hw_2_1.py
290
3.96875
4
# Chapter 2 Exercise 1 Homework listy = ["All", "work", "and", "no", "play", "makes", "Jack", "a", "dull", "boy."] sentence = "" print("\nAs different variables:") for i in listy: sentence += i + " " print(i) print("\nPrint variables into single sentence:" + "\n" + sentence)
a9a33d6b286d9d68c34d93213d16df7f223dc2ee
Lor3nzoMartinez/Python
/SPR19/Quiz&EC/TakeHome _Quiz_7.py
1,850
3.71875
4
import random # # # Problem 1) # # # Words = ['The', 'moment', 'a', 'little', 'boy', 'is', 'concerned', 'with', 'which', 'is', 'a', 'jay', # 'and', 'which', 'is', 'a', 'sparrow', 'he', 'can', 'no', 'longer', 'see', 'the', 'birds', # 'or', 'hear', 'them', 'sing'] # # # def find_position(List): # co...
08a2bb3a079b695c86a541c7865f30052c70d4ee
Lor3nzoMartinez/Python
/SPR19/Notes/Chapter 6 notes.py
2,069
3.765625
4
import math # Problem 6_0 # def circle_area(Radius): # ans = math.pi * Radius **2 # return ans # # print(circle_area(12)) # Problem 6_1 # def avg_2_nums(x, y): # ans = x + y # ans = ans/2 # return ans # # print(avg_2_nums(2,4)) # Problem 6_2 # def distance(x1, y1, x2, y2): # D1 = math.s...
77878affcb63043b52a1b6146da400d6abd694e2
Lor3nzoMartinez/Python
/SPR19/Notes/Chapter 8 notes.py
1,565
3.75
4
alphabet = 'abcdefghijklmnopqrstuvwxyz' Upper_alpahbet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Problem 8_1 def numeric_value_ofL(letter): counter = 1 letter = letter.lower() for i in alphabet: if i == letter: break counter += 1 answer = counter return answer # Problem 8_...
c774829ee12053764e30781837e38075c114adcf
Lor3nzoMartinez/Python
/SPR19/Chapter_2_Homework/hw_2_6.py
1,143
3.875
4
# Chapter 2 Exercise 6 Homework ''' My initial guesses: (a) 5 % 2 = 1 (b) 9 % 5 = 4 (c) 15 % 12 = 3 (d) 12 % 15 = 0 (e) 6 % 6 = 0 (f) 0 % 7 = 7 (g) 7 % 0 = 7 ''' print("5 % 2 =", 5 % 2, "\n9 % 5 =", 9 % 5, "\n15 % 12 =", 15 % 12, "\n12 % 15 =", 12 % 15, "\n6 % 6 =", 6 % 6, "\n0 % 7 =", 0 % 7, "\n7...
bee95c39ec36fa669a574732be32e6a85d024117
bvishny/basic-algos
/mergesort_inversions.py
2,008
4.25
4
# Basic Merge Sort Implementation # Components # 1. split_array(array) array array - takes an array and splits it at the midpoint into two other arrays # 2. merge(array, array) array - takes two split arrays and merges them together sorted # 3. mergesort(array) array - takes an array and sorts it using mergesort def s...
59bb2bdc83c77c2384b221fd74e15466b4314edf
mintdouble/LeetCode
/Medium/677_键值映射/main.py
564
3.65625
4
class MapSum: def __init__(self): """ Initialize your data structure here. """ self.dic = {} def insert(self, key: str, val: int) -> None: self.dic[key] = val def sum(self, prefix: str) -> int: summary = 0 for i in self.dic.keys(): if le...
374f262c78d894881185db9bdccc4cdc88905855
mintdouble/LeetCode
/Easy/455_分发饼干/main.py
650
3.5
4
# 思路:分别对两个列表进行排序,从最小值开始比较,如果胃口大于饼干,则饼干后移一个 # 如果胃口小于等于饼干,则计数加一,饼干后移一位,胃口也后移移位,直到其中一个移到结尾 class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g = sorted(g) s = sorted(s) g_i = 0 s_i = 0 count = 0 while g_i < len(g) and s_i < len(s): ...
2eb16cafc9b7bd04b02848ca9281c0783ed2bd75
mintdouble/LeetCode
/Medium/763_划分字母区间/main.py
842
3.59375
4
# 思路:统计每个字符出现的起始位置为终结位置,完全不相交的区间才能分割,相交的各区间,取其中最小值为左界,最大值为右界形成新的区间, # 所有新区间都不相交,每个新区间就是分割的字符串的位置 class Solution: def partitionLabels(self, S: str) -> List[int]: dic = {} result = [] for i in range(len(S)): if S[i] in dic: dic[S[i]][1] = i+1 else: ...
81492726c4b54a9674602c2fdc5e9ceb76d73460
mintdouble/LeetCode
/Easy/258_各位相加/main.py
327
3.6875
4
# 思路:多观察几组数据就能发现规律,各位相加的结果就是就是该数对9取余数,如果余数为0,则结果为9,不为0则结果为余数,0本身除外 class Solution: def addDigits(self, num: int) -> int: if num == 0: return 0 return num%9 if num%9 != 0 else 9
5a7041de1b6571afce5c10870bf67c6d6e488d62
mintdouble/LeetCode
/Easy/605_种花问题/main.py
1,936
3.859375
4
# 思路:计算连续0的个数即可,但要注意把一些特殊情况考虑进去 # 当花坛只有1个位置或2个位置时,必须这些位置都是0才能种下n<2朵花 # 当花坛位置数大于2时,则计算连续0的个数,由于首部和尾部只需连续两个0就能钟一朵花,而中间位置要3个0,所以初始化连续0个数时将其设为1 # 遍历花坛的位置,如果此位置上的数为1,则将连续0个数置0,如果此位置上的数为0,则将连续0个数加1 # 判断连续0个数是否等于3,如果有3个连续0的话,则将种花数加1,而由于再中间的0位置上种了花,所以此时连续0个数需要减2 # 当遍历到花坛最后一个位置上时,如果此时连续0个数为2,说明最后有两个连续0,是可以再种一朵花的,需要将种花数再加1 # 同样,...
6578fd20dfb520f1469396b11670e754bd0732dd
mintdouble/LeetCode
/Easy/581_最短无序连续子数组/main.py
707
3.515625
4
# 思路:将数组与排序后的数组进行对比,相同下标上的数如果不相同,则该数是需要排序的,因此分别从前和从后开始查找第一个不相同的数 class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: nums_sort = sorted(nums) head = 0 tail = len(nums) - 1 flag = True while flag and head < tail: if nums[head] == nums_sort[head]...
cc0bb7410ef9451cb9d23cba7c79f8dfd747f14a
mintdouble/LeetCode
/Medium/48_旋转图像/main.py
891
3.703125
4
# 思路:按层旋转,先旋转最外层,然后旋转内层,每次旋转四个元素,从四个角元素开始,直到该层转完 class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ head_i, head_j = 0, 0 tail_i, tail_j = len(matrix) - 1, len(matrix[0]) - 1 while head_i ...
51f84efafa51929e9f6db0dd5a3f9f8c4e41a4ba
mintdouble/LeetCode
/Easy/868_二进制间距/main.py
421
3.796875
4
# 思路:利用快慢指针,遍历二进制数,计算两个1之间的间隔 class Solution: def binaryGap(self, N: int) -> int: binN = bin(N) i,j,count = 2,3,0 while j < len(binN): if binN[j] == '0': j += 1 else: if count < j - i: count = j - i i...
85d45b16cb618bd9bc92b61b5c2e871923f2c6c7
kkbwilldo/boostcamp
/3일차/2133 타일 채우기/2133_타일채우기_전주영_x.py
159
3.65625
4
# n=int(input()) def sol(n): result=0 if n%2==1: result=0 else: result=3**(n//2) print(result) for x in range(1,30): sol(x)
3214d258b3b6dd426d622a4ca8b76da43a8a9755
vairus666/lesson9
/fizzbuzz.py
367
4
4
def Fizz(a = 0, b = 0): for number in range(a, b): # if number % 3 == 0 and number % 5 == 0: # print('FizzBuzz') if number % 3 == 0: print('Fizz') # elif number % 5 == 0: # print('Buzz') else: print(number) a = int.inp...
2ded5316ca58199a61fb6287472a08997eef4f73
shahakshay11/DFS-1
/zero_one_matrix.py
1,675
3.609375
4
""" // Time Complexity : O(m*n) // Space Complexity : O(m*n) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : No // Your code here along with comments explaining your approach Algorithm explanation BFS - Initial conf - Update the 1s to inf and add the values with 0 to th...
806513ea489da069e1da10f4a1accc45f51090e7
OmAshish/Python-Programs
/players.py
430
3.9375
4
dict={} N=[] E=[] n=int(input('No of players in each team : ')) m=int(input('No of teams : ')) for i in range(0,m): z=input('Enter the team''s name: ') E.append(z) for j in range(0,n): u=input('Enter the player''s name : ') N.append(u) dict[E[i]]=N N=[] F=input('Enter th...
dfadc834cef55e5ce177a5bf7bdf6f6c7d21e5b8
wkim300/data_structures-and-algorithms
/stack_queue/queue.py
6,164
4.0625
4
""" Implement using linked-list, with tail pointer: - enqueue(value) - adds value at position at tail - dequeue() - returns value and removes least recently added element (front) - empty() Implement using fixed-sized array: If implemented this way, "read" and "write" pointers needs to be pointing at the next dequeue a...
a637c62a8e579efc8f20d8f18c64dd237c8eae29
OreoCookiesYeah/base2
/hm_02_事件检测.py
1,303
3.53125
4
# pygame python第三方游戏库 .pyd 动态模块(可以导入,但是看不到源码) .py 静态模块 import pygame # 官方推荐这样导入 from pygame.locals import * import sys def main(): # 一般将程序的入口定义为main函数 """主函数""" # 1. 创建窗口 window = pygame.display.set_mode((512, 768)) # 2.贴背景图 # 加载图片 image = pygame.image.load("res/img_bg_level_1....
e1e45b9289ffc85c6203188e19d320478b40e782
shubhamPrakashJha/selfLearnPython
/6.FunctionalProgramming/8.IterationTools.py
342
3.953125
4
from itertools import count,accumulate,takewhile,product,permutations for i in count(3):#counts from 3 to infinite print(i) if i>=11: break nums = list(accumulate(range(8))) print(nums) print(list(takewhile(lambda x: x<=6,nums))) letters = ("A","B") print(list(product(letters,range(2)))) print(list(p...
1ea854878930dabb0427f78c7defe2f1331dd5d1
shubhamPrakashJha/selfLearnPython
/4.Exception and Files/8.WorkingWidFile.py
203
3.5625
4
try: myfile = open("filename.txt","w") myfile.write("this has been written 1st time to the file") finally: myfile.close() with open("filename.txt", "r") as myfile: print(myfile.read())
403a8e81c0c40a824df49e21776e986445d76bd0
shubhamPrakashJha/selfLearnPython
/3.function and module/module.py
185
3.734375
4
import random from math import pi,sqrt as square_root # import some_module for i in range(5): value = random.randint(1,6) print(value) # print(sqrt(pi)) print(square_root(pi))
b98c45e58694e05b7fadee7721ce57a4e625c603
shubhamPrakashJha/selfLearnPython
/6.FunctionalProgramming/6.Recursion.py
328
4.1875
4
def factorial(x): if x == 1: return 1 else: return x*factorial(x-1) print(factorial(int(input("enter the number: ")))) def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_even(23)) print(is_odd(1)) print(is...
7d8839f939e416611c5a680de28141f71915a315
Ranimaheshwari/Quiz-implementation-by-python
/quiz/check.py
284
3.8125
4
import random import pickle file=open("ques_for_quiz.txt","rb") dict_ques=pickle.load(file) file.close() score=0 l1=dict_ques.keys() l1=list(l1) print(l1) l3=[] for i in range(10): while True: a=random.choice(l1) if a not in l3: l3.append(a) break print(l3)
0a2af53c3dcd65939101b566442605e4f5edc667
d3ming/hackerrank-solutions
/bigger-is-greater/solution.py
1,459
3.859375
4
# https://www.hackerrank.com/challenges/bigger-is-greater ## read inputs num_tests = int(input().strip()) test_cases = [] for i in range(0, num_tests): test_cases.append(input().strip()) ## helpers # get array of chars from a string def getCharArr(str): ret = [] for c in str: ret.append(c) ...
0e40ebd5a6a80ff69f3abfc071405d7a7cad2f9d
d3ming/hackerrank-solutions
/encryption/solution.py
719
3.984375
4
#!/bin/python3 # https://www.hackerrank.com/challenges/encryption import sys import math s = input().strip() l = len(s) sqrt_l = math.sqrt(l) rows = math.floor(sqrt_l) cols = math.ceil(sqrt_l) # it's OK for rows to == cols, for when we need to make it fit the string if (rows * cols) < l: rows += 1 # Split strin...
5e4c4ebae7714afa65a208a80912de85687dedc8
Seba-san/pyquaternion
/pyquaternionIO.py
3,747
3.6875
4
import numpy as np import math """ Esta libreria es la libreria de Quaterniones generada por y para el Instituto de Automatica INAUT: link """ class Quaternion: """ Objeto cuaternion creado ad hoc para este caso Se toma: q=w+xi+yj+zj=[w,a] q=cos(fi/2)+sin(fi/2)*[x,y,z] """ def __init__(...
60a192dcdca7eeacae6fd469cf3488cde12b28d2
Andrew-liu/learn_python_the_hard_way
/exercise/ex40.py
582
3.578125
4
# -*- coding:utf-8 -*- #directory / hash #list things = ['a', 'b', 'c', 'd'] print things things[1] = 'z' #会将原来第二位的元素覆盖 print things[1] #hash_map print things stuff = {'name' : 'Zed', 'age' : '36', 'height' : 6 * 12 + 2} print stuff['name'] print stuff['age'] print stuff['height'] stuff['city'] = "San Francisco...
5c907f780b3df88dea7e692dbfc0f99e715d04b5
nobbynobbs/devman-async-python-1
/spaceship/objects/timeline.py
550
3.5625
4
"""simple year container""" import dataclasses from core.loop import sleep from settings import YEAR_IN_SECONDS @dataclasses.dataclass class Timeline: """use mutable object intead global variable""" year: int async def run(self): """periodically increments the year""" while True: ...
28d107c1d0d20e0c57d2f38d0d2b7000ffe84fc1
rmoein/Raspberry-pi-gas-sensor-data-collection
/gas_composition_monitor.py
9,920
3.71875
4
##!/usr/bin/python # Written by Reza Moein Taghavi, August 2018 # if you have any questions, contact me at rezamoeint@gmail.com # This program collects and stores sensor data (O2, CO2, and Humidity) attached to Raspberry Pi. It also controls a # motor pump through a relay switch. # the sensors used are: # COZIR CM-0...
1fc61716ff10b5ec25337e7a7d32ad6b649146d7
juechen-zzz/LeetCode
/python/0040.Combination Sum II.py
1,232
3.65625
4
''' 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 Example 1: Input: candidates = [10,1,2,7,6,1,5], target = 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] Example 2: Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,...
6ef787e7b4ae2e961aee726efb51471d5736b51e
juechen-zzz/LeetCode
/python/0060.Permutation Sequence.py
1,184
3.90625
4
''' The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. Given k wi...
f9a34ec2cd69deb1bc020afd803e3abd5f3ac877
juechen-zzz/LeetCode
/python/0207.Course Schedule.py
2,706
4.125
4
""" There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for yo...
a380785b1eae7a6a8ee4347ffeffc40650c722a1
juechen-zzz/LeetCode
/python/0035.Search Insert Position.py
958
3.953125
4
''' 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0 ''' # 法一 class Solution: def searchInsert(self, nums: List[int], target: int) -> i...
31a9a549c9081afa232d1270006b7a10f185f4f8
juechen-zzz/LeetCode
/python/0350.Intersection of Two Arrays II.py
516
3.96875
4
""" 给定两个数组,找出其中重叠的数字(重复出现的全算) Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] """ class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: if len(nums1) == 0 or len(nums2) == 0: return [...
823f3ae5f352d45ebba18821b0fa8f039539b467
juechen-zzz/LeetCode
/python/0165.Compare Version Numbers.py
1,850
4.09375
4
''' Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate num...
6e6ed0aa1f2588c1a94459956c167d6fcb5895d6
juechen-zzz/LeetCode
/python/0002.add two numbers.py
1,013
3.609375
4
''' 给定两数(链表反序表示),相加后也反向存储成链表 Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None ''' # Definition for singly-linked list. # class ListNode: # ...
91b592e7f27cac692a9400bbf27ec3190a3ba72f
juechen-zzz/LeetCode
/python/0287.Find the Duplicate Number.py
560
4.03125
4
""" Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 """ class...
837c95fb0a7b12b26dd16d0c3c693ac16ed1bfd1
juechen-zzz/LeetCode
/python/0075.Sort Colors.py
1,075
4.21875
4
''' Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the l...
03f0ea9aff58f8dfae2f577e4705557df16717b9
juechen-zzz/LeetCode
/python/0204.Count Primes.py
739
3.953125
4
""" Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. """ # 要得到自然数n以内的全部质数,必须把不大于根号n的所有质数的倍数剔除,剩下的就是质数。 class Solution: def countPrimes(self, n: int) -> int: if n < 2: return 0 ...
3d5a03fb2cb384d46332eaca1940f90fb2abee83
WillMc93/AS.605.620
/Project1/code/strassen.py
4,418
3.65625
4
""" Implements the Strassen Matrix Multiplication algorithm. @ authour William McElhenney @ version 1.0 09/25/2019 """ from matrix_tools import * """ Implements Strassen matrix multiplication @param matrixA: the first matrix to multiply @param matrixB: the second matrix to multiply @return the product of matrixA ...
364a972488c75c7e869b7a52c0bc9f560186c199
bom2zzang/python_basic
/day_01/if.py
6,967
3.953125
4
''' pwd = input("비밀번호는 무엇?") if pwd == '0808': print("문이 열리네요....\n ㅎㅎㅎㅎㅎ") else : #생략가능 print("x") ''' ''' x = 10 if x == 10: print("x에 있는 숫자") # print(x) 들여쓰기 이렇게 하면 오류남... unexpected indent print(x) ''' ''' x = 10 if x == 10: print("x에 있는 숫자") print(x) #참 거짓 상관없이 무조건 출력되는 오류 ''' ''' pri...
2504db1118e055773562456ae955bd891561a11c
r-sorna/bank
/bankk.py
1,284
4.0625
4
while True: mail=input("enter your mail:") if "@" and "." in mail: if "gmail" and "outlook" in mail: break break else: print("please enter valid mail id") continue while True: schar=["@","#","%","*"] pas=input("enter your password:") if len(pas)==6 or len(pas)==7 or len...
da688fd7881f84e9d9c94d25c84e76cc4e50a849
josepfont65/neurodsp
/neurodsp/tests/test_utils_norm.py
1,191
3.546875
4
"""Tests for normalization related utility functions.""" import numpy as np from neurodsp.utils.norm import * ################################################################################################### ################################################################################################### def te...
af9dfce4900f6178cbbbc3962c8acbac5bf738cf
mqadimzadeh/Course-Projects
/creates a smily.py
1,313
4.03125
4
#Name: Mahsa Qadimzadeh Alamdari #UCID No.:30057724 #This program creates a smily centered to the point defined by the user #Importing SimpleGraphics and sets the background color from SimpleGraphics import * background("black") #Sets the background color #Ctreating the outline of face with the given center point...
c73bafa0553c4bd78eb32c739787566d13028e33
millnsbc/Python_Questions
/Q1.py
2,958
4.0625
4
#  student number:2098580 def do_arithmetic(x, y, op=''): ''' Performs an operation on two numbers and returns the result. Parameters ---------- x: int or float A number y: int or float A number op: str, optional represents an arithmetic operation. Takes the arguments: ...
a91a8c970d015656cbffdbd9d32cf0a038fcf98a
drakhir/pyety
/core/dice.py
2,959
3.734375
4
# -*- coding: utf-8 -*- """ Pyety: Dice """ import random from os import linesep class Dice(object): """Simulate a dice roll""" def __init__(self): try: # Initialize random seed self._r = random.SystemRandom() except NotImplementedError: # Use the default randomization if no ra...
ffe27468440c6cc96b9d4acbb39228d30dba00a4
learnwithlakshman/core-python
/source-code/day_4/sizefacedice.py
350
3.890625
4
import random num = random.randint(1,6) for i in range(1,4): gnum = int(input("Guess a number 1-6 :")) if num == gnum: print(f"Good you guessed number in {i} attempts") break else: print(f"Sorry wrong guess") if i == 3: print("You have reached max attempts, try ...
80f3d083d5ad7461481bd65e8535dc9c1abd0084
learnwithlakshman/core-python
/source-code/day-10/factorial.py
373
4.03125
4
# 1 + 1 / 2! + 1 / 3! + 1 / 4! +...... 1/n! def factorial(num): res = 1 for i in range(2,num+1): res *= i return res def sum_of_series(n): sum = 1 for i in range(2, n + 1): sum += 1/factorial(i) return sum num = 5 res = factorial(num) sum = sum_of_series(num) print(f"The fa...
ab423cf0655963fbcfe1fc0fb4f72ba3a1fb3b4e
learnwithlakshman/core-python
/source-code/day_2/profitorloss.py
296
3.9375
4
# Profit or loose example b_price = int(input("Enter the Buying price: ")) s_price = int(input("Enter the selling price: ")) res = s_price - b_price if res < 0: print(f"You made a loose of {res}") elif res > 0: print(f"You made a profit of {res}") else: print("No profit No loose")
d64eb4e1af0d2ed45bf68f0e5be7ee0a35ddfcbd
learnwithlakshman/core-python
/source-code/day_5/generatefirstnprime.py
400
4
4
N = int(input("Enter the N value:")) num = 2 count = 0 while True: isprime = True if num % 2 == 0 and num != 2: isprime = False else: for i in range(2,(num//2)+1): if num % i == 0: isprime = False break if isprime and num > 1: count +=...
0ce445d17c7ec5b1b8479c2129da5b9f73258258
kramalab-iith/SSL_PointClouds
/Covertree/naiveknn.py
544
3.5625
4
# File: naiveknn.py # Author: Nil Geisweiller # email: ngeiswei@gmail.com # Date: # All Rights Reserved. Copyright Nil Geisweiller 2011 # # This function to perform maive nearest neighbors. from heapq import nsmallest def knn(k, pt, pts, dist_f): '''Return the k-nearest points in pts to pt using a naive alg...
c07b0cc443ce2b3e4a5b070ee60f4498161d399d
ankuriitk/sample_code
/part2.py
2,039
3.640625
4
import json , math #JSON file is assumed to be a list of dictionaries each describing 1 friend #JSON Format example: #[{"user - id":12 , "name":"asket" , "x_coordinate":84.2232 , "y_coordinate":77.23432} # {"user_id":13 , "name":"shubham" , "x_coordinate":86.435} , "y_coordinate":77.4432} # .......... #] class...
7b3b4e75ddcd0eb01b1e49e7382357a568ab9ada
matheusforlan/TST-P1
/imposto/roubo.py
493
3.5
4
#coding:utf-8 bruto = float(raw_input()) horas = float(raw_input()) print "Salário Bruto = {:.1f}".format(bruto) print "Hora Bruta = {}".format(bruto/horas) ir = bruto*0.11 inss = bruto*0.08 sindicato = bruto*0.05 print "Desconto IR = {:.1f}".format(ir) print "Desconto INSS = {:.1f}".format(inss) print "Desconto Sindic...
b372fdee4ca5a6730d82d83b312d1da3cb296218
matheusforlan/TST-P1
/forvogal/word.py
232
3.515625
4
#coding:utf-8 palavra = raw_input() lista = [] vogais = ["a","e","i","o","u","A","E","I","O","U"] for c in palavra: lista.append(c) for m in lista: if m in vogais: print "<{}> sim".format(m) else: print "<{}> nao".format(m)
a7a3494516f9df4c2667ea90dd88e474d54c67a5
matheusforlan/TST-P1
/agendaordenada/ordemalfa.py
673
3.921875
4
#coding:utf-8 def lista_ordenada(lista, nome): lista.append(nome) if len(lista) != 1: #tem que ser diferente de 1 para ordenar... for c in range(len(lista)-1, 0, -1): #adiciona no final e vai comparando de trás if lista[c] < lista[c-1]: # para frente lista[c], lista[c-1] = ...
0b488f94258a3e15d80eaab1b605e0c6775f8edc
matheusforlan/TST-P1
/ponderada/medpon.py
293
3.5625
4
#coding:utf-8 n1 = float(raw_input()) n2 = float(raw_input()) n3 = float(raw_input()) peso1=float(raw_input()) peso2 = float(raw_input()) peso3 = 100-peso1-peso2 media = (n1*(peso1/100)+n2*(peso2/100) +n3*(peso3/100))/(peso1/100+peso2/100+peso3/100) print "Média Final: {:.1f}".format(media)
b4002e892bec846b3dcecfef7685cebdb13cd7a8
matheusforlan/TST-P1
/ceramica/calculo.py
416
3.859375
4
#coding:utf-8 capacidade = float(raw_input("Capacidade de revestimento?")) print " " print "== Dados do vão a revestir ==" c = float(raw_input("Comprimento? ")) l = float(raw_input("Largura? ")) a = float(raw_input("Altura?")) print " " print "== Resultados ==" area = c*l+2*a*c+2*a*l print "Área total a revestir: {:.1f...
1692461d248ca794a46031acfd846eb29b1fd956
matheusforlan/TST-P1
/defdivisor/divisor.py
262
3.5625
4
#coding:utf-8 def divisor(num,lista): indice = -1 for c in range(len(lista)): if lista[c]%num == 0: indice = c break return indice lista1 = [100,10,40,50] lista2 = [3,15,50,23,5] assert divisor(10, lista1) == 0 assert divisor(5, lista2) == 1
b7eb32bfc11b33e7ce8dbfc6124356d71c1c7f54
matheusforlan/TST-P1
/campinense/campanha.py
1,015
3.5625
4
#coding:utf-8 campanha = [] vitorias = 0 empates= 0 derrotas = 0 pontos_casa = 0 pontos_fora = 0 gols_pro = 0 gols_contra = 0 for c in range(10): jogos = raw_input() campanha.append(jogos) for mando in campanha: if mando[5] == "c": if int(mando[0]) > int(mando[2]): vitorias += 1 pontos_casa += 3 elif int(m...
f38f0ed9558c1a45a80c614a6fa4d356e7191f3b
matheusforlan/TST-P1
/tijolos/quantidade.py
620
3.6875
4
#coding:utf-8 preco = float(raw_input("Digite o preço da unidade do tijolo (Em reais): ")) altij = float(raw_input("Digite a altura do tijolo (Em metros): ")) comtij = float(raw_input("Digite o comprimento do tijolo (Em metros): ")) alpar = float(raw_input("Digite a altura das paredes (Em metros): ")) compar = float(ra...
1eaafc390076960d3562f7cb6eb455e66fec49cb
matheusforlan/TST-P1
/crialogin/guardians.py
488
3.671875
4
#coding:utf-8 def meu_in(elemento,sequencia): for e in sequencia: if e == elemento: return True return False def cria_login(nome): split_nome= nome.split() login = "" login += split_nome[0].lower() conectores = ["de","da","do"] for c in range(1,len(split_nome)): if not meu_in(split_nome[c],conectores...
b25276c96fa929ed7298fc2133fa65f2a63d99fb
matheusforlan/TST-P1
/defanula/opostos.py
564
3.640625
4
#coding:utf-8 def anula(lista): for c in range(len(lista)-1,0,-1): if len(lista) == 1: return lista if lista[c] + lista[c-1] == 0: lista.pop(c) lista.pop(c-1) lista1 = [1, 2, -2, 3, 4] assert anula(lista1) == None assert lista1 == [1, 3, 4] lista2 = [1, 2, -2, -1, 4] assert anula(lista2) == None as...
a29abf118fc3d65ec54940d3b0ab74dac9fdd33f
zodiac15/python
/matrixadd.py
1,568
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 17 09:03:19 2018 @author: Ayush """ a=[[0,0,0], [0,0,0], [0,0,0]] b=[[0,0,0], [0,0,0], [0,0,0]] c=[[0,0,0], [0,0,0], [0,0,0]] d=[[0,0,0], [0,0,0], [0,0,0]] m=[[0,0,0], [0,0,0], [0,0,0]] print "enter elements o...