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
dd7c7d610693962c38b03cad154d0bcedd243ad8
smile0304/py_asyncio
/chapter11/thread_sync.py
552
3.671875
4
import threading from threading import Lock,RLock total = 0 lock = RLock() def add(): global lock global total for i in range(1000000): lock.acquire() lock.acquire() total += 1 lock.release() lock.release() def desc(): global lock global total for i in ra...
7d22306762bb54a09f2d764a83bc8ed60ea8c706
smile0304/py_asyncio
/chapter05/biset_test.py
314
3.8125
4
import bisect #用来处理已排序的序列,用来维持已排序序列(升序) #二分查找 inter_list = [] bisect.insort(inter_list,3) bisect.insort(inter_list,2) bisect.insort(inter_list,5) bisect.insort(inter_list,1) bisect.insort(inter_list,6) print(bisect.bisect_left(inter_list,3)) print(inter_list)
ae591c5ccda56d20dd75a06bbbec5ba51556efe0
Hassiad/100-days-of-Code-Python
/20_21-Snake_Game/main.py
1,236
3.796875
4
# Day 20 and 21 Snake Game from turtle import Turtle, Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time """Screen setup""" screen = Screen() screen.setup(width=600,height=600) screen.bgcolor("black") screen.title("Timmy Snake Game") screen.tracer(0) """Initial 3 segme...
acf5a86f8be7589c70c6156e8935379ba7295a1d
akashsury/Operations
/Operations.py
1,683
3.8125
4
class Operations: def __init__(self): pass def aboveBelow(self, values, comparison): dict = {"above": 0, "below": 0} # created as local variable, each call it has to have zero if not isinstance(comparison, int) or not isinstance(values, list): return False...
f0206ac8aa63ea9b17d861d3115932b014abcbfc
sensecollective/bioinformatics-coursera
/find_sequence.py
524
3.578125
4
#!/usr/bin/env python import sys import operator #first argument is a single-line fasta input seq_f = sys.argv[1] f = open(seq_f) #f.readline() #toss input line seq = f.readline() #grab fasta seq = seq.strip() kmer = f.readline().strip() #grab kmer f.close() #second argument is the k-mer to find #kmer = sys.argv[2...
97001f35773373489d615f21fd25d2cba18a20ef
Nisarga-AC/python-for-mbas
/Part 1/strings.py
720
4.0625
4
# Strings are text surrounded by quotes # Both single (' ') and double (" ") can be used kanye_quote = ('My greatest pain in life is that I will never ' 'be able to see myself perform live.') print(kanye_quote) # Switch to single quotes if your string uses double-quotes hamilton_quote = 'Well, the word got around, th...
1c1c65e73e9072be54e5428f4a9c4f95745658e9
yyassif/My_Util_Scripts
/multi_threading.py
1,450
3.578125
4
import threading import time class MyThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting", self.name, "\n") thread_lock.acquire() print_time(s...
ba84d228a663b9c9dce7dc8fc2916a55fca1305b
PrajaktaJadhav2/Problems-on-DS-and-Algos
/The_Celebrity_Problem.py
1,421
4.03125
4
# Problem Statement # A celebrity is a person who is known to all # but does not know anyone at a party. # If you go to a party of N people, find if there is a celebrity in the party or not. import numpy as np def celebrity(): n = int(input("Enter the number of people")) matrix = [] #Get the number of peo...
da34092f0d87be4f33072a3e2df047652fb29cf3
sudj/24-Exam3-201920
/src/problem2.py
2,658
4.125
4
""" Exam 3, problem 2. Authors: Vibha Alangar, Aaron Wilkin, David Mutchler, Dave Fisher, Matt Boutell, Amanda Stouder, their colleagues and Daniel Su. January 2019. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. def main(): """ Calls the TEST functions in this module. """ run_tes...
b2e763e72dd93b471294f997d2c18ab041ad665c
Evanc123/interview_prep
/gainlo/3sum.py
1,274
4.375
4
''' Determine if any 3 integers in an array sum to 0. For example, for array [4, 3, -1, 2, -2, 10], the function should return true since 3 + (-1) + (-2) = 0. To make things simple, each number can be used at most once. ''' ''' 1. Naive Solution is to test every 3 numbers to test if it is zero 2. is it possible to c...
c40c9fcd27f8cf8f9ecf46cf7c576507450fb6e3
Evanc123/interview_prep
/dynamic_programming/edit_distance.py
2,307
3.96875
4
# A Naive recursive Python program to fin minimum number # operations to convert str1 to str2 def editDistance(str1, str2, m , n): # If first string is empty, the only option is to # insert all characters of second string into first if m==0: return n # If second string is empty, the only op...
408aa37f423d41ae5b724fbae02a5a92228ddfb0
packetbuddha/SecretSanta
/secret_santa/secret_santa.py
4,923
3.53125
4
#!/usr/bin/env python """ Description: Plays traditional Secret Santa game, printing results to stdout, to files or send via email. Author: Carl Tewksbury Last Update: 2019-11-27 - Py3-ize; remove unneeded passing of couples var; email auth password now in file. """ # stdlib imp...
0664bf4c09687ee98fb8f81d11c6691ddaa67642
CrazyCoder4Carrot/lintcode
/python/Reverse Linked List II.py
1,155
3.890625
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The head of linked list @param m: start position @param n: end position """ def reverseBetween(self, head, m, n):...
fa7f6f44b5a764f35e32120ecb1dba1595c16dd6
CrazyCoder4Carrot/lintcode
/python/Subsets.py
499
3.75
4
class Solution: """ @param S: The set of numbers. @return: A list of lists. See example. """ def subsets(self, S): # write your code here res = [] S.sort() self.search(S, [], 0, res) return res def search(self, nums, temp, index, res): if index == ...
152113e43cceee7807ab807267ca54fb2a1d1c19
CrazyCoder4Carrot/lintcode
/python/Search a 2D Matrix.py
352
3.765625
4
class Solution: """ @param matrix, a list of lists of integers @param target, an integer @return a boolean, indicate whether matrix contains target """ def searchMatrix(self, matrix, target): # write your code here for row in matrix: if target in row: ...
96df8f1ee63a40fde99d66d6218987cf119a12e6
CrazyCoder4Carrot/lintcode
/python/Swap Two Nodes in Linked List.py
1,319
3.953125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head, a ListNode # @oaram {int} v1 an integer # @param {int} v2 an integer # @return {ListNode} a new head of singly-linked list ...
5ebd4c91bd2fd1b34fbfdcff3198aef77ceb8612
CrazyCoder4Carrot/lintcode
/python/Insert Node in a Binary Search Tree.py
1,676
4.25
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ Revursive version """ class Solution: """ @param root: The root of the binary search tree. @param node: insert this node into the binary search tree. @return...
d14d74df34371a880c57f2580e2f27cc9a35aee6
CrazyCoder4Carrot/lintcode
/python/Insertion Sort List.py
1,696
3.921875
4
""" 932ms version insert node in the same list """ class Solution: """ @param head: The first node of linked list. @return: The head of linked list. """ def insertionSortList(self, head): # write your code here cur = head index = head tempmax = head.val while...
1a5645ba8a8b640312045416a97fcabd7ff14e6e
CrazyCoder4Carrot/lintcode
/python/Rotate List.py
918
3.96875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head: the list # @param k: rotate to the right k places # @return: the list after rotation def rotateRight(self, head, k): # write your ...
0046fd9fa359ebfaa81b7fb40ecf2c5f6d278273
sfagnon/stephane_fagnon_test
/QuestionA/QaMethods.py
1,120
4.21875
4
#!/usr/bin/python # -*- coding: utf-8 -*- #Verify if the two positions provided form a line def isLineValid(line_X1,line_X2): answer = True if(line_X1 == line_X2): answer = False print("Points coordinates must be different from each other to form a line") return answer #Verify i...
7a50c599822eba23ea3de2e98fe95a7fdc7c8152
PanQnshT/Projekt_X
/ship.py
1,149
3.53125
4
import pygame from pygame.math import Vector2 class Ship(object): def __init__(self, game): self.game = game size = self.game.screen.get_size() self.speed = 1.5 self.opor = 0.85 self.gravity = 0.5 self.pos = Vector2(size[0]/2,(size[1]/2)-(size[1]/4)) self.v...
f65179cd3fa2f47d95a538cded047baaf18c4d1c
ares5221/python-Learning
/day04/MaxtRotation.py
546
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __mtime__ = '2018/6/7' """ array=[[col for col in range(4)] for row in range(4)] #初始化一个4*4数组 for row in array: #旋转前先看看数组长啥样 print(row) print('-----开始旋转矩阵----') for i, row in enumerate(array): for index in range(i, len(row)): tmp = array[index][i] # get...
e5a2135657bb8bf74063da10c85701b820cf386e
mc-cabe/CompareLists
/compareLists.py
192
3.59375
4
arr1 = [] arr1 = raw_input("please enter list1:") arr2 = [] arr2 = raw_input("please enter list2:") if arr1 == arr2: print "arrays are the same" else: print "arrays are not the same"
f15c286da0a0de84375e3f71b88b3a2711e74180
umemotsu/deimscripts
/generateVoteData.py
1,724
3.578125
4
#coding:utf-8 # generateVoteData import csv, sys # read participan data def readParticipants(filename): partList = {} with open(filename,'rb') as csvfile: reader = csv.reader(csvfile,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL) for row in reader: person = {} ...
06176687b50a2f17535536bf922dc6254b5c348d
artmukr/Homework_4
/Homework_4.2.py
167
3.515625
4
link = input('Enter your link :') link = link.replace('https://', "") link=link.replace('www.', '') value_of_start = link.rfind('/') print(link[:value_of_start])
70d3fb39df6fd9c1e6f48569d0057d9c11c32dec
apotato369550/breadth-first-search-python
/main3.py
4,142
3.796875
4
# i think i get this # x and y # test it with another maze configuration def create_maze(): return [ "O..#.", ".#.#.", "....#", "#...#", "X.###" ] def create_maze_2(): return [ "...O##X", ".###...", ".####..", "...#...", "..###...
89df09062d2ccaefd9526ee559ee67bf9a837a39
AmrinderKaur1/turtle-crossing-start
/car_manager.py
2,061
3.640625
4
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 X = [-300, 300] Y_AXES_LIST = [[120, 220], [20, 120], [-120, -20], [-220, -120]] class CarManager: def __init__(self): self.all_cars = [] self.ca...
e606335002d2e02b40b59538d2dc59aba70eed6f
ganjingcatherine/leetcode_python
/sort_by_leetcode/math/hard/780 reaching point.py
1,487
3.59375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ 一开始的思路是逆向推,目的坐标(tx, ty)肯定是由(tx-ty, ty)或(tx, ty-tx),但是坐标限定不为负数,因此比较tx、ty的大小可以唯一确定上一步的步骤 类似搜索的题,从终点往起点看,比较容易猜到正解。 这个题的关键点是,如果 ty > tx,那么必然是从 (tx, ty-tx)到达(tx, ty)这个状态的。 想明白上面,还需要知道一个优化的思路:取模不要一次一次相减 题目大意: 从点(x, y)出发经过一次移动可以到达(x + y, y)或者(x, x + y) 给定点(sx, sy)与(tx, ty),判断(...
23167d9292e97e858d70c4836fe3f6cb4f09fc5f
getoverlove/Majiang
/eye/32-不放回摸球直到摸到a白b黑球的比例.py
1,309
3.609375
4
from fractions import Fraction from sympy import * f_dict = {} def f(m, n, a, b): """ m个白球,n个黑球,想要摸到a个白球,b个黑球 用递推式的方式计算准确结果,结果使用分数表示 """ assert a >= 0 and b >= 0 and m >= 0 and n >= 0 assert a <= m and b <= n param = (m, n, a, b) if param in f_dict: return f_dict[param] if...
c99ba21ebb47076b3fcefefc8d29e9ad6bcf50e3
getoverlove/Majiang
/eye/40-多目标不放回摸球每个目标与总目标的关系.py
2,083
3.796875
4
""" 当前局面到胡牌局面的差 D={d1,d2,d3......} 问题等价于:从一个袋子里面摸球,期望摸几次才能使pattern符合D中的任意一个。 例如2个白球3个黑球,摸到1个白球或者1个黑球时停止,此问题的答案会小于f(2,3,1,0)和f(2,3,0,1).显然此问题的答案会变成1. 麻将问题应该是一个多目标概率问题。 称此问题为:多目标摸球问题 """ from fractions import Fraction from copy import deepcopy noput_dict = {} def noput(m, n, a, b): """ m个白球,n个黑球,想要摸到a个白球,b个...
d83e883c6595e1e5eb646f96a9f12635b81839c0
shtakai/cd-python
/0502-am/assignment/scoresandgrades.py
789
4.03125
4
def scores_and_grades(): scores = [] for value in range(10): score = raw_input("Input Score {}:".format(value + 1)) scores.append(score) print "Scores and Grades" for score in scores: grade = "" score = int(score) if score >= 60 and score < 70: # print...
753165690888d3364f9a6bb9de23a4e24b148f0f
shtakai/cd-python
/oop/assignment/linkedlist/linkedlist.py
2,725
4.0625
4
class Linkedlist(object): def __init__(self, value): self.value = value self.prev_node = None self.nxt_node = None print 'initialized node', self def insert_last(self, last_node): if last_node: last_node.nxt_node = self self.prev_node = last...
0d7c64b809aaf2495587c01e21f76792733ed566
shtakai/cd-python
/0502-am/list.py
356
3.65625
4
ninjas = ['Rozen', 'KB', 'Oliver'] my_list = ['4' ,['list', 'in', 'a', 'list'], 987] empty_list = [] print ninjas print my_list print empty_list fruits = ['apple', 'banana', 'orange', 'strawberry'] vegetables = ['lettuce', 'cucumber', 'carrots'] fruits_and_vegetables = fruits + vegetables print fruits_and_vegetables...
efbe44be5d1ab0fd9f75f373ed7c7bf1ea2cdda7
tt1998215/pythoncode1
/begin end.py
712
3.671875
4
# import functools # def log(func): # # @functools.wraps(func) # def wrapper(*args,**kw): # print("begin call %s():"%func.__name__) # res=func(*args,**kw) # print("the result of the program is {}".format(res)) # print("end call %s():"%func.__name__) # #resturn res # r...
cdaee67ad742ae35588e82fd5682391750e4f583
tt1998215/pythoncode1
/Mydatetime.py
515
3.515625
4
from datetime import datetime,timezone,timedelta # print(datetime.now()) # utc_dt=datetime.utcnow().replace(tzinfo=timezone.utc) # print(utc_dt) # bj_dt=utc_dt.astimezone(timezone(timedelta(hours=8))) # print(bj_dt) import re def to_timestmap(dt_str,tz_str): input_dt=datetime.strptime(dt_str) time_zone_num=re.m...
22ca752af618837890c074dfe20776c44f40fece
matteblack9/infoRetrieval
/searchEngine5.py
6,636
3.984375
4
""" This file contains an example search engine that will search the inverted index that we build as part of our assignments in units 3 and 5. """ import sys,os,re import math import sqlite3 import time # use simple dictionnary data structures in Python to maintain lists with hash keys docs = {} resultslist...
b24483771fe532d0641a9025558c07fab2559f75
kushaswani/Insight_DE_Challenge
/src/consumer_complaints.py
1,995
3.6875
4
import csv import sys # from read_csv import read_csv # importing read_and_transform_csv function which lets you apply custom functions to rows and get the transformed dataframe as dict of arrays from read_csv import read_and_transform_csv # importing the custom function which we need to apply to get intended results...
c3625fd73193cbcbc96060b39e37b3b9a9104828
Bn-com/myProj_octv
/myset_scripts/ttteeemmm.py
97
3.515625
4
abc = "ABCcdedDD" print(abc.lower()) print(abc.swapcase()) print(abc.title()) print(abc.upper())
ad847ca987ab258b897d0d436a537863b9aeefd5
yangzhaonan18/detect_traffic_light
/kmeans.py
2,705
3.640625
4
# -*- coding=utf-8 -*- # K-means 图像分割 连续图像分割 (充分利用红绿灯的特点) import cv2 import matplotlib.pyplot as plt import numpy as np def seg_kmeans_color(img, k=2): # 变换一下图像通道bgr->rgb,否则很别扭啊 h, w, d = img.shape # (595, 1148, 3) # 0.47 聚类的时间和图像的面积大小成正比,即与图像的点数量成正比。 b, g, r = cv2.split(img) img = cv2.merge([r, g...
84b65a981960d7895747edd6e9090df0f34c71e7
hoylemd/practice
/pattern_matching/pattern_matching.py
837
3.890625
4
import argparse import operator # set up the args parser parser = argparse.ArgumentParser(description='This is a script to find all positions of a substring in a string') parser.add_argument("file", help="The file to operate on") args = parser.parse_args() # open the file and read it f = open(args.file) input_lines =...
78d4b7482374fd8a57c06b76b7474b0a373e1d3d
prakashdivyy/advent-of-code-2019
/01/run.py
566
3.546875
4
import math total_part_1 = 0 total_part_2 = 0 filename = 'input.txt' with open(filename,) as file_object: for line in file_object: # Part 1 x_part_1 = int(line,10) res_part_1 = x_part_1 / 3 total_part_1 += math.floor(res_part_1) - 2 # Part 2 x_part_2 = int(line,10)...
1916ef020df5cb454e7887d2d4bb051d308887e3
sammysun0711/data_structures_fundamental
/week1/tree_height/tree_height.py
2,341
4.15625
4
# python3 import sys import threading # final solution """ Compute height of a given tree Height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a leaf to the root. """ class TreeHeight: def __init__(self, nodes): self.num = len(nodes) self.parent = nodes ...
0723f91d492b9e11767bc6b5a019977ed0f3eb73
kbtony/my-teleprompt
/src/teleprompter/run.py
4,560
3.84375
4
import csv import sys from datetime import datetime from datetime import timedelta from datetime import timezone USAGE = f"usage: python {sys.argv[0]} file_name.csv datetime" class CommandLine: def __init__(self, argv): # More than two cmd arguments if len(argv) > 3: print("error: at m...
61dd1f00de80a02605fdab226828683769b6bf96
araceli24/Ejercicios-Python
/Modificar.py
667
3.5
4
lista = [29, -5, -12, 17, 5, 24, 5, 12, 23, 16, 12, 5, -12, 17] def modificar(l): l = list(set(l)) # Borrar los elementos duplicados (recrea la lista a partir de un nuevo diccionario) l.sort(reverse=True) # Ordenar la lista de mayor a menor for i,n in enumerate(l): # Eliminar todos los números impa...
95ef4825c2a198c3ebabcdb5a26e4328ab4bb4ed
xudalin0609/leet-code
/dynamic/generateTrees.py
887
4.09375
4
""" Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. Example: Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: ...
83176af41a32baa87bf1ce06b002e1d5c82865f4
xudalin0609/leet-code
/BinarySearch/findPeek.py
1,335
3.75
4
#LintCode 75 """ 75. 寻找峰值 中文English 你给出一个整数数组(size为n),其具有以下特点: 相邻位置的数字是不同的 A[0] < A[1] 并且 A[n - 2] > A[n - 1] 假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1],返回数组中任意一个峰值的位置。 样例 样例 1: 输入: [1, 2, 1, 3, 4, 5, 7, 6] 输出: 1 or 6 解释: 返回峰顶元素的下标 样例 2: 输入: [1,2,3,4,1] 输出: 3 挑战 Time complexity O(logN) 注意事项 数组保证至少存在一个峰 如果...
740a31e63edbde67c2add9e33219f5616c5af689
xudalin0609/leet-code
/BFS/sequenceReconstruction.py
2,434
3.828125
4
""" 605. 序列重构 中文English 判断是否序列 org 能唯一地由 seqs重构得出. org是一个由从1到n的正整数排列而成的序列,1<=n<=10^4​ 。 重构表示组合成seqs的一个最短的父序列 (意思是,一个最短的序列使得所有 seqs里的序列都是它的子序列). 判断是否有且仅有一个能从 seqs重构出来的序列,并且这个序列是org。 样例 例1: 输入:org = [1,2,3], seqs = [[1,2],[1,3]] 输出: false 解释: [1,2,3] 并不是唯一可以被重构出的序列,还可以重构出 [1,3,2] 例2: 输入: org = [1,2,3], seqs = [[1,2]]...
8178aa5e0cc682bec6b3935fa7eadf2c1c9bb3fa
xudalin0609/leet-code
/Greedy/canCompleteCircuit.py
1,549
3.5625
4
# LintCode 187 """ 187. 加油站 中文English 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第_i_个加油站前往第_i_+1个加油站需要消耗汽油cost[i]。 你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。 求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。 样例 样例 1: 输入:gas[i]=[1,1,3,1],cost[i]=[2,2,1,1] 输出:2 样例 2: 输入:gas[i]=[1,1,3,1],cost[i]=[2,2,10,1] 输出:-1 挑战 O(n)时间和O(1)额外空间 ...
ae456f697158e53e2a6a806a6344757247fd1e23
xudalin0609/leet-code
/Greedy/canPlaceFlowers.py
1,176
4
4
# 605 """ 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。 示例 1: 输入: flowerbed = [1,0,0,0,1], n = 1 输出: True 示例 2: 输入: flowerbed = [1,0,0,0,1], n = 2 输出: False 注意: 数组内已种好的花不会违反种植规则。 输入的数组长度范围为 [1, 20000]。 n 是非负整...
e3b9ee8b7a645084e7430185c65db3e59d097718
xudalin0609/leet-code
/DFS/wordSearchII.py
2,763
3.84375
4
# LintCode 132 """ 132. 单词搜索 II 中文English 给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。 一个单词可以从矩阵中的任意位置开始,可以向左/右/上/下四个相邻方向移动。一个字母在一个单词中只能被使用一次。且字典中不存在重复单词 样例 样例 1: 输入:["doaf","agai","dcan"],["dog","dad","dgdg","can","again"] 输出:["again","can","dad","dog"] 解释: d o a f a g a i d c a n 矩阵中查找,返回 ["again","can","dad","dog...
014009ae4f7e48fe843dd5dc02104ffbf887fb52
xudalin0609/leet-code
/BFS/numIslands.py
2,072
3.8125
4
# LintCode 433 """ 433. 岛屿的个数 中文English 给一个 01 矩阵,求不同的岛屿的个数。 0 代表海,1 代表岛,如果两个 1 相邻,那么这两个 1 属于同一个岛。我们只考虑上下左右为相邻。 样例 样例 1: 输入: [ [1,1,0,0,0], [0,1,0,0,1], [0,0,0,1,1], [0,0,0,0,0], [0,0,0,0,1] ] 输出: 3 样例 2: 输入: [ [1,1] ] 输出: 1 """ import collections class Solution: """ @param grid: a boolean 2D ...
310be24ce75fad3d656397284eaf5fbbc9f70784
xudalin0609/leet-code
/DivideAndConquer/flatten.py
1,974
4.03125
4
# LintCode 453 """ 453. 将二叉树拆成链表 中文English 将一棵二叉树按照前序遍历拆解成为一个 假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。 样例 样例 1: 输入:{1,2,5,3,4,#,6} 输出:{1,#,2,#,3,#,4,#,5,#,6} 解释: 1 / \ 2 5 / \ \ 3 4 6 1 \ 2 \ 3 \ 4 \ 5 \ 6 样例 2: 输入:{1} 输出:{1} 解释: """ """ Defi...
5e0b1671e4a00faa1c0481ea461ffaa089c30d5e
xudalin0609/leet-code
/DivideAndConquer/findKthLargest.py
1,560
4
4
""" Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤...
6cca45c1943ad0fa138ae0e5dcf331aa54aba5b1
xudalin0609/leet-code
/BFS/searchNode.py
2,303
4.09375
4
""" 618. 搜索图中节点 中文English 给定一张 无向图,一个 节点 以及一个 目标值,返回距离这个节点最近 且 值为目标值的节点,如果不能找到则返回 NULL。 在给出的参数中, 我们用 map 来存节点的值 样例 例1: 输入: {1,2,3,4#2,1,3#3,1,2#4,1,5#5,4} [3,4,5,50,50] 1 50 输出: 4 解释: 2------3 5 \ | | \ | | \ | | \ | | 1 --4 Give a node 1, target is 50 there a hash named values which ...
b4c38e0f4f0446c2bb67bdb844f51ce3263732c7
xudalin0609/leet-code
/DivideAndConquer/closestValue.py
2,799
3.9375
4
# LintCode 900 """ 900. 二叉搜索树中最接近的值 中文English 给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值 样例 样例1 输入: root = {5,4,9,2,#,8,10} and target = 6.124780 输出: 5 解释: 二叉树 {5,4,9,2,#,8,10},表示如下的树结构: 5 / \ 4 9 / / \ 2 8 10 样例2 输入: root = {3,2,4,1} and target = 4.142857 输出: 4 解释: 二叉树 {3,2,4,1},表示...
d49a28a9653203145baf58365b4c7e4861e6b01b
ryan-aday/adayR
/20_cw/app.py
1,675
3.65625
4
from functools import reduce from collections import Counter import itertools import operator def most_common(L): # get an iterable of (item, iterable) pairs SL = sorted((x, i) for i, x in enumerate(L)) # print 'SL:', SL groups = itertools.groupby(SL, key=operator.itemgetter(0)) # auxiliary function to get...
4cc92252d90ac9677998ec3669b3bd7a35bb8d10
alxthedesigner/cloud_application_example
/word_number_app.py
1,368
3.84375
4
from flask import Flask from flask import request application = Flask(__name__) #App Instance created @application.route("/") #When URL ends in '/', execute method def home(): return WORDHTML WORDHTML = """ <html><body> <h2>Word and Number Game</h2> <form action="/game"> E...
c5ac3685195f48a4da04cd71e2ed8202c375ac28
Teghfo/python_workhosp_zemestan98_mapsa
/J6/my_pickle.py
1,021
3.71875
4
import pickle class Book: def read_data(self): self.title = input('Enter Book tile: ') if not self.title: return self.author = input('Enter Author name: ') self.page_count = input('Enter page count: ') self.borrow_history = [] def add_borrow_history(self, u...
853c4b8d92dd31f672cdc1f15cb0deedc852c961
desperadoespoir/TheoriesDesGraphes-LangagesNaturels
/tp2/automate.py
1,655
3.921875
4
class Automate(object): """Une class automate qui permet de lire des solutions on peut y ajouter une regle on peut aussi resoudre avec la fonction solve et un mot de passe """ END = -1 NOT_FOUND = 0 START = "" def __init__(self, name): self.name = name self.regles...
1e26f26d4d308a9a9ac1c8f9975b459b945ce315
Htrams/Leetcode
/binary_search_tree_iterator.py
1,101
4.03125
4
# My Rating = 2 # https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/570/week-2-december-8th-december-14th/3560/ # 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...
b07d3973639dd0b42409027ff1ed2e31aace33cf
Htrams/Leetcode
/matrix_diagonal_sum.py
621
3.9375
4
# My Rating = 1 # https://leetcode.com/contest/biweekly-contest-34/problems/matrix-diagonal-sum/ # Given a square matrix mat, return the sum of the matrix diagonals. # Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagon...
f02f36b8bab69dcaef3240ae84600a3092f720ae
Htrams/Leetcode
/flipping_an_image.py
854
3.875
4
# My Rating = 1 # https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3526/ # Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. # To flip an image horizontally means that each row of the image is ...
6ab534dbbc70e049b062fd0f93c43f578531e8fa
Htrams/Leetcode
/psuedo-palindromic_paths_in_a_binary_tree.py
1,489
3.859375
4
# My Rating = 1 # https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/573/week-5-december-29th-december-31st/3585/ # Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic # if at least one permutation of the node values in the pa...
d7b224fc94c116eb466349f05f2657f0cd0fc27a
Htrams/Leetcode
/reverse_string.py
308
3.5
4
# My Rating = 1 class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ length=len(s) for i in range(length//2): temp=s[i] s[i]=s[length-i-1] s[length-i-1]=temp
7bb08a8b4b5963ff4fdf46f7a62e30959e74aac0
Htrams/Leetcode
/swapping_nodes_in_a_linked_list.py
1,676
3.71875
4
# My Rating = 2 # https://leetcode.com/contest/weekly-contest-223/problems/swapping-nodes-in-a-linked-list/ # The following code interchanges the nodes, instead of the values in the node. # You are given the head of a linked list, and an integer k. # Return the head of the linked list after swapping the values # of t...
c14defaa309c4ab8868ae7c756bd89aeeb5bf678
grsind19/Pythondeveloper
/2. Learning Python/11. Fileaccess.py
256
3.53125
4
def main(): # f = open('textfile.txt','w+') # for i in range(10): # f.write("this is line "+str(i) + "\r\n") g = open('textfile.txt','r') if g.mode == 'r': contents = g.read() print(contents) if __name__ == "__main__": main()
3ef54f4dcf0751f1bc2d4be3bc387910c2e0330d
grsind19/Pythondeveloper
/1. Programmingfoundationsandalsogithms/10. Quicksort.py
840
3.734375
4
items=[6, 20, 8, 19, 56, 23, 87, 41, 49, 53] def quickSort(dataset, first, last): if first < last: pivotrIdx = partition(dataset, first, last) quickSort(dataset, first, pivotrIdx-1) quickSort(dataset, pivotrIdx+1, last) def partition(dataset, first, last): pivotValue = dataset[first] lower = first...
fb2e544ffcccaacad953cfcba321bf757af6ecef
grsind19/Pythondeveloper
/5. PythonstandardLib/8. Type.py
167
3.5625
4
# type # Instance class Car: pass class Truck(Car): pass c = Car() t = Truck() print(type(c)) print(type(t)) print(isinstance(c,Car)) print(isinstance(t,Car))
683673bcb322193b98900c5dd93ec07b14f5eb8a
tron135/python_practise
/even odd.py
137
4.21875
4
number = int(input('Enter any number: ')) if(number%2 == 0): print('The Number is even.') else: print('The Number is odd.')
c5d87c6d8317f501cb862fb0a8bc30b16868e759
tron135/python_practise
/unlucky number.py
202
3.875
4
for i in range(1,21): if i == 4 or i == 13: s = str(i) + " is unlucky !!!!" print(s) elif i % 2 == 0: t = str(i) + " is even !!" print(t) else: u = str(i) + " is odd !!" print(u)
adc39c22e430ce632ebcb644797ef2addd9f8553
hyunlove12/20191005
/dlearn/digits/__init__.py
1,242
3.671875
4
import matplotlib.pyplot as plt from digits.hand_writing import HandWriting if __name__ == '__main__': def print_menu(): test = ['asdfsadf', 'asdgsad', 'asdf'] print(test) #print(test[:3, 1]) t = [2 == 2] print(t) print('0, EXIT') print('1, 손글씨 인식') pr...
7a75cd6d39e5329b1226ddf851478f341cc163bc
m-hollow/deeper_dungeons
/old_files (archive)/main.py
45,747
3.671875
4
import time from random import randint from random import choice import copy # define game objects class GameSettings(): """Define game settings""" def __init__(self): self.grid_size = 5 self.starting_gold = 10 self.difficulty = 1 def user_settings_change(self): msg = 'Choose the size of the dungeon gri...
810cdf77367004f7764c0de8e6af34d7253011fd
m-hollow/deeper_dungeons
/old_files (archive)/determine_event.py
1,074
3.53125
4
from random import randint from random import choice import time def determine_event(current_room): """look at current room type and determine event that results""" if current_room == 'Empty': pass if current_room == 'Monster': monster_event(settings, player) if current_room == 'Treasure': treasure_event(pl...
3f40d22f79ba711e9ff154e109338d58804f2256
m-hollow/deeper_dungeons
/old_files (archive)/dungeon_more_old/ui_functions.py
3,901
3.765625
4
import time from random import randint, choice import copy # define game UI functions. def you_are_dead(player, text=''): if text: print(text) print('YOU', end='', flush=True) time.sleep(0.5) print('\tARE', end='', flush=True) time.sleep(0.5) print('\tDEAD.', end='', flush=True) print('So passes {} the {} ...
b1080291935da258c1711e9980f70ab10dbe28cc
m-hollow/deeper_dungeons
/old_files (archive)/encounter_work.py
1,846
3.90625
4
from random import randint from random import choice import time def user_input(): msg = '> ' choice = input(msg) return choice def press_enter(): msg = '...' input(msg) def run_attempt(): escape_num = 10 # this will be determined by mosnster difficulty in actual game print('Press enter to roll your Run ...
566276fb5aa5e56e446404520131bff5b19a6a91
arumsey93/py-class
/pizzajoin.py
624
3.640625
4
class Pizza: def __init__(self): self.size = 0 self.style = "" self.new_topping = [] def add_topping(self, topping): self.new_topping.append(topping) def print_order(self): space = " and " new_string = f"I would like a {self.size}-inch, {self.style} pizza" ...
e442af8261e751871962eaedc86d8afc61156284
irina-baeva/algorithms-with-python
/algorithms/big-o-complexity/constant_linear-complexity.py
507
3.96875
4
# Constant complexity example # O(1) - the same time no matter how much input def sum(a, b, c): return a + b + c print(sum(3,2,1)) # takes the same time as: print(sum(1000,300,111)) # Linear complexity example # O(n) - grows with the input 1:1 foodArray = ['pizza', 'burger', 'sushi', 'curry'] def findFoodInThe...
7cafa9fc6b348af6d2f11ad8771c5cca59b1bea7
irina-baeva/algorithms-with-python
/data-structure/stack.py
1,702
4.15625
4
'''Imlementing stack based on linked list''' class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head ...
12e37d46b3b3b1dbcac643020f6faa1c28202d70
amitesh1201/Python_30Days
/day1_ex03.py
193
4.28125
4
# Calculate and print the area of a circle with a radius of 5 units. You can be as accurate as you like with the value of pi. pi = 3.14 radius = 5 area = pi * radius ** 2 print("Area: ", area)
c022ad739dbd4634b682b04f4036a18014b6283f
amitesh1201/Python_30Days
/OldPrgms/Day4_Ex2.py
437
3.921875
4
# 2. Use the input function to gather information about another movie. You need a title, director’s name, release year, and budget. movies = [ ("The Room", "Tommy Wiseau", "2003", "$6,000,000") ] title = input("Title: ") director = input("Director: ") year = input("Year of release: ") budget = input("Budget: ") # m...
358227b3759aa81b96ea6b1e4be87e066be878ee
amitesh1201/Python_30Days
/day2_ex01.py
184
4.21875
4
# Ask the user for their name and age, assign theses values to two variables, and then print them. name = input("Enter your name: ") age = input("Enter your age: ") print(name, age)
01ece2001beaf028b52be310a8f1df24858f4e59
amitesh1201/Python_30Days
/OldPrgms/Day3_prc05.py
579
4.375
4
# Basic String Processing : four important options: lower, upper, capitalize, and title. # In order to use these methods, we just need to use the dot notation again, just like with format. print("Hello, World!".lower()) # "hello, world!" print("Hello, World!".upper()) # "HELLO, WORLD!" print("...
36ab5e0899e94be5d9ad720ace9341e4866a541c
amitesh1201/Python_30Days
/OldPrgms/Day4_Ex6.py
374
3.890625
4
# 6) Print both movies in the movies collection. movies = [ ("The Room", "Tommy Wiseau", "2003", "$6,000,000") ] title = input("Title: ") director = input("Director: ") year = input("Year of release: ") budget = input("Budget: ") new_movie = title, director, year, budget print(f"{new_movie[0]} ({new_movie[2]})") m...
f138eb288de47bb1d2262157d93e1802f0e1252e
bolyb/CS361
/down_up.py
744
3.765625
4
class therapist: name = "" rank = "" __init__(self, set_name): name = set_name rank = 0 #Discription: #the votetally function is the crux of the task, the rest is used to showcase what the functionality is supposed to do. #This function takes in a user vote and a therapist to be voted on and manipulates the ...
6b17d9aa0fb29c58334ed4cf199d972a62706301
Atabuzzaman/AI-code-with-Python
/waterJug.py
432
3.671875
4
def pour(jug1, jug2): print(jug1,'\t', jug2) if jug2 is 2: return elif jug2 is 4: pour(0, jug1) elif jug1 != 0 and jug2 is 0: pour(0, jug1) elif jug1 is 2: pour(jug1, 0) elif jug1 < 3: pour(3, jug2) elif jug1 < (4 - jug2): pour(0, ...
980610302335d57bf25946c94f4bd2c7cc0eb97f
skidmarker/bugatti
/hash/42578.py
264
3.515625
4
def solution(clothes): answer = 1 c_dict = {} for c, type in clothes: if type in c_dict: c_dict[type] += 1 else: c_dict[type] = 1 for cnt in c_dict.values(): answer *= cnt + 1 return answer - 1
2417d550b5488eaec6800336beda0cbd8748a747
nataliaruzhytska/Password-generator
/src/app/api_pass/utils.py
2,597
3.59375
4
import random import string from flask import jsonify def random_chars(n=12, uppercase=False, symbol=False, digit=False): """ The function generates a random password using user-defined parameters and evaluates its difficulty :param n: str :param uppercase: bool :param symbol: bool :param...
f6c183fb7de25707619a330224cdfa841a8b44be
maryliateixeira/pyModulo01
/desafio005.py
229
4.15625
4
# Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e antecessor n= int(input('Digite um número:')) print('Analisando o número {}, o seu antecessor é {} e o sucessor {}' .format(n, (n-1), (n+1)))
13307a93bfccb71f40106daf37b2851a994ff070
maryliateixeira/pyModulo01
/desafio011.py
534
4.09375
4
#faça um programa que leia a altura e a largura de uma parede em metros, calcule sua area e a quantidade de tinta # necessária para pintá-la, sabendo que cada litro de tinha, pinta uma area de 2 metros quadrados larg= float(input('Digite a largura da parede em metros:')) alt = float(input('Digite a altura da parede em ...
47ba0dd3e658857ff57767aa6b70bba17abce29e
ssiddoway/IT567
/port.py
5,137
3.609375
4
#!/usr/bin/python import sys, argparse, socket def main(): parser = argparse.ArgumentParser() parser.add_argument("-i","--input", help="Input file") parser.add_argument("-t", help="TCP port sccaner range, i.e. -t 1-1024") parser.add_argument("-u", help="UDP port scanner range, i.e. -u 1-1024") par...
067bba31d0f51150264914637f39224fe6d0cecd
renol767/python_Dasar
/DQLab/Kelas Persiapan/chartnamakelurahan.py
589
3.640625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt table = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/penduduk_gender_head.csv") table.head() x_label = table['NAMA KELURAHAN'] plt.bar(x=np.arange(len(x_label)), height=table['LAKI-LAKI WNI']) #Memberikan nilai axis dari data CSV plt.x...
f52d016e2684b8d6cfceb2366bd27331b4ddd71b
renol767/python_Dasar
/Latihan Python Dasar/35.3 Latihan Mengecek Suatu Password.py
360
3.625
4
def userx(): user = input("Masukan Username : ") if user == 'admin': print("Lanjut Gan, Masukin Passwordnya") pw = input("Masukan Password : ") if pw == 'admin': print("Login Sukses !") else: print("Password salah!") else: print("Salah Coy User...
2d7bfd605e1105eb79716bb0b93357760887bd4a
renol767/python_Dasar
/Latihan Python Dasar/Tutorialsebelumpackage/11 Return and Lambda.py
489
3.6875
4
# return a = 8 def kuadrat (a): total = a**2 print("Kuadrat dari",a,"adalah",total) return total a = kuadrat(a) print (a) print (50*'-') # return multiple argument def tambah (a,b): total = a+b print(a, "+" , b , '=', total) return total def kali (a,b): total = a*b print(a, "x" , b , "="...
047ca459460989c8c06d76cf16c341cee0e838a4
renol767/python_Dasar
/Latihan Python Dasar/35.4 Latihan Deret Fibonaci.py
154
3.953125
4
suku = int(input('Masukan Suku Ke Berapa : ')) a = 0 b = 1 c = 3 print(a) print(b) while c <= suku: c = a+b a = b b = c print(c) c+=1
3e3618fc47c05008bf92518dcd953d350c265918
avsingh999/rl-tictactoe
/tictactoe.py
10,944
4.0625
4
""" Reference implementation of the Tic-Tac-Toe value function learning agent described in Chapter 1 of "Reinforcement Learning: An Introduction" by Sutton and Barto. The agent contains a lookup table that maps states to values, where initial values are 1 for a win, 0 for a draw or loss, and 0.5 otherwise. At every mov...
a3fb45777567b8e29bb0b31fb734bcd1dc8579ca
mikeyhu/project-euler-python
/test/test_Problem1.py
374
3.8125
4
import unittest from main import Problem1 class TestProblem1(unittest.TestCase): def test_sum_of_natural_numbers_below_10_that_are_multiples_of_3_or_5(self): p1 = Problem1.Problem1() self.assertEqual(23,p1.solve(10)) def test_sum_of_natural_numbers_below_1000_that_are_multiples_of_3_or_5(self): p1 = Problem1...
f003866db45687ef25b32772941b73413ae552cf
mikeyhu/project-euler-python
/main/Problem5.py
447
3.5
4
import itertools class Problem5(object): def solve(self,number): uniqueProducts = self.products(number) for x in itertools.count(1): valid = True for i in uniqueProducts: if not x % i == 0: valid = False if valid: return x def products(self,number): result = [] for i in range(number,...
8d19c27a48eef36d5924f38be89fee9a362d95bc
igorbustinza/theegg_ai
/tarea23/tarea23.py
7,606
3.703125
4
##Tarea 23 import random ##funciones ##función que cifra y descifra el texto def cifra_descifra(cifraTextoDescifra,listaCartasFuncion,operacion): #creamos un diccionario con las letras y su correpondiente valor valoresLetras = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14...
b9151241f8234f5c1f038c733a5d0ff46da376d3
louishuynh/patterns
/observer/observer3.py
2,260
4.15625
4
""" Source: https://www.youtube.com/watch?v=87MNuBgeg34 We can have observable that can notify one group of subscribers for one kind of situation. Notify a different group of subscribers for different kind of situation. We can have the same subscribers in both groups. We call these situations events (different kinds o...
bb1e695e901d9f80fd97ac45ad64891229f2d79c
timmichanga13/python
/fundamentals/fundamentals/demos/data_types.py
1,411
4.03125
4
# many of the same types; booleans, values, strings # python interpreter is an environment where the computer can immediately implement code # use for testing/remembering if something works # booleans start with capital T and F #values are split between integers and floats # floats are imperfect representations # s...