blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5d259898b9384995790f25fd6feed43284655366
vzpd/myBrushRecord
/exercise/每日一题_最长公共前缀.py
1,109
3.71875
4
# 编写一个函数来查找字符串数组中的最长公共前缀。 # # 如果不存在公共前缀,返回空字符串 ""。 # # 示例 1: # # 输入: ["flower","flow","flight"] # 输出: "fl" # 示例 2: # # 输入: ["dog","racecar","car"] # 输出: "" # 解释: 输入不存在公共前缀。 # 说明: # # 所有输入只包含小写字母 a-z 。 from typing import List class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: # if not s...
1dc968aee2ade8275249d893de5537b7c7b5f739
vzpd/myBrushRecord
/exercise/每日一题_验证回文字串.py
1,106
3.90625
4
# 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 # # 说明:本题中,我们将空字符串定义为有效的回文串。 # # 示例 1: # # 输入: "A man, a plan, a canal: Panama" # 输出: true # 示例 2: # # 输入: "race a car" # 输出: false class Solution: def isPalindrome(self, s: str) -> bool: # s = s.upper() # vchr = set([chr(i) for i in range(65, 91)] + [str(...
a4c6b4aa52e58644b117b0d9651f3e84b092e5c7
vzpd/myBrushRecord
/exercise/bd_二叉树的最近公共祖先.py
2,288
3.5625
4
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def getTree(l: List): dp = [None if x is None else TreeNode(x) for x in l] dp.insert(0, None) for i in range(len(dp)): if dp[i] is not None: if 2...
168ccc4d5ac294c65999871230c3219311719423
vzpd/myBrushRecord
/exercise/二叉树的中序遍历.py
859
3.953125
4
# Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] temp = [root...
f4be78ce019b7e8f5d889b27d7bfef0e979731cb
vzpd/myBrushRecord
/exercise/动态规划_做菜顺序.py
2,235
3.71875
4
# 一个厨师收集了他 n 道菜的满意程度 satisfaction ,这个厨师做出每道菜的时间都是 1 单位时间。 # # 一道菜的 「喜爱时间」系数定义为烹饪这道菜以及之前每道菜所花费的时间乘以这道菜的满意程度,也就是 time[i]*satisfaction[i] 。 # # 请你返回做完所有菜 「喜爱时间」总和的最大值为多少。 # # 你可以按 任意 顺序安排做菜的顺序,你也可以选择放弃做某些菜来获得更大的总和。 # #   # # 示例 1: # # 输入:satisfaction = [-1,-8,0,5,-9] # 输出:14 # 解释:去掉第二道和最后一道菜,最大的喜爱时间系数和为 (-1*1 + 0*2 + 5*3 ...
b37f4d873afce553f3ba107e8c218748a5589b86
chimnanishankar4/program_vita033
/Even_odd.py
170
4.21875
4
#Even or not start=int(input("Enter the start range:")) end=int(input("Enter the end range:")) for i in range(start,end+1): if i%2==0: print("Even numers",i)
d27f7aa379e3ff2b41e03b8a17db8f8fa58081e6
PeterStrob/agent-testing
/app/RESTful_API.py
1,590
3.875
4
"""Here we start with the construction of our FASTapi server. This server will be designed to add items to, delete items from, and retrieve a given list of items. """ from fastapi import FastAPI from pydantic import ( BaseModel, ) # Turns FastAPI into a function that we can pull commands from. app = ( FastAPI...
ae61a62cfdef6b2fbf8ce1a1aaa5e76e1030b58d
chinsaku/SwordForOffer
/8.跳台阶.py
348
3.8125
4
# -*- coding:utf-8 -*- class Solution: def jumpFloor(self, number): # write code here if number == 1 or number == 2 or number == 0: return number n = 1 m = 2 for i in range(number-2): res = m +n m, n = res, m return res a = Solu...
4724db7cc39048c02031d027c3f8cd1f6b0f4438
chinsaku/SwordForOffer
/19.顺时针打印矩阵.py
635
3.71875
4
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def transpose(self,M): m = len(M) n = len(M[0]) b = [] for p in range(n-1,-1,-1): a = [] for q in range(1,m): a.append(M[q][p]) b.append(a) return b def ...
c6ecbbff5b162c94ba0b363f408093fe1c45f9a9
chinsaku/SwordForOffer
/4.重建二叉树.py
676
3.609375
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if len(pre) == 0: return None index = tin...
718e16449fea92f173fe82ed33a7545bfe08e460
jackkinsella/RossmannPredictions
/code/linear_regression.py
989
3.5
4
import pandas from prepare_data import X, y from utils import root_mean_square_percentage_error from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.dummy import DummyRegressor X_train, X_test, y_train, y_test = train_test_split(X, ...
8a26b6f553a4d0cf5503afe2e132a005af5bbe4c
andrewnvu/linked_lists
/delete_middle.py
1,363
4
4
class Node(): def __init__(self, value): self.value = value self.next = None class linkedList(): def __init__(self): self.head = None def append(self,value): new_node = Node(value) if self.head == None: self.head = new_node return cu...
05248e95998d9ea3c84f42d39d117a2ad9b373d3
aa-adnanazad/python-blackjack
/table.py
1,872
3.8125
4
# print("===============================") # print("||---------BLACKJACK---------||") # print("|| [K][░] ||") # print("|| ||") # print("|| ||") # print("|| ||") # print("|| [A][K][5] ||") # print("|| ...
24b9d8eb3844d0e9bfa43e9c3ec9a27613dbf306
VsPun/learning
/sample/chapt05/chapt05-13.py
1,775
3.84375
4
from bs4 import BeautifulSoup # HTMLコードを準備 html = ''' <!DOCTYPE html> <html> <head> <title>BeautifulSoup test</title> </head> <body> <h1 id="hello">Hello, BeautifulSoup !</h1> <h1 id="nice">Nice to meet you, HTTP !</h1> <h1 id="how">How are you, HTML !</h1> This is document. </body> </html> ''' soup = BeautifulSoup( ...
b880de53fa74bbd0e926dc0551ec7c64fe012642
VsPun/learning
/sample/chapt02/chapt02-11.py
470
3.6875
4
for i in [0, 1, 2, 3, 4]: print( i ) # 0から4まで1行ずつ表示される for j in (0, 1, 2, 3, 4): print( j ) # 0から4まで1行ずつ表示される for k in range( 5 ): print( k ) # 0から4まで1行ずつ表示される h = [ 'Hello, World', 'How are you, System', 'Nice to meet you, Python' ] for l in h: print( l ) # メッセージが3行表示される for m in 'ABC': print( m ) # Aから...
fedf2cd0ebb531212f549dae75227671f02c64d6
VsPun/learning
/sample/chapt02/chapt02-19.py
876
3.8125
4
def showMsg( msg1, msg2='Good morning', msg3='See you later' ): print( msg1 ) print( msg2 ) print( msg3 ) # 最初と二つ目の引数を指定する showMsg( 'Hello, World', msg2='How are you, System' ) """ Hello, World How are you, System See you later と表示される """ # 最初と三つ目の引数を指定する showMsg( 'Hello, World', msg3='Nice to meet you, Python' ) "...
2894b82e5bb537ff4de9bce7c23716302dcea985
VsPun/learning
/sample/chapt07/chapt07-10.py
437
3.796875
4
import threading import time g = threading.Lock() # ロックを作成 def h(): # 並列処理の内容 with g: # 排他的に行いたい処理 for j in range( 5 ): print( 'Hello' ) time.sleep( 1 ) return i = threading.Thread( target=h ) i.start() # 並列処理を開始 with g: # 排他的に行いたい処理 for j in range( 5 ): print( 'World' ) time.sleep( 1 ) ...
75c52fb11887cd89be8cf98d54faf653351661d9
VsPun/learning
/sample/chapt02/chapt02-3.py
589
3.5625
4
with open( 'filename.txt', 'w' ) as f: pass # これはコメントです print( 'Hello, World' ) print( 'Hello, World' ) # これはコメントです """ with open( 'filename.txt', 'w' ) as f: f.write( 'Hello, World\n' ) # これは間違ったコメントです f.write( 'How are you, System\n' ) """ with open( 'filename.txt', 'w' ) as f: f.write( 'Hello, World\n' ) # これは...
39b13c3c0a8252d702976dfbf84ebab93598a228
algerk/210CT
/Q2.py
472
3.5
4
def trlz(n): x = 1 tList = [] output = 0 for i in range(2, n + 1): x *= i for i in str(x): tList.append(i) tList.reverse() #iterates the factoral numbers, appends to list and then reversed for y in tList: if y == "0": output += 1 ...
a5c5d77c80f6fe9f7f1f5106632c977b0826b017
MunkyCode/CubeSolver
/SimpleSolver/HumanSolver.py
986
3.8125
4
import pycuber as pc from SimpleSolver.util import Solved class HumanSolver: def Solve(self, cube): assert type(cube) == pc.Cube, "Cannot solve non Cube" print(cube) moves = ["R","R'","R2","L","L'","L2","U","U'","U2","D","D'","D2","F","F'","F2","B","B'","B2"] inp = inp...
f0ecf874f6e6285d9e3537b63b4ea03b1698eb93
bartlomiejmusial/TurtleRace
/turtles.py
1,232
4.0625
4
from turtle import Turtle colors = ["red", "orange", "yellow", "green", "blue", "purple"] turtles = [] # Function to set turtles with different colors, in line def set_turtles(): turtle_red = Turtle(shape="turtle") turtle_red.penup() turtle_red.color(colors[0]) turtle_red.goto(x=-230, y=-100) tur...
6540c2bb394f3184dc0d560362a563abe511a9da
kmpatzke/theGoatProblem
/Automatic/TheGoatProblemSimulation.py
1,469
3.84375
4
from door import door from functionList import * import random def main(): while True: rounds = int(input("How many rounds you want to simulate?")) try: rounds = int(rounds) break except ValueError: print("Oooops. Invalid value") hits = ...
a7a4535fdd19828eca250ca09ed7d09d132c760c
JimVliet/Python-DataStructures
/Python-DataStructures/Python-DataStructures/encryptTest.py
592
3.75
4
def encrypt(numbToEncrypt, key): base = len(key) remList = [] while numbToEncrypt > 0: rem = numbToEncrypt%base remList.append(rem) numbToEncrypt = numbToEncrypt // base newString = "" while remList != []: newString += key[remList.pop()] return newString def decrypt(stringToDecrypt, key): stringToDec...
2a2bb7ec0bd59bc48ad41e27667a13e7fdfd44de
gideontong/FireAssassins
/BruteForcedIteration.py
1,300
3.609375
4
""" Program: Brute Forced Iteration Author: Gideon Tong Version: Generator v5 Description =========== This program is very similar to BruteForce.py, except in the sense that it doesn't actually brute force through a sequence of values in order to find possible keys. Instead it takes an input (in this case, pwned.txt)...
9cefc268ec95fbd74de8b653cf8559eb50844d9a
BrunoBocarde/Curso-Python
/notas/fundamentos.py
5,402
4.59375
5
print('Hello word') print(1 + 2) # help(print) usando o help voce consegue consegue ver a "documentação" da função # TIPOS BASICOS print(True) print(False) print(1.2 + 3) print('test') print("test 2 ") print('voce é '+ 3 * 'muito ' + 'legal') #print(3 + " 3") Ambiguidade lista = [1, 2, 3] # lista dicionar...
8a3c55dce4318d14b3c26a8260537492f718540c
liamkolber/ASTR3800
/Project1/Kolber_LabProject1.py
15,665
3.828125
4
import numpy as np import matplotlib.pyplot as plt import scipy.stats as sci import Kolber_functions as my print "\nBeginning Project 1\n" print "Press enter to begin Problem A(i)" my.pause() # Problem A(i) rand1 = [] rand2 = [] rand3 = [] randlist = [rand1, rand2, rand3] #empty array for random numbers seed1 = 41492...
9c2935c42f4c2cd13d3367b8bc1e0d039db124ad
jkulesza/Python_Workshop
/03_Monte_Carlo_Pi/MC_pi_simple.py
1,089
3.84375
4
import numpy as np from matplotlib import pyplot as plt # Function to calculate pi by comparing if a random x,y pair falls within a # circle with unit radius. Return the x,y values, estimate of pi, and relative # error. def calc_pi(n): x = np.random.rand(n) y = np.random.rand(n) within = np.less_equal(np....
367ab9749a7d03967633afaf7b7f408090952cb1
pranshu19chester/Coursera-ML-in-Python
/Scripts/Part 3- Logistic Regression/regularized_logistic_regression.py
3,008
3.59375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 27 03:26:51 2017 @author: pranshu """ #Logistic Regression #importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import os path=os.path.pardir+'/data/ex2data2.txt' data = pd.read_csv(path, header=None, nam...
a72246b6d82019383c90fc9213f28909bd785a06
guidokanschat/notes
/numerik/code/newton-stepsize.py
398
3.859375
4
import math def newton(x, f, Dfinv, tol): r = f(x) r_current = abs(r) while (r_current>tol): d = Dfinv(x,r) x -= d r_old = r_current r = f(x) r_current = abs(r) while (r_current>=r_old): d *= 0.5 x += d r = f(x) r_current = abs(r) return x def f(x): return x...
2205ab4e379c58ee6c14fc5687157536c6d59c35
CHO1116/self-study-py
/PythonApplication1/MaxAlgorithm.py
804
3.609375
4
#[?] 주어진 데이터 중 가장 큰 값 구하기 import sys # 최댓값 알고리즘: 주어진 범위에 주어진 조건에 해당하는 자료들 중 가장 큰 값 def main(): #[0] Init(초기화): max = -sys.maxsize - 1 # 숫자 형식의 데이터 중 가장 작은 값으로 초기화 #[1] Input(입력): numbers = [-2, -5, -7, -1, -15]; # MAX: -1 N = len(numbers) #[2] Process(처리): 주어진 범위에 주어진 조건 (필터링) for i ...
b5a3ce8d61448ad28a247972d29f15314e892a94
jamesmitchell81/CSVQuery
/csvq/patterns.py
593
3.828125
4
class Patterns(object): def __init__(self): self.column = "([a-z]+)" self.space = "\s{1}" self.float_number = "([0-9]+(?:\.[0-9]+)?)" self.string = "'([a-z ]+)'" def between_pattern(self): return (self.column + self.space + "BETWEEN" + self.space + self.float_number + ...
3cee1f59a8fcc066ee2f65359d340acab132cae6
slycooper50/Python
/lec1/Ex3.py
181
4.03125
4
print ("Enter the five-digit number that will be printed with its digits seperated by spaces: \n") x = input() print (x[0] + " " + x[1] + " " + x[2] + " " + x[3] + " " + x[4])
1f65a72a4ef3411c1c4e35151e114f854a6fdd32
slycooper50/Python
/lec4/Ex1.py
194
3.8125
4
def funct(a): mult = 1 for i in a: mult = mult * float(i) return print(mult) print("Enter the list of numbers to be multiplied.") s = input() list1 = s.split() funct(list1)
40e0e67978d50053f5cceada7402961cc27db9da
aliu47/Hepran-Tree
/Tree.py
3,163
3.8125
4
import oddSugar import evenSugar class Tree: def __init__(self): self.evenSugars = ["GlcNAc", "GlcNAc6S","GlcNS","GlcNS6S"] self.oddSugars = ["GlcA","GlcA2S","IdoA","IdoA2S"] def tree(self): # Send an even parent sugar in to see what odd sugar children can connect def oddLoop(s...
b0245e4d3b0229655fd2325c9eb58b79d4a720be
leejaeyeong/Algorithm
/Baekjoon/silver/행렬.py
650
3.90625
4
def toggle(arr,row,col): for i in range(row,row+3): for j in range(col,col+3): arr[i][j]='1' if arr[i][j]=='0' else '0' def is_equal(arr1,arr2): for i in range(n): for j in range(m): if arr1[i][j]!=arr2[i][j]: return False return True n,m=map(int,inp...
10a1c0d227864f29b53a08185363b44ff61f90d3
leejaeyeong/Algorithm
/Programmers/연습문제/핸드폰 번호 가리기.py
187
3.546875
4
def solution(phone_number): answer = '' for i in range(len(phone_number)-4) : answer = answer + '*' return answer + phone_number[len(phone_number)-4:len(phone_number)]
03290097ad8a2ea32ded88f1b3d84847cdeb45f3
leejaeyeong/Algorithm
/Programmers/DFS,BFS/타겟넘버.py
959
3.875
4
""" n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요. """ cnt = ...
5615b1d2eac7357a660e100d295c6c4a6f189a4d
leejaeyeong/Algorithm
/Programmers/연습문제/JadenCase 문자열 만들기.py
349
3.5625
4
def solution(s): state = False x = '' for i in range(len(s)) : if state == False and s[i] != ' ': x = x + str.upper(s[i]) state = True elif state == True and s[i] != ' ' : x = x + str.lower(s[i]) elif s[i] == ' ' : x = x + ' ' ...
630999cb246915614035ca2e49230fa4b43faf73
leejaeyeong/Algorithm
/Baekjoon/silver/큐.py
860
3.65625
4
import collections import sys queue=collections.deque() n=int(input()) queue_length=0 # len(queue) 보다 push할때 +1, pop할때 -1로 queue size 갱신 for i in range(n): command=sys.stdin.readline().split() # python 입력은 sys로 if command[0]=='push': queue.append(command[1]) queue_length+=1 elif command[0]==...
dcd1a21fb0212637e54baea90dab73e1579d9682
chausler/funky_george
/utils.py
1,091
3.8125
4
#!/usr/bin/env python """ various utility functions @author: Chris Hausler """ import numpy as np def locate_tweet(places, tweet): """ If the tweet has coordinates and they are in one of the target places, update the tweet with the place field and return, otherwise return None """ if (tweet['coor...
cf79046803230de7125feaab4b56ce43de1131ac
93arnaldo/hello-world
/FizzBuzz.py
744
4.375
4
#FIZZBUZZ #Python 2.7 print '''Hi This is the game FizzBuzz In case a number is divisible with 3, the diplay will show "fizz" instead of the number. If a number is divisible with 5, it prints "buzz". If it's divisible with both 3 and 5, it prints "fizzbuzz".''' x = 0 while True: Number = int(raw_input('Plea...
4614f3a18313063ce42f5e58f5f2ee7a9ccb738c
Akash00726/Python
/HelloWorld.py
154
4.09375
4
print("What is your Name?") ans=input() if ans=="Akash": print("Hello Akash Saxena") else: print("Sorry you are not my boss! " + str(len(ans)))
91bca604120f65fc086bfbae3f4fc820c8cd1834
Artekaren/Trainee-Python
/D52_quarters.py
1,335
3.703125
4
#Desafío52 - Ventas. Considerar este diccionario para todos los siguientes ejercicios #5. Generar programa quarters.py. Se pide generar un diccionario, llamado quarters , con las ventas de cada trimestre. Las claves tienen que ser "Q1" , "Q2" , "Q3" , "Q4". ventas = { "Enero": 15000, "Febrero": 22000, "Marzo": 12000, ...
a939b74bd722c173cf6294b6a3e3fbc6e3e6cd0f
Artekaren/Trainee-Python
/V28_dicc.py
940
4.15625
4
#Ejercicio28: Diccionarios #Creacion notas = {'camila':7,'antonio':5,'felipe':6,'antonia':7} #Entrega las notas de felipe print(notas['felipe']) #Si el valor está duplicado entrega el último valor asignado duplicados = {'clave':1,'clave':2} print(duplicados) #Se puede agregar un nuevo elemento al final del Diccion...
f306d4a266b79909d285c7c0ffc722c9634b335b
Artekaren/Trainee-Python
/D14_genera_patron.py
466
3.8125
4
#Desafío14: Generar patrón #Debe crear un programa que logre replicar el siguiente patrón, donde el usuario ingrese un número, y ese número corresponderá al número de filas que se debe generar. La soluciṕon debe estar dentro delprograma llamado genera_patron.py . #1 #12 #123 #1234 #12345 num = int(input("Ingrese núme...
4448ab2998b729c3eddd5a11e1bd7960580beac1
Artekaren/Trainee-Python
/V16_variables_local_y_global.py
439
3.5
4
#Ejercicio16: Variables locales def ejemplo_local(parametro): print('Este es el parametro ',parametro) definida_dentro='Esta variable también es local' return parametro, definida_dentro #Defino la variables: retorno para que almacene el valor que entrega la función retorno=ejemplo_local('hola') print(retor...
17f815b749293e5c4aad806d48181d1346c3712f
Artekaren/Trainee-Python
/D05_emprendedor3.py
1,317
3.59375
4
#Desafío5: Rentabilidad #Un emprendedor quiere crear una aplicación y necesita saber si es rentable. #3. Crear el programa emprendedor3.py donde el usuario ingrese el precio, el número de #usuarios, los gastos y las utilidades del año anterior, este último parámetro será optativo, #si el usuario no lo ingresa se asumi...
43b0c2460babc51c29a16ce68d301361fa229fa7
Artekaren/Trainee-Python
/E05.py
348
4.09375
4
# Ejercicio 5: Obtener la representación inversa de una cadena de caracteres cadena=input('Ingrese la palabra a invertir: ') for i in range(len(cadena)-1,-1,-1): print(cadena[i],end='') print() print('La longitud de la cadena es: ',len(cadena)) #Notacion de slicing print('') print(cadena[::]) print('La palabra in...
35d16790e1120e7ed06a776254ea47da313cef0e
Artekaren/Trainee-Python
/D43_listas_tres.py
1,384
3.703125
4
#Desafio43:Generar un loop que muestre en pantalla aquellos autos cuyo segundo campo (el número flotante) es mayor al de la media de todos los autos. import pandas as pd df_auto = pd.read_csv('auto.csv') auto=df_auto.values.tolist() #print('Lista original: {}'.format(auto)) #print('-----------------------------------...
8d21a9183339b004f82e8dc9ee7d788a4d732408
Artekaren/Trainee-Python
/D49_caso_chile.py
906
3.703125
4
#Desafío49 - El caso de Chile import pandas as pd df_jolim = pd.read_csv('athlete_events.csv') #1. Generar un nuevo subset a partir del DataFrame original, que almacene todas las observaciones correspondientes a Chile. aux_1 = df_jolim[df_jolim['NOC'] == 'CHI'] #2. Utilizando el subset generado, reportar la cantida...
78e3e794a62cdeffabcd05b4b3d44055e2a1be80
Artekaren/Trainee-Python
/D25_letra_o.py
512
4.125
4
#Desafío25: Programa de letras #1 La función letra_o(n) , la cual al ser llamada, retornará una cadena de texto que al ser imprimida con print, dibujará una letra "o" según el ejemplo print(letra_o(n)) import sys num=int(sys.argv[1]) def dibujar(num): contain='' for i in range(num): contain+='*' p...
977ec871668b347e4e8a26e5cdc02ef024103638
timotech/GettingStartedWithPython
/02DisplayingText/_02DisplayingText.py
635
3.84375
4
print('The capybara is the worlds largest rodent') print('The capybara likes to live in groups') print("The capybarra can swim") print("It's a beautiful day") #its better to stick with either single quotes or double quotes because you can use either print('Hickory Dickory Dock!\n The mouse went up the clock') #Goes to ...
65e7d94071be3af0f603f632674610079e182651
daberry/python_toy_problems
/coinSums.py
432
3.578125
4
coins = [200, 100, 50, 20, 10, 5, 2, 1] cache = {} def makeChange(total, coins): counter = 0 coins.sort() def generator(index, remainder): coin = coins[index] if index == 0: remainder % coin == 0 && counter += 1 return while remainder >= 0: genera...
f1390c8466fdbb537223b28a138b42539d10b960
daberry/python_toy_problems
/makeChange.py
444
3.65625
4
coins = [200, 100, 50, 20, 10, 5, 2, 1] def makeChange(amount, coins): counter = 0 coins = sorted(coins, reverse=True) def generator(index, remaining): coin = coins[index] if index == 0: if remaining % coin == 0 : counter += 1 return while remaining >= 0: ...
d02f45ba870ddd9f4a5617f83108f7ad764bd747
daberry/python_toy_problems
/set.py
1,009
3.671875
4
import set class Set(set.Set): # this set class extends set.Set def __init__(self, value = []): self.data = {} # manages a local dict self.concat(value) # hashing: linear search times def intersect(self, other): result = {} for x in other: ...
bd6ce730a7e2988f03eb68c0118f52990dfd07f5
daberry/python_toy_problems
/convertArray.py
897
3.984375
4
# 2. Given an array [a_1, a_2, ..., a_N, b_1, b_2, ..., b_N, c_1, c_2, ..., c_N], # efficiently convert it to # [a_1, b_1, c_1, a_2, b_2, c_2, ..., a_N, b_N, c_N] # using as little space as possible. # The element at the ith position in the final array # is at position (i % 3) * N + (i / 3) in the original a...
85bc5ed719f197b4675a7c7e7cb1c03bebe6a8bb
daberry/python_toy_problems
/insertionSortList.py
344
3.609375
4
class Solution: def insertionSortList(self, head): if not head: return head ref = ListNode(0) ref.next = head current = head while current.next: if current.next.val < current.val: current.val, current.next.val = current.next.val, curren...
937be77d29e9d81abb79147c4feda6e00168ae29
keaveney/EOS_DB
/module_codes/uploadITSDAQTests.py
11,224
3.5
4
#!/usr/bin/env python # uploadITSDAQTests.py -- an (updated!) interface for uploading tests from ITSDAQ results summary files to the ITk Production Database # Created: 2019/01/17, Updated: 2019/03/22 # Written by Matthew Basso if __name__ == '__main__': from __path__ import updatePath updatePath() import argp...
8deb34c5fd4ee7cf15f437ce8e2961bb91ae401f
songchenguang/LeetCode
/LeetCode_CN/21.合并两个有序链表.py
1,077
3.765625
4
# # @lc app=leetcode.cn id=21 lang=python3 # # [21] 合并两个有序链表 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional...
771dc8bea83ce57de392604f34a7cf0a4613c59a
songchenguang/LeetCode
/LeetCode_CN/14.最长公共前缀.py
474
3.546875
4
# # @lc app=leetcode.cn id=14 lang=python3 # # [14] 最长公共前缀 # # @lc code=start class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if len(strs) == 0: return '' for index in range(len(strs[0])): curChar = strs[0][index] for item in strs: ...
74b96d54d78d5391160b2d5e2db9be748d81e0a0
jnicholson-wcgs/Python-Cricket-2
/main.py
3,229
4.21875
4
# WCGS Cricket Program # # over() - an over is cricket is 6 balls bowled by the batting team # validateball() # Routine to capture the value for a run # Better version of enterball(). Uses try and except to make the code robust # Still needs better validatiion of the range of values for a run # def validateball(ball)...
7b1d8e653786ae24b5c2956d655e5158be41fcef
kamble-pradnya/program
/6.py
156
3.96875
4
#..TO DISPLAY INDEX OF 1ST APPEARANCE OF THE SUBSTRING..# string='Python programming' substring='prog' index=string.find(substring) print(index)
1ca4f6f398c753bb514c365ec39f4a4456d8a96f
ChrisDuhan/4143-CPL.P-J
/LetterDistribution.py
1,095
3.8125
4
""" This program counts and stores the frequency of each letter occuring in a document. When I started I realised that using regular expressions is not a great way to solve this problem, as it has to run through the entire file once for each letter. I intended to use it as a way to do comparison with the known english ...
24e8f84903b1230542ea4d40e7d60be881e232d2
J-Weaver0405/Py121Class
/double_letters.py
428
4.09375
4
# double letter solution def double_letters(string): lst=[] for i in string: lst.append(i) x=0 while x < len(lst) - 1: if lst[x] == lst[x+1]: return True x=x+1 return False def find_double_letters3(word): return len([x for x in word if x*2 in word]) >= 1 prin...
efa0fe83dab0f055b7155888392113b876dfa629
K-ksenia/play-off
/DZ1.py
3,775
3.671875
4
import random def draw(team_list, match): if len(team_list) > 0: # Определяем команду рандомно random.shuffle(team_list) match.append(team_list[0]) del team_list[0] # Определяем количество ею забыитых голов в первом матче match.append(random.randint(0,8)) # ...
c197e0d5e3492c66ba6d3f483a098bdadc76e8a4
maggiebzt/learn-python-the-hard-way
/ex19-my-own-function.py
1,136
4.21875
4
from sys import argv script, place_of_origin = argv # Define the function where are you from def where_are_you_from(country): return "I am from %s." % country # Define the function how old are you def how_old_are_you(age): return "I am %d years old." % age origin = 'Indonesia' current_age = 23 # Variable print ...
4c8df439d1aa9d020fa79d3b10566c9a0588d6f9
maggiebzt/learn-python-the-hard-way
/ex13-more-input-from-user.py
554
3.859375
4
# 3. Combine raw_input with argv to get more input from user from sys import argv # Variables script, time_of_day = argv print "This is ma script:", script # Print out greetings according to the argument provided by user print "Good", time_of_day # Prompt user to provide input condition = raw_input("How are you tod...
4022d3cfed8a85b8d36d354e9bb1b09bf7df6a68
maggiebzt/learn-python-the-hard-way
/ex15-file-methods.py
1,356
3.984375
4
# ex15: Reading Files # The file requires 1 additional argument when ran in terminal # To run in terminal: # - download this file (ex15c.py) and ex15_sample.txt file # - call '$ python ex15c.py ex15_sample.txt' from sys import argv # Argv variables script, filename = argv # Open file txt = open(filename) # Print f...
f14e6798c22fe6e201587c53dcc7cb6b427f0ec2
maggiebzt/learn-python-the-hard-way
/ex15-raw-input-only.py
870
4.46875
4
from sys import argv # Argument variables script = argv # Prompt user to insert filename filename = raw_input("What's your file name?") # Open the file and save it as a variable txt = open(filename) # Print out the filename print "Here's your file %r:" % filename # Read the file and print it out print txt.read() ...
1c5733b4863f217a9282fc599c5bf0f5294f322d
maggiebzt/learn-python-the-hard-way
/ex06.py
883
4.28125
4
# Variables x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s" % (binary, do_not) # Two strings # Print out strings print "I said %r" % x # One string print "I also said: '%s'." % y # One string # More variables hilarious = False joke_evaluation = "Isn...
fbcd621b6d33a84e0121d45b56a45e64679f2777
aafak/TestAssignment
/check_list_is_partitionable.py
1,336
3.890625
4
def is_subset_exist_with_sum(arr, required_sum): for i in range(1, len(arr)+1): for perm in permutations(arr, i): if sum(perm) == required_sum: return True return False def is_list_partitionable(arr): result = None size = len(arr) total_sum = sum(arr) # If s...
a511f6204593206058821038d33b34831ac41c13
Ayala075/Ejercicios-de-tipos-de-datos-simples
/Ejercicios de Tipos de Datos Simples/Ejercicio11.py
923
3.96875
4
# Imagina que acabas de abrir una nueva cuenta de ahorros que te ofrece el 4% de interés al año. Estos ahorros debido a intereses, que no se cobran hasta finales de año, se te aña # den al balance final de tu cuenta de ahorros. Escribir un programa que comience leyendo la cantidad de dinero depositada en la cuenta de ...
826ff38e2667a461f6fbfdeae301c20a3172bfba
HiteshK21/SDP-Python
/Task1.py
2,611
4.03125
4
#1 WAP for addition, subtraction, multiplication, and division:- num1 = int(input("Enter First Number: ")) num2 = int(input("Enter Second Number: ")) print("Enter which operation would you like to perform?") ch = input("Enter any of these char for specific operation +,-,*,/: ") result = 0 if ch == '+': ...
1df34d40d11a05b620f635e7efe64ca87434205c
jtizon001/visa-info-website
/sqlqueries.py
528
3.578125
4
import sqlite3 import pprint def main(): conn=sqlite3.connect('countries.db') c=conn.cursor() q1=c.execute('''select count(nameKey) from COUNTRIES''').fetchall() pprint.pprint(q1) q2=c.execute('''select name, travelAdvisory from COUNTRIES as c where c.travelAdvisory like "%Level 4%" or c...
b824d56e2b2c577c07f807f6fe41fef3ee97ce4e
larry-dalmeida/movie-nights
/Desktop/Movie_nights/movie_nights.py
808
4.21875
4
import random from movies import movies print("Welcome to random Movie generator") genre_selection = input("Do you want to select a genre? Type - yes or no\n").lower() if genre_selection == 'no': #for random movie from all lists num_gen = random.randint(1,len(movies)) random_movie = movies[num_gen] print(f"O...
690740b4f70d046042724fb0f187139d7ed9ae7c
Aubins-Projects/WorldClock
/Example.py
9,844
3.90625
4
################################################ # PYTHON SCRIPT FOR SETTING THE DISPLAY CLOCKS # # By: AUBIN HEFFERNAN # # Using TKINTER you can set multiple clock instances based off your choosen offset # ################################################## # # Example: clock1_zone = 1 #this gives a...
e2068e3572a23d1bff124bda849938773251ac91
Gloom-er/training_matplotlib
/2.py
380
3.53125
4
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.array([-3, -2, -1, 0, 1, 2, 3]) y = np.array([9, 4, 1, 0.1, 1, 4, 9]) ax.plot(x, y, marker='o') ax.plot(0.5 * x, y, marker='^') ax.plot(2 * x, y, marker='*') ax.plot(x*0.3, y, color='red', linestyle='--', marker='o', alpha=0....
4cfa4b438f62c95ec0de4243857ab75bc782abc9
SaiChandraCh/DSA-py
/src/tree/binary_tree/binary_tree.py
2,744
3.75
4
from tree.node import Node from stack.stack import peek class BinaryTree: __root = None def __init__(self,val): __root = Node(val) def insert(self,val): curr = self.__root prev = None """DLR""" def pre_order(self, head): stack = [] stack.append(head) ...
8f4637ed7444514e25fbfb8730d7b3a8d4309308
SaiChandraCh/DSA-py
/src/list/circular_linked_list.py
1,118
3.71875
4
from list.Node import Node class CircularLinkedList: __head = None __tail = None __length = 0 def __init__(self,val): self.__head = Node(val) self.__tail = self.__head self.__length = 1 def insert(self,val,index = 0): if index == 0: temp = Node(val) ...
b17eac1a09259d588837673721bf14a361619a98
annh3/coding_practice
/dfs.py
854
3.75
4
import copy class Node: def __init__(self, name=-1, children=[]): self.color = "white" self.parent = None self.d = 0 self.f = 0 self.name = name self.children = children time = 0 def dfs_visit(cur, sorted_list): print("apples") global time time += 1 cur.d = time cur.color = "gray" print("hello") ...
057ef68a579ba3316055880b6cbd199e535ac351
annh3/coding_practice
/prefix_suffix_search.py
2,282
3.9375
4
import collections Tree = lambda: collections.defaultdict(Tree) # oh wow you can literally name this anything WEIGHT = False import pdb """ """ class WordFilter(object): def __init__(self, words): self.trie1 = Tree() #prefix self.trie2 = Tree() #suffix for weight, word in enumerate(words):...
546d004f011c7143aff2625ef1edd0e218e14b61
den41k0708/python
/denis_2_1.py
819
3.53125
4
import random import time def create_matrix(n): random_matrix = [[random.randint(1, 100) for e in range(n)] for e in range(n)] rows = random.randint(1, n) for i in range(rows): row = random.randint(0, n - 1) random_matrix[row].sort(reverse=True) return random_matrix de...
c370a5048698fc030ec14a0966578a19cc4e98e7
marciogarridoLaCop/Python
/Calculadora Tintas/comodo.py
1,180
3.5
4
class Comodo: __largura: float __profundidade: float __altura: float def __init__(self, largura, profundidade): self.largura = largura self.profundidade = profundidade self.__altura = 2.9 # propriedades do objeto comodo @property def largura(self): return self.__...
6061f01c05fee6ecd70fce9020d0b6d1249786bb
GfGranato/URI
/URI_1001.py
84
3.65625
4
# -*- coding: utf-8 -*- A=int(input()) B=int(input()) X= A + B print('X = %d' %X)
bbf940cb21fa2d1dfce5bff3d2180bfb5f333db2
praxpk/Weather_accidents_prediction
/merge_thread.py
7,765
3.546875
4
import pandas as pd import datetime import time import threading from selenium import webdriver import queue import traceback class w_sel: def __init__(self,muni,num): """ The queue stores tuples where each tuple contains start and end indices of the rows of the dataframe. :param muni: the ...
39ee83c3b2a67bc119238f5349f97a4ea7c08348
javenonly/stock
/src/learn/1.py
697
3.59375
4
# i = 1 # print(type(i)) # f = 1.1 # print(type(f)) price_str = '30.14,29.58,26.36,32.56,32.82' # if isinstance(price_str, str): # print('str') # 数组,有序 mylist = [1,2,3,4] price_array = price_str.split(',') print(price_array) # print(list(enumerate(price_array))) price_array.append('32.82') print(price_array) ...
43b87e9c1762f52597fa43b888136a7aea1633ec
javenonly/stock
/src/learn/09_function_高阶函数.py
1,239
3.84375
4
# def myfun(fun, string): # fun(string) # def fun1(string): # print(string*1) # def fun2(string): # print(string*2) # myfun(fun1,'hello') # myfun(fun2,'world') # # lambda # a = lambda x, y: x+y # b = lambda x : x *3 # print(a(10,5)) # print(b('*')) # def myfun(func, string): # func(string) # myfu...
11c4cfaf6b9afdb82283380dce235f924a3b1f60
khill-turbo/python-fun
/thirty-days/day8/dictionary.py
659
3.6875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math import os import random import re import sys if __name__ == '__main__': t = int(input()) inputs = [] for i in range(t*2): inputs.append(input()) # put the name and numbers into a dictionary namenumDict =...
1c532103db2d814eb3a9250454ea9abb99b94838
Suzie-to/Python_Data_Structures
/Stacks_Tuples_Sets/04.Honey.py
3,407
4.34375
4
''' Worker-bees collect nectar. When a worker-bee has found enough nectar, she returns to the hive to drop off the load. The worker-bees pass the nectar to waiting bees so they can really start the honey-making process. You will receive 3 sequences: • a sequence of integers, representing working bees, • a s...
c49e6e507f925e6992966326a33cd9f85f862252
BunnyRabbit2/BunnyAoC2019_Python
/DayCode/Day9.py
803
3.71875
4
import pathlib import itertools from AOCLibrary import IntcodeComputer def loadInputs(fileLocation): file = pathlib.Path(fileLocation) if file.exists(): return file.read_text().split(",") else: print("Day 9 input file does not exist") def solvePuzzle1(fileLocation): icp = IntcodeComput...
ba6e77c877adf7772fc2366d5c9c3c598eb5cc29
RomaSega/Py-Pandas_BCamp
/pandas_prj.py
1,675
3.65625
4
### Projeto de do módulo "Análise de Dados com Python e Pandas" do BootCamp de Data Engineer do Banco Carrefour - Digital Innovation One Informações sobre as manifestações da Ouvidoria relacionadas à pandemia de Coronavírus (COVID-19) recebidas pelo Governo do Estado de Santa Catarina, coletadas no Portal de Dados Aber...
6f623acfb96e98aa01de427048f0efd1b287f2dc
Peter-Immanuel/time-table-app-pv1
/index_counter.py
1,418
3.828125
4
''' class to count the numbers of courses in a day and returns a dict of the days and a list of their courses''' class Counter: def __init__(self,result): self.__result = result # Getter function def get(self): return self.__result # Method to count the courses in a day and ...
f4a4f5b81ee78f81a6e826ef9730d4a88ab42de1
km88469879/Minati
/appli.py
577
3.96875
4
print("Om Shanti") chus = input("select your whatever: ") list = ["plus", "minus", "multipication"] if (list[0])== chus: x = int(input("first number: ")) y = int(input("second number: ")) z = int(x +y) print(z) elif (list[1]) == chus: x = int(input("first number: ")) y = int(input("sec...
4a0145869c73a5674da2e5ef2337c5780477539c
vchan418/pythonGUI
/radio_buttons.py
1,442
3.515625
4
from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Choose your favorite movie genres" ).grid(row = 0, column = 0, sticky = W) Label(self, text = "Select ...
038112602e1479717e9419cce55304c2de2f42dc
bot-coder05/Ultimate-Calculator
/modules/release.py
1,081
3.640625
4
import webbrowser import time from modules import colors def start(): """ Allows the user to be able to view either the latest or oldest release of this project via GitHub """ while True: choice = int(input('''(1) Latest Stable Release (2) Oldest Release (3) Exit Which release would you like to v...
7219cfc418af44f2be46910acee9f1a9b9855c91
Davidjohnwilson/PythonPolys
/pypoly/polyclasses.py
15,205
4.09375
4
# coding: utf-8 from __future__ import division # Polynomial classes from math import pow from math import sqrt # General Polynomial Class class Polynomial: 'Polynomials of any type' # Empty class currently just for inheritance. # dense polynomial # We store an array with all the coefficients for every de...
688847466b0c77af6ed3553b2792faa6dd98d35a
m-artarello/Trabalho-1.2-Logica-e-Fundamentos-da-Programacao
/2.py
915
4.0625
4
# Faça um programa que, dado um conjunto de N números, determine o menor valor, o maior valor e a soma dos valores. n1 = int(input("Informe o n1: ")) n2 = int(input("Informe o n2: ")) n3 = int(input("Informe o n3: ")) if n1 > n2 and n1 > n3: print(f'{n1} é o maior número entre eles!') if n2 > n3: ...
1dd61556e8cab0eb4b9653de977dcf3db7fd67ff
shanshay/practise_str
/3seq.py
994
3.90625
4
myL_01 = input('Введите значения элементов списка через чё угодно: ').replace(';', ',').replace('/', ',').split(',') myL_02 = input('Введите значения элементов списка через чё угодно: ').replace(';', ',').replace('/', ',').split(',') print(myL_01) print(myL_02) for i in myL_02: while i in myL_01: myL_01.rem...
48e92f8983b77ab789ac0585fb9ea2c9edca0e23
kaismithereens/realpython
/pages 0-100/doubles.py
94
3.515625
4
def doubles(number): for i in range(1, 4): number = number * 2 print (number) doubles(2)
c8d81874e2b81645ca039ade8f0cdc4f0d440a5a
kaismithereens/realpython
/pages 0-100/lists.py
1,037
3.8125
4
colors = ["red", "green", "burnt sienna", "blue"] scores = [10, 8, 9, -2, 9] my_list = ["one", 2, 3.0] print(colors[2]) print(my_list[0]) print(scores[0:2]) print(colors) colors[0] = "burgundy" colors[2] = "electric indigo" print(colors) animals = [] animals.append("lion") animals.append("tiger") animals.append("do...