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
9516c757ff8eacaff3edb929e59fc7032610f4f1
QuinPoley/ChessGame
/pieces.py
8,000
3.703125
4
class Piece: def __init__(self, color, letter, number): self.position = letter, number self.letter = letter self.number = number self.color = color self.hasMoved = False def returnLegalMoves(): return None def move(self, letter, number): firstmov...
8e03751fb6c7e483d09dec12e3606bef9a443189
jtbarker/pyocto-wordcounter
/countwordfreq.py
690
4.0625
4
#! /usr/bin/python """ this program breaks a string into a list of component words and counts each word, by Jon Barker, 2014-1-7""" # import matplotlib # import os # print(dir(matplotlib)) def main(): print "input a sentence and i will count the words for you" sentence = str(input("your sentence: ")) main() ...
d052bdd3529c7c444cbec14bc1fe3ce1ae5b6093
shaikafiya/pythonprogramming
/pangram.py
141
3.734375
4
s=input() n=[] for i in s: if(i not in n): n.append(i) if(len(n)==27 or len(n)==28): print("yes") else: print("no")
88f49fdde71ecb4ffcdbe49a889e058190d0feb9
shaikafiya/pythonprogramming
/even num between two intervals.py
101
3.515625
4
n,m=input().split() n=int(n) m=int(m) for k in range(n+1,m): if(k%2==0): print(k,end=" ")
359d0387e3684f13ae34726654419d169fb22efb
frankc95/exercise
/workbook_01.py
140
3.796875
4
weight_lbs = input('Weight (lbs): ') weight_kg = int(weight_lbs) * 0.45 txt = "your weight in kilograms is " print (txt + str(weight_kg))
0194f671da5971a2f30a4df885e6318312f6c172
jeremysinger/python-forloop-parser
/tests/test3.py
277
4
4
for i in range(0,10): for j in range(0,i): for k in range(i,j): print(i,j) for a in range(5): for b in range(2): print('foo') for x in range(a): for y in range(a-1): for z in range(y): print('bar')
f9b68289368ca68d3bc557f7e11261c9d8683c79
mikyqwe/python.py
/firstday.py
483
4.09375
4
"""Write a script that writes the day of the week for the New Year Day, for the last x years (x is given as argument).""" import time saptamana=["Luni","Marti","Miercuri","Joi","Vineri","Sambata","Duminica"] def f(x): date="01-01" for i in range(1,x+1): currentYear=2020+1-i currentdate=date+"-"+str(currentYear) ...
057a72a1e97177d2266389973837f9edf8b67806
deepalikushwaha18/SDET-Training-Python
/Activity2.py
160
4.1875
4
num=int(input("enter number:")) mod = num % 2 if mod > 0: print("You picked an odd number.") else: print("You picked an even number.")
5945cce076d47a3dc3f23ed6dad61a3153ae4721
MarcPartensky/Python-Games
/Game Structure/geometry/version4/myrect.py
7,466
4
4
class Rect: """Define a pure and simple rectangle.""" def createFromCorners(corners): """Create a rectangle.""" coordonnates=Rect.getCoordonnatesFromCorners(corners) #print("c:",coordonnates) return Rect(coordonnates[:2],coordonnates[2:]) def createFromRect(rect): ""...
e9432b4362be20638c2d72af1fb3a37f3e67c889
MarcPartensky/Python-Games
/Game Structure/geometry/version5/mysyracuse.py
1,528
3.53125
4
from myabstract import Point,Segment class Branch: def __init__(self,n=1,g=0): """Create a branch.""" self.n=n self.g=g def children(self): """Return the childen branches of the branch.""" children=[Branch(self.n*2,self.g+1)] a=(self.n-1)//3 if a%2==1: ...
4a25f75e797b7ca5915b7c8689482a6f329a8af1
MarcPartensky/Python-Games
/Game Structure/geometry/version3/mypoint.py
6,376
4.09375
4
from math import pi,sqrt,atan,cos,sin import random mean=lambda x:sum(x)/len(x) import mycolors class Point: def random(min=-1,max=1,radius=0.1,fill=False,color=mycolors.WHITE): """Create a random point using optional minimum and maximum.""" x=random.uniform(min,max) y=random.uniform(min,m...
7c3ba27c237a61201655c18fd2520838b5215778
MarcPartensky/Python-Games
/Mandelbrot/mandelbrot1.py
1,621
3.640625
4
import numpy as np from matplotlib import pyplot as plt from matplotlib import colors #%matplotlib inline settings=[-2.0,0.5,-1.25,1.25,3,3,80] def mandelbrot(z,maxiter): c = z for n in range(maxiter): if abs(z) > 2: return n z = z*z + c return maxiter def mandelbrot_set(xmin,...
237174569b314b5ad7b2df0f9d0cc2bc80a5a3f2
MarcPartensky/Python-Games
/Game Structure/geometry/version3/myvector.py
8,935
3.71875
4
from mydirection import Direction from mypoint import Point from math import cos,sin from cmath import polar import mycolors import random class Vector: def random(min=-1,max=1,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]): """Create a random vector using optional min and max.""" x=random.uniform...
e4f909f0ecdf3f3529efe9de530ab31df9e4c1ed
MarcPartensky/Python-Games
/Game Structure/geometry/version4/myabstract.py
74,221
3.9375
4
from math import pi,sqrt,atan,cos,sin from cmath import polar from mytools import timer import math import random import mycolors average=mean=lambda x:sum(x)/len(x) digits=2 #Number of digits of precision of the objects when displayed class Point: """Representation of a point that can be displayed on screen.""...
2114723258f1a9a8d3b0281676020098d7629943
MarcPartensky/Python-Games
/Game Structure/geometry/version5/modulo.py
1,888
3.6875
4
import math class Modulo: def __init__(self, n, a=None): """'n' is the number, and 'a' is the modulo""" if a == None: self.a = float("inf") else: self.a = a self.n = n % self.a # Type conversions def __str__(self): return str(self.n) de...
5d304023128714c95e67ec1ed77c8d4f1b3f33a9
MarcPartensky/Python-Games
/Intersection/myposition.py
2,382
3.546875
4
from math import sqrt,cos,sin from cmath import polar from numpy import array,dot class Position: base="xyztabcdefhijklmnopqrsuvw" angle_base="ab" def __init__(self,*data,base=None,system="cartesian"): """Save a position using cartesian coordonnates.""" self.system=system if self.s...
6a5961313d688e4136885a19f2cd33e6592ff4cd
LanHikari22/Mutu-chan
/Commands/botcmd.py
3,002
3.765625
4
class BotCMD: """ abstraction class of a bot command. Create this for every command except very fundemental ones Override methods as necessary. """ # execution activation command for when listening for mention commands command = None # defined error_code constants SUCCESS = 0 ...
58529d86ce20df905e85e7641408699ba48a0aa2
YpchenLove/py-example
/8-list.py
416
3.765625
4
# l = [1, 2, 3, 4, 5] # print(l[0]) # print(l[1: 2]) # print(l[-2: -1]) # print(l[:]) # print(l[0:5:2]) l = [1, 2, 1, 1, 3, 4, 5, -1] l2 = [7, 8, 9] print(l[-1:]) # [5] print(l[-1::-1]) # [5, 4, 3, 2, 1] print(len(l)) print(max(l)) print(min(l)) print(l.count(1)) l.append(88) print(l) l.pop() print(l) l.rem...
a4682975b00b3a87be7e293ae844bd921e3d4db7
zjipsen/chef-scheduler
/chef.py
652
3.6875
4
class Chef: days_in_week = 5 def __init__(self, name, unavailable=[], since=6, times=0, vacation=False): self.name = name self.unavailable = unavailable self.since = since self.times = times self.init_since = since self.init_times = times self.vacation =...
6e9541ca3a2030a5fdcbd1f28d4937afe60ae03e
MeitarEitan/Devops0803
/1.py
449
3.671875
4
my_first_name = "Meitar" age = 23 is_male = False hobbies = ["Ski", "Guitar", "DevOps"] eyes = ("brown", "blue", "green") # cant change (tuple) # myself = ["aviel", "buskila", 30, "identig"] myself = {"first_name": my_first_name, "last_name": "Eitan", "age": age} # dictionary print("Hello World!") print(my_first_name...
ee0ca87dc7393247fc507193b6ef22c4c97c1293
MeitarEitan/Devops0803
/9.py
343
3.796875
4
def saveNames(): inputUser = input("Enter your name:") myNewFile = open("names.txt", "a") myNewFile.write(inputUser + "\n") myNewFile.close() def printNames(): file = open("names.txt", "r") for name in file.readlines(): print(name, end=" ") file.close() saveNames() saveNames() sa...
17c0945cae7677615b0f2b181b12505ebfadb0fd
varunpsr/python-ds
/binary-search-tree.py
2,061
4.0625
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): if self is not None: return f"{self.value}" else: return "None" class BinarySearchTree: def __init__(self): ...
6e49ad323b536ee1e669d1ce643959b66da67823
python-fisika-uin/Fundamental
/fundamental001.py
1,367
3.8125
4
# Sintaks Sekuensial print('Hello World!') nama = 'Eko S.W' usia = 40 Usia = 50 #ini berbeda dengan usia (huruf kecil) print(nama, 'Usia=', usia) # Sintaks bercabang if usia <= 40: print('Masih muda') print('Usia belajar') print('Usia mencari jatidiri') else: print('Tak muda lagi') print('Banyakin tobat') ...
bc8744b8265be788f974f5bd0a5c9b24f26da35d
xinzheshen/py3-practice
/src/cookbook/09_yuanbiancheng/decoretor0.py
735
3.546875
4
import time from functools import wraps def timethis(func): ''' Decorator that reports the execution time. ''' # 注意加不加@wraps的区别 @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, en...
03175236c641b680cf7e47e78e13c6f3bece9a72
Aptegit/Assignment1
/new_testcode.py
751
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: obill =float(input('How much is your original bill? ')) #input string # In[2]: print(type(obill)) #to check the data type of variable # In[3]: tip = int(input('What percentage is your tip?')) #input string # In[4]: print(type(tip)) #to check the data typ...
f7202c99351112f2da3783118059f6d02c040d1d
jameswong95/ICT1008
/block_stack.py
1,341
3.890625
4
class Stack: top = -1 def __init__(self): self.top = -1 # this stack is implemented with Python list (array) self.data = [] def size(self): return len(self.data) def push(self, value): # increment the size of data using append() self.data.append(value)...
8e803130fffcc7f8139e4125c2e1fa451becba71
binjun/LeetCode
/longestpalindromicsubstring.py
1,196
4.0625
4
# -*- coding: utf-8 -*- """ Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example2: Input: "cbbd" Output: "bb" """ import unittest class Solution(object): def longestPa...
2512fbd72639a9c9d35adad3ddbb2c4e9b032ace
shivam-72/simple-python
/PYTHON FUN/lovecalculator.py
798
3.890625
4
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") name1.lower() name2.lower() name3 = name1+name2 T = name3.count("t") R = name3.count("r") U = name3.count("u") E = name3.count("e") total = str(T+R+U+E) L = name3.count("l") O = name3.coun...
e547651f91838d65f910be328522ef1e196652a4
salemmp/memorize-words
/words.py
1,626
3.71875
4
import os import sys import time lista = {"hello":"hola", "word":"palabra", "phone":"celular", "hand":"mano", "how":"como", "people":"gente", "leave":"salir", "key":"tecla", "understand":"entender", "can":"poder", "we...
a383e4a8701f7c9ab85f7295dc309bb4609902f9
lianhuo-yiyu/python-study
/study9 str/main.py
464
4.09375
4
#str的驻留机制 指相同的字符串只会占据一个内存空间,一个字符串只被创建一次,之后新的变量是获得之前的字符串的地址 a = 'python' b = "python" c = """python""" print(id(a)) print(id(b)) print(id(c)) s1 = '' s2 = '' print(s1 == s2) print(s1 is s2) print(id(s1)) print(id(s2)) #理论上有特殊字符串不驻留,下面这个cmd不驻留,pycharm进行了优化 z1 = 'a%' z2 = 'a%' print(id(z1)) print(id(z2))
94c2379bf1ab91f31e7fcb57dee06b37b00d3a14
lianhuo-yiyu/python-study
/study6 dict/main.py
824
4.09375
4
#字典 { } 可变序列 dict 以键值对的方式存储数据 {name : hhh}:前面的叫键,:后面的叫值 字典是无序的序列 字典存储是key时经过hash计算 #字典的键key不允许重复,只有值可以重复,后面的键值会覆盖相同的键名 列表可以按照自己的想法找地方插入元素,dict不行,它是无序的 字典空间换时间,内存浪费大 zidian = {'name' : 'python' , "nianling" : 24} print(zidian) c = dict(name = 'python', nian = 100) print(type(c)) print(c) #字典中的值获取 print...
1f5f1540137ef46b49d62027955fa15f46dc14e1
lianhuo-yiyu/python-study
/STUDY10 函数/递归函数.py
393
3.875
4
# Python 学习 1 # 2020/11/28 17:12 #递归函数 一个函数调用自己 #递归用来计算阶乘 def fac(n): if n ==1: return 1 else: return n *fac(n - 1) print(fac(6)) def text(n): for i in range(1,n): if i == 1 : print('1') elif i == 2 : print('1','1') elif i != 1 and i !=2 : pr...
5cd01bde10307074f0c003b09c034b799fb36965
lianhuo-yiyu/python-study
/STUDY10 函数/main.py
1,775
4.0625
4
#函数的原理与利用 #函数的创建 #def 函数名([输入参数]): # 函数体 # [return xxx] def cale(a,b): # c = a + b c = a - b return c result = cale(10,20) print(result) #函数调用时的参数传递 创建的时候函数括号里面是def hhh(形参,形参), 在函数的调用处,括号里面的是实参,实际参数 形参和实参的名字可以不相同 #参数的传递(实参的值传给形参) #1 位置实参 如上例,按存放的第一个第二个位置传递 #2 关键字传参,就是将形参自行按需求赋值 result2 = cal...
ea03689b8be9bd5fab6af7d4e20d2ceae0d8e88b
reesporte/euler
/3/p3.py
534
4.125
4
""" project euler problem 3 """ def is_prime(num): if num == 1: return False i = 2 while i*i <= num: if num % i == 0: return False i += 1 return True def get_largest_prime_factor(num): largest = 0 i = 2 while i*i <= num: if num%i == 0: ...
8063a87ba1e389e833699bfdc6378698ae8490a7
reesporte/euler
/19/p_19.py
1,608
4.03125
4
""" project euler problem 19 """ def is_leap_year(year): if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): return True return False def get_days_in_month(month, year): months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month == 2 and is_leap_year(year): return 29 ...
567820cdb4e2c97509d232fe441e2f9b6a58a34b
jayden-nguyen/Homework2--NguyenQuangHuy
/homework4/serious2.py
1,364
3.9375
4
prices = {"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3} li = prices.keys() purchased = { "banana": 5, "orange":3 } print("YOU BOUGHT 5 BANANAS AND 3 ORANGES") choice = "yes" while choice.lower() != "no": choice = input("Do you want more(yes or no, press no...
d0131c5e298483388d06683c5f60046a570ba2eb
ErickHernandez/ProyectoCompiladores
/pyfiles/gcd.py
290
4.09375
4
# Program to compute the GCD # Funcion que calcula el maximo comun divisor def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) x = input("Introduzca un numero: ") y = input("Introduzca otro numero: ") z = gcd(x, y) print "El maximo comun divisor es ", z
ed5d3fc73cc8479689a580b926346d098d467c71
sajjanparida/DS-Algorithms
/Sorting/tripletwithlessthansum.py
406
3.90625
4
# program to find the count of triplets with sum less than given number def triplets_sum(arr,n,req_sum): c=0 arr.sort() for k in range(0,n-2): i=k+1 j=n-1 while i<j: if arr[k] + arr[i] + arr[j] < req_sum: c += j-i i += 1 else...
2fc28c8c55ff62b44ecf16f3094d41dee4c3a012
sajjanparida/DS-Algorithms
/LinkedList/Introduction.py
428
3.953125
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def printList(self): temp=self.head while(temp): print(temp.data) temp = temp.next llist = LinkedList() first=Node(...
c050dc01202dce89bf26ea6f125d3410d2177a50
sajjanparida/DS-Algorithms
/Sorting/subarraysumcount.py
390
3.6875
4
def countOfSubarray(arr,n): i=-1 count=0 sum=0 freq={} freq[sum]=1 while i < n-1: i +=1 sum += arr[i] if freq.get(sum) != None: count += freq[sum] freq[sum]=freq[sum]+1 else: freq[sum]=1 return count arr=[0,0,5,5,0,0] pr...
2529bc8fce8c1186cf9325d6ef1479f22adb9e1f
sajjanparida/DS-Algorithms
/Sorting/productarraypuzzle.py
622
3.703125
4
def productExceptSelf(nums, n): #code here zeroflag=0 product=1 if n==1: return 1 for i in range(0,n): if nums[i]!= 0 : product *= nums[i] else: zeroflag += 1 if zeroflag==1: for i in range(0,n): if nums[i]==0: ...
f6063a11518b1fcc2bc653ed3f505dddc9ad4dbf
sajjanparida/DS-Algorithms
/Arrays/Three_way_partition.py
925
4.09375
4
# Given an array of size n and a range [a, b]. The task is to partition the array around the range such that array is divided into three parts. # 1) All elements smaller than a come first. # 2) All elements in range a to b come next. # 3) All elements greater than b appear in the end. # The individual elements of three...
bbeb124cd35e865c17ae7a9691022031b81ba553
jonahtjandra/sudoku-solver
/Sudoku.py
2,939
4.15625
4
class Sudoku: def __init__(self, board:'list[list]') -> None: if (len(board) != 9 or len(board[0]) != 9): raise "Expected a 9 by 9 board" self.board = board self.iterations = [] # for printing out the 2d list representation of the board def display(self, board:'list[list]'): ...
18d4f634488453133535b594fdff3fb8d851f6af
Yokohama-Miyazawa/uec_django
/presen/veiw_tetris.py
3,312
3.734375
4
import tkinter as tk from random import choice class Game(): WIDTH = 300 HEIGHT = 500 def start(self): self.speed = 150 self.new_game = True self.root = tk.Tk() self.root.title("Tetris") self.canvas = tk.Canvas( self.root, width=Game.WIDTH...
4e3ae8718dd37281e9b8dbf85d2df92c555efd48
50417/phd
/learn/challenges/020-highest-product.py
953
3.5
4
#!/usr/bin/env python3 from collections import deque from typing import List def approach1(lst: List[int]) -> int: if not isinstance(lst, list): raise TypeError if len(lst) < 3: raise ValueError if any(x is None for x in lst): raise TypeError best = deque(sorted(lst[:3])) for x in lst[3:]: ...
54d2e882b8d9a188ffdef473ad3e6372c1d3f0fd
50417/phd
/learn/challenges/018-list-binary-tree.py
2,489
3.8125
4
#!/usr/bin/env python3 from collections import deque from typing import List class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None def __lt__(self, rhs: "Node"): return self.data < rhs.data def __eq__(self, rhs: "Node"): return self.data == rhs....
b490ccfe7a99436aa96f5e9ad6d04c83caaba021
YinglunYin/MachineLearning-CS6140
/2-Linear&RidgeRegression/src/problem2.py
4,487
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 14 12:32:58 2018 CS6140 Assignment2 Gradient Descent Problem2 @author: Garrett """ from sklearn import linear_model import math import numpy as np import pandas as pd import matplotlib.pyplot as plt # reader def dataset_reader(file): return n...
fd289fe5c232aa58735368aff954409d808adf02
Black-Eagle-1/driving
/driving.py
248
3.84375
4
country = input('你所在的國家: ') age = input('你的年齡: ') age = int(age) if country == '美國' and age >= 16: print('你可以開車') elif country == '台灣' and age >= 18: print('你可以開車') else: print('你不能開車')
11ec0890ed9eb2c6540f1c8c34eb778c8302fd46
wxmsummer/algorithm
/leetcode/hot/605_canPlaceFlowers.py
851
4.0625
4
# 605.种花问题 from typing import List class Solution: # 模拟法,如果该位置、该位置的前一个位置、该位置的后一个位置没种,就种上 def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: length = len(flowerbed) count = 0 for i in range(length): # 注意数组越界 if flowerbed[i] == 1 or (i > 0 and flower...
87f761c182e6d122e69d9d5d9c44d896fd729655
wxmsummer/algorithm
/leetcode/offer/offer14_cuttingRope.py
759
3.90625
4
# 剪绳子 import math # 数学证明 # 任何大于1的数都可由2和3相加组成 # 当n>=5时,将它剪成2或3的绳子段,2(n-2) > n,3(n-3) > n,都大于他未拆分前的情况, # 当n>=5时,3(n-3) >= 2(n-2),所以我们尽可能地多剪3的绳子段 # 当绳子长度被剪到只剩4时,2 * 2 = 4 > 1 * 3,所以没必要继续剪 class Solution: def cuttingRope(self, n: int) -> int: if n <= 3: return n - 1 a = n // 3 b ...
23b9938f61e413a65cee12d5501680271b7d622a
wxmsummer/algorithm
/leetcode/hot/222_countNodes.py
1,281
3.6875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 层序遍历,暴力法 def countNodes(self, root: TreeNode) -> int: if not root: return 0 stack = [root] coun...
eeeace6a1d48324c28845d51b89535f2527a72e2
wxmsummer/algorithm
/leetcode/hot/77_combine.py
742
3.75
4
# 组合 class Solution: def combine(self, n: int, k: int) -> list: # 回溯法,idx为当前元素,cur为当前解 def backtrack(idx, cur): # 如果当前解符合要求,就加入解集 if len(cur) == k: res.append(cur[:]) # 遍历当前位置后面的元素 for i in range(idx, n+1): print('cur:'...
8c80e03f0044efa8379d202302807430cb5b5ee4
wxmsummer/algorithm
/leetcode/hot/49_groupAnagrams.py
658
3.703125
4
# 字母异位词分组 class Solution: # 将单词转换为列表后按字典序排序 # 使用dic保存分组 def groupAnagrams(self, strs:list) -> list: dic = {} length = len(strs) for i in range(length): l = list(strs[i]) l.sort() s = ''.join(l) if s in dic: dic[s].append...
6d655a04136f2a2bf3f4ad5c6726e6c3cf886d5d
wxmsummer/algorithm
/leetcode/hot/383_ransom.py
386
3.515625
4
ransomNote = input() magazine = input() list_1 = list(ransomNote) list_2 = list(magazine) for i in range(len(list_1)): print(list_1) print(list_2) if list_1[0] not in list_2: print(0) break else: list_2.remove(list_1[0]) del list_1[0] continue print(1) # return n...
c9941ccd8853940bc4b9f64f26c4783755349de7
wxmsummer/algorithm
/leetcode/offer/offer56-1_singleNumber.py
217
3.578125
4
# 只出现一次的数字 class Solution: def singleNumbers(self, nums: List[int]) -> int: single_number = 0 for num in nums: single_number ^= num return single_number
2cb11923ce346d66cf554b7556592494c52b2d05
wxmsummer/algorithm
/leetcode/hot/139_wordBreak.py
1,038
3.5625
4
class Solution: # 记忆化递归 # @functools.lru_cache(None) 禁止开启lru缓存机制 def wordBreak(self, s: str, wordDict: list) -> bool: import functools @functools.lru_cache(None) def backTrack(s): if not s: return True res = False for i in range(1, ...
8dd9a081d4078f7161cf36acf76d189d5afb2688
wxmsummer/algorithm
/leetcode/hot/22-2_generateParenthesis.py
2,096
3.5
4
class Solution(): def generateParenthesis(self, n:int) -> list: res, tmp = [], [] # left_num 表示还能放多少个左括号, right_num 表示还能放多少右括号 def backtrack(left_num1, right_num1, left_num2, right_num2): print('tmp:', tmp) # 如果左括号和右括号都放完了,说明这一轮回溯完成,将结果加入结果集 if left_num1 =...
f944157689453208684072deb6b5f99a7ddff703
wxmsummer/algorithm
/leetcode/hot/90_subsWithDup.py
586
3.65625
4
# 求子集2 # nums可能包含重复元素 class Solution: def subsetsWithDup(self, nums: list) -> list: def backTrack(start, tmp): res.append(tmp[:]) for i in range(start, len(nums)): if i > start and nums[i] == nums[i-1]: continue tmp.append(nums[i])...
35b2f4d82df46090bec5b965bf24f1c21454834b
wxmsummer/algorithm
/leetcode/hot/976_largestPerimeter.py
768
3.859375
4
# 三角形的最大周长 class Solution: def largestPerimeter(self, nums: list) -> int: if len(nums) < 3: return 0 nums.sort() length = len(nums) i, j, k = length-3, length-2, length-1 while i >= 0: if nums[i] + nums[j] > nums[k]: return nums[i] + n...
1349e81c63782210f997a14b8040f55228b3e6e8
wxmsummer/algorithm
/leetcode/offer/offer21_exchange.py
787
3.78125
4
# 调整数组顺序使奇数位于偶数前面 # 两次遍历 class Solution: def exchange(self, nums: list) -> list: newList = [] for num in nums: if num % 2 == 1: newList.append(num) for num in nums: if num % 2 == 0: newList.append(num) return newList ...
38a37365f1df0a0e8911266f32d4482096c2789a
wxmsummer/algorithm
/leetcode/hot/12-2_romanToInt.py
1,067
3.515625
4
class Solution(): # 直接遍历,逐个翻译 def romanToInt(self, s:str) -> int: # 由大到小构造罗马字字典 dic = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1} tmp, res = '', 0 if not s: return 0 i =...
4f2dc89118ac9811a7705b9e003ee484bb68b3ff
wxmsummer/algorithm
/leetcode/array/binary_search.py
643
3.5625
4
class Solution: def binary_search(self, nums:list, target:int): i, j = 0, len(nums) while i < j: m = (i + j) // 2 if nums[m] >= target: j = m else: i = m + 1 if i == len(nums): return -1 return i if __n...
b9498d588de3e9bf2cc8893544c744f29aa7d214
wxmsummer/algorithm
/leetcode/offer/offer31_validateStackSequences.py
942
3.734375
4
# 栈的压入、弹出序列 class Solution: def validateStackSequences(self, pushed: list, popped: list) -> bool: newList = [] # 直接模拟,每次入栈后,循环判断栈顶元素是否等于弹出序列的当前元素,将符合弹出序列顺序的栈顶元素全部弹出。 for num in pushed: newList.append(num) while newList and newList[-1] == popped[0]: de...
9ae4eb3dde5360d1e3487db79a7cbb64fd97e2d6
wxmsummer/algorithm
/leetcode/hot/73_setZeroes.py
847
3.703125
4
# 矩阵置零 class Solution: def setZeroes(self, matrix: list) -> None: row_len, col_len = len(matrix), len(matrix[0]) # 使用额外的两个行数组和列数组来存储行和列中的零信息 row_list = [1] * row_len col_list = [1] * col_len for i in range(row_len): for j in range(col_len): if ma...
26edab3caee726fcd7a5e621c59c23a4b4409cbc
CcCc1996/myprogram
/2-oop/03.py
2,142
3.5
4
# -*- coding: utf-8 -*- # Author: IMS2017-MJR # Creation Date: 2019/4/23 # 多继承的例子 # 子类可以直接拥有父类的属性和方法,私有的属性和方法除外 class Bird(): def __init__(self, name): self.name = name def fly(self): print("i can fly") class Fish(): def __init__(self, name): self.name = name def swim(self): ...
fe10575d95d37269565d10c9ee8ebe343edbb7b6
francisco0522/holbertonschool-interview
/0x00-lockboxes/0-lockboxes.py
531
3.796875
4
#!/usr/bin/python3 """ Lockboxes """ def canUnlockAll(boxes): """ method that determines if all the boxes can be opened """ if not boxes: return False opened = {} queue = [0] while queue: boxNum = queue.pop(0) opened[boxNum] = 1 for key in boxes[boxNu...
e4eab633f19ee8cdc500a7c8b48c8b2f7ace9fce
mp360/manitab
/scaleCan.py
3,996
3.578125
4
# from Tkinter import * # # a subclass of Canvas for dealing with resizing of windows # class ResizingCanvas(Canvas): # def __init__(self,parent,**kwargs): # Canvas.__init__(self,parent,**kwargs) # self.bind("<Configure>", self.on_resize) # self.height = self.winfo_reqheight() # sel...
b78ca51e2461286da4cfbb8f16610217e3db01dc
raseribanez/Youtube-Tutorials--Python-Basics--Wordlist-Generators
/wordlist_very_basic_nonrepeat.py
177
3.953125
4
# Ben Woodfield # This basic list generator DOES NOT repeat characters in each result import itertools res = itertools.permutations('abc',3) for i in res: print ''.join(i)
c22b162d749ad8db0d4e74228899c6a7f94e56ec
comalvirdi/CPE101
/LAB8/list_comp/funcs_objects.py
377
3.8125
4
# LAB 8 # COMAL VIRDI # EINAKIAN # SECTION 01 from objects import * import math # calculates the euclidian distance between two point objects # Object Object --> int def distance(p1,p2): return math.sqrt(((p1.x-p2.x)**2)+((p1.y-p2.y)**2)) def circles_overlap(c1, c2): sumRadii = c1.radius + c2.radius distanceCP = ...
354d51e1558a6e332bf82000e9d874b3d6c87b4b
comalvirdi/CPE101
/LAB3/logic.py
351
4
4
# LAB 3 # Name: Comal Virdi # Instructor: S. Einakian # Section: 01 # Determines whether or not an int is even # int --> bool def is_even(num): return (num % 2 == 0) #Determines whether or not a number falls within certain intervals #float --> bool def in_an_interval(num): return (-2 <= num < 9 or 22 < num < 42...
53da6c914c6b7139abf47e3b214b47725e93c50b
comalvirdi/CPE101
/LAB4/loops/cubesTable.py
1,518
4.3125
4
# CPE 101 Lab 4 # Name: def main(): table_size = get_table_size() while table_size != 0: first = get_first() increment = get_increment() show_table(table_size, first, increment) table_size = get_table_size() # Obtain a valid table size from the user def get_table_size(): size = int(i...
8b1b6df83a10e673536f70ac0e157b349269e975
yanitsa-m/udemy-ML-AZ
/reinforcement_learning/upper_confidence_bound.py
1,374
3.609375
4
# Upper Confidence Bound (UCB) in Python # Reinforcement learning algorithm import numpy as np import matplotlib.pyplot as plt import pandas as pd import math # Importing the dataset dataset = pd.read_csv('Ads_CTR_Optimisation.csv') # Implementing UCB algorithm for advertisements data N = 10000 d = 10 ads_selected ...
f46f987cb4948763de2c63a6ad33ffddbe2ef8dd
yanitsa-m/udemy-ML-AZ
/regression/multiple_linear_reg.py
2,557
3.921875
4
""" Multiple Regression model in Python """ import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing dataset - set up wd dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values # Encoding categorical data # Encoding the Indep...
94288149957696b01230c9cba3ae8c3c8257491e
gpapalois/ergasies-examinou
/exercise12 .py
215
3.90625
4
file = input("Δώσε ένα αρχείο ascii.") for i in range(len(file)): letter = file[len(file)-i -1] number = ord(letter) number2 = 128 - number ascii = chr(number2) print(ascii ,end ="")
5c025aa292e6e3bd670d99670a744324cdc6e463
monicarico-210/clase28febrero
/first.py
281
3.9375
4
print ("hola") a=2+3j b=1+1j c=a*b print(c) x=2 print(x) x=1.6 print(x) print(a, b, sep="...") print(a, b, sep="") x=float(input("entre el valor para x: ")) print(3*x) d=5 e=2 f=d/e print (f) h=d//e print (h) if x == d: print("iguales") if x > d or x < e: print("son iguales")
74973b79560175b3bc94bafe84051865ff9f3a53
ricardocodem/py-regex-exm
/ex3_findall_nome_idade.py
301
3.671875
4
#setup import re #entrada texto = ''' Michelle tem 20 anos a sua irmã Monique tem 22 anos. José, o avô delas, tem 77 anos e mora no apto 17.''' #buscando idades idades = re.findall(r"[0-9]{1,2}\s[a-z]+",texto) print(idades) #buscando nomes nomes = re.findall(r"[A-Z][a-z]+\w",texto) print(nomes)
3000fd6a5f68d7f3ed0ae6fdeedf7421775e580a
CEASLIBRARY/Intermediate_Python
/MyPackage/uc_student.py
1,303
3.921875
4
# Fuction to get the first anme, last name and year of birth of a person def demographics(): first_name = input('What is your First Name: ') last_name = input('What is your Last Name: ') year_of_birth = input('What is your Year of Birth: ') return [first_name, last_name, year_of_birth] # Fuction...
3aa0b1d11997bdd1e2e305532851d37a490e7f87
IvTema/Python-Programming
/lesson1.12_step7.py
205
3.578125
4
# https://stepik.org/lesson/5047/step/7?unit=1086 a = (input()) if (int(a[0])+int(a[1])+int(a[2])) == (int(a[-1])+int(a[-2])+int(a[-3])): print("Счастливый") else: print("Обычный")
115c5c1ae4b9ed7f13f7f974a27afa20fc1819d0
IvTema/Python-Programming
/lesson2.1_step12.py
141
3.5
4
# https://stepik.org/lesson/3364/step/12?unit=947 a = int(input()) b = int(input()) c = 1 while c % a != 0 or c % b != 0: c += 1 print(c)
6a923de7af4f2325e939b02b4ec10118b0837170
davidwilson826/TestRepository
/Challenge1.py
300
3.65625
4
done = "false" cubes = [1] sums = [1] currentnum = 2 while done == "false": cubes = cubes+currentnum**3 sums = sums+[x+currentnum**3 for x in cubes] for x in sums.sort(): if sums.count(x) > 1 and done == "false": print(x) done = "true" currentnum += 1
0edfe376bcc39c00986bae6a1016660ec1caec99
robocvi/2021-1-Computacion-Distribuida-
/Practica00/src/Grafica.py
1,596
3.953125
4
#Computación Distribuida: Práctica 0 #Integrantes: Ocampo Villegas Roberto 316293336 # David Alvarado Torres 316167613 #Clase Gráfica, la cual contendra nuestra implementación de una Gráfica, los detalles #de la implementación se encuentran en el readme. class Grafica(): numVertices = 0 listaVerti...
e9cb86ab9b68ed4b6f0c061f48629cb0eb270316
lguychard/loispy
/src/loispy/interpreter/procedure.py
2,279
4.28125
4
from environment import Environment class Procedure(object): """ Represents a loisp procedure. A procedure encapsulates a body (sequence of instructions) and a list of arguments. A procedure may be called: the body of the procedure is evaluated in the context of an environment, and given """ ...
cf06a980834902dedeb9b90610423b373cb382cc
shahakshay11/Array-3
/rotate_array_kplaces.py
820
3.9375
4
""" // Time Complexity : O(n) n is length of shorter array // Space Complexity : O(1) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : // Your code here along with comments explaining your approach Algorithm Explanation Reverse the array Swap the elements from 0 to k-1 ...
a4656e6ed4e97500a444824c2df8750cabc6fae2
Heisenberg27074/Web-Scraping-with-Python3
/urllibwork.py
560
3.625
4
@Imorting urllib modules import urllib.request, urllib.parse, urllib.error url=input('Enter') #urllib.request() is used for requesting a URL and urlopen() for opening a new URL #fhand is url handle here as in files it was file handle #Here we do not write encode() as urllib.request.urlopen() does it automatically fha...
2fa3fbd312b86064da4f77d85dd226575de9dcaf
Heisenberg27074/Web-Scraping-with-Python3
/lists/maxmin.py
724
4.3125
4
#Rewrite the program that prompts the user for a list of #numbers and prints out the maximum and minimum of the numbers at #the end when the user enters “done”. Write the program to store the #numbers the user enters in a list and use the max() and min() functions to #compute the maximum and minimum numbers after t...
2620b59600f82e82bdf14d2e8602c1a76c721659
Heisenberg27074/Web-Scraping-with-Python3
/diction/9.py
253
3.53125
4
st=input('Enter anything u want to:') di=dict() for something in st: #if something not in di: # di[something]=1 #else: # di[something]=di[something]+1 di[something]=di.get(something,0)+1 print(di)
356eff040a055c24f3b56603bcb7061b97f9f326
Heisenberg27074/Web-Scraping-with-Python3
/string/trawhile.py
409
3.921875
4
index=0 st='czeckoslowakia' while index<len(st): #index<=len(st)-1 /same # print(st[index]) index=index+1 #Write a while loop that starts at the last character in the #string and works its way backwards to the first character in the string, #printing each letter on a separate line, except...
c7a61e4190cec3569060c6d8b123e1181516fcb2
Heisenberg27074/Web-Scraping-with-Python3
/tuples/10.2.1.py
869
3.875
4
#Write a program to read through the mbox-short.txt and figure out the distribution by hour of the # day for each of the messages. You can pull the hour out from the 'From ' line by finding the time # and then splitting the string a second time using a colon. #From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008...
75a6883fb38db72e5775e46f6e94e49a3c4a9978
dimitardanailov/google-python-class
/python-dict-file.py
1,842
4.53125
5
# https://developers.google.com/edu/python/dict-files#dict-hash-table ## Can build up a dict by starting with the empty dict {} ## and storing key / value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' print dict ## {'a': ...
f47a6d7abe7ec178fa212157da6b64bb3b5dc084
fdloopes/Praticas_Machine_Learning
/Python/Linear_Regression/multi_features/main.py
3,485
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 4 00:50:26 2021 @author: fdlopes This program aims to implement a linear regression in a set of property price data by city, in order to be able to predict how much the value of each property will be according to the size and number of rooms. X...
eb3f91c0d395abf93d5c447b8883ab8e29ab4a80
rupeshvins/Coursera-Machine-Learning-Python
/CSR ML/WEEK#2/Machine Learning Assignment#1/Python/ex1_multi.py
2,808
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 13 00:40:12 2018 @author: Mohammad Wasil Saleem """ import pandas as pd import matplotlib.pyplot as plot import numpy as np import featureNormalize as fp import gradientDescentMulti as gdm import normalEqn as ne # Getting the data and plotting it. # x - profit # y - po...
978d281ef1061cfcb2afb78537b15b6f26553e03
openGDA/gda-core
/uk.ac.gda.bimorph/scripts/bimorphtest/__init__.py
668
3.78125
4
class Float(float): """Helper class for comparing calls with float arguments""" def __new__(self, value, tol=1e-8): return float.__new__(self, value) def __init__(self, value, tol=1e-8): float.__init__(self, value) self.value = value self.tol = tol def __eq__(self, other...
8c209d8fa3290af3dcbaf91942d376ded835706e
pbeth92/SSI
/prct06/multiplicar.py
2,844
3.65625
4
class Multiplicar(): def __init__(self, a1, a2, alg): if self.check_bin(a1): self.b1 = a1 self.b2 = a2 else: self.b1 = self.convertir_binario(a1) self.b2 = self.convertir_binario(a2) print(self.b1) print(self.b2) self.a1...
767b0082ff51d6363ff88022e7debb5f943b6338
pbeth92/SSI
/prct11/prct11.py
567
3.609375
4
""" Pablo Bethencourt Díaz alu0100658705@ull.edu.es Práctica 11: Implementar el cifrado de clave pública RSA. """ from rsa import RSA def menu(): print("Algoritmo RSA. \n 1.Cifrar mensaje \n 2.Descifrar mensaje \n 3.Salir") opc = input("Opción: ") if opc == '1': mensaje = input("\nInt...
c7668e86b91ed2fbcaa51d0d4811ae448d0f2a14
RobDBennett/DS-Unit-3-Sprint-1-Software-Engineering
/module4-software-testing-documentation-and-licensing/arithmetic.py
1,941
4.21875
4
#!/usr/bin/env python # Create a class SimpleOperations which takes two arguements: # 1. 'a' (an integer) # 2. 'b' (an integer) # Create methods for (a, b) which will: # 1. Add # 2. Subtract # 3. Multiply # 4. Divide # Create a child class Complex which will inherit from SimpleOperations # and take (a, b) as argueme...
26e6b4897c75fcc9aff4f845a5fc2a57a4983780
ROOTBEER626/Tic-Tac-Toe
/FinalTTT.py
10,308
3.8125
4
import sys import random #This class will be placeholder for the board values class mySquare(): EMPTY = ' ' X = 'X' O = 'O' #class to get the current player and positions class Action: def __init__(self, player, position): self.player = player sel...
264890b97e175eefb09864a743fa924d8d8563a8
TongyunHuang/LeetCode-Note
/Jan11.py
2,520
3.5625
4
# Jan 11 # 53. Maximum Subarray def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ maxSum, maxIdx, arrSum, arrIdx = nums[0], 0, 0, 0 L = [] for i in range(len(nums)): if i == 0: L.append((0, nums[i])) else: newSum = L[i-1][1] + nums[i] ...
f7d2976af17d464b0ff2bf35afe67b1b49c712e3
TongyunHuang/LeetCode-Note
/Jan18.py
1,869
3.546875
4
# 122. Best time to Buy and Sell Stocks def maxProfit(prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 0: return 0 if len(prices) ==2: if prices[1]-prices[0] >0: return prices[1]-prices[0] return 0 total = 0 localMin, localMax = p...
45c0ab4712ef1601e7b7679fdc3ad638866415a7
bps10/base
/files/files.py
1,689
3.9375
4
import glob as glob import os def getAllFiles(dirName, suffix = None, subdirectories = 1): """ Get a list of path names of all files in a directory. :param Directory: a directory. :type Directory: str :param suffix: find only files with a specific ending. :type suffix: str :param subd...
5a937360687f171ef3081dbbc613ee4a9b7b7af0
kaminosekai54/Modelisation-of-Interaction-of-O2-fish-aglae-
/functions.py
3,516
3.90625
4
# This file is composed of the usefull function ################################################ # import of the package # for the mathematical computation import numpy as np # import for the plot import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d # importing the odeint package to resolv our equat...