blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
226ceeac8256bb567d21dade909a9f24b3369e53
AlexPlatin/Grokking_Algorithms_book
/tests/test_recursive.py
764
3.5
4
import unittest from Recursive_tryings import recursive_factorial, loop_factorial, recursive_sum, recursive_max class Recursive(unittest.TestCase): def test_recursive_algorithm(self): self.assertEqual(recursive_factorial(5), 120) def test_loop_algorithm(self): self.assertEqual(loop_factorial...
0513b455aaf0f5c2289790507c7782b3465b56d3
jl532/BME547-TSHTestData
/tsh.py
6,620
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 10 20:54:03 2019 @author: Mars """ def nameParser(inputDictionary, inputString): """Splits full name string into First and Last name and parses into dict nameParser takes an input String with a full name ("First Last") and splits the string to a list of ["F...
42d43aa23b28fe2b95cf6f7063a90d465ecbbcc2
hhoangphuoc/data-structures-and-algorithms
/cracking_the_coding_interview/trees_and_graphs/linked_list.py
2,052
4.375
4
# -*- coding: UTF-8 -*- from __future__ import print_function ''' Linked list is a dynamic linear data structure where each element is represented as an object. Each element is comprised of two items - the data and the reference to next element or next node. ''' # Class to initialize a node for a linked list class...
bd22c2d7321eefbaecc25497b4fec2bcbfb651b0
chloe-wong/pythonchallenges
/AS23.py
609
3.5
4
#1 file= open("textfile.txt", "r") a = [] for line in file: a.append(line.strip('\n') a = reverse(a) for x in range(len(a)): print(a[x]) #2 file= open("textfile.txt", "r") a = [] for line in file: if "snake" in line: print(line.strip('\n') #3 with open("textfile.txt","w") as file: x = 1 fo...
9f7d9b898b8e61ba20b8a554529e2b00a1dd78a7
6ftunder/open.kattis
/py/Stacking Cups/stacking_cups.py
856
4.21875
4
cups = [] # list of cups with tuple (color, radius) for i in range(int(input())): # go through i test cases and add the cups into the cups list # if we get data as diameter color we convert it to color radius # if we get data as color raius we just enter the data as is a, b = input().split() # split...
1b531d0a6dc207cdc84528075cc60d2c97a0bb49
trivelt/academic-projects
/Python/lab3/zad3_4.py
220
3.6875
4
#!/usr/bin/python import re while(True): inp = raw_input(">>") if inp == "stop": break if re.findall(r"\D", inp): print "Nalezy podawac liczby, nie tekst!" continue x = int(inp) print x, pow(x,3)
9dff520a84aec044429e0fb6e40544ec72631ab0
Ikigai-pt/interview
/python/src/matrix/rotateMatrix.py
2,166
3.78125
4
# rotate a give nxn matrix clockwise # eg: m[5,4] = > [1,2,3,4] # [5,6,7,8] # [a,b,c,d] # [e,f,g,h] # */ # op: m[5,4] = > [e,a,5,1] # [f,b,6,2] # [g,c,7,3] # [h,d,8,4] # from random import randint def prettyP...
ea0d274b566d564a266efb7c23de78c3b3221a6d
nbiederbeck/Advent-Of-Code
/aoc/aoc12.py
1,256
3.765625
4
class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return f"<x={self.x:3d}, y={self.y:3d}, z={self.z:3d}>" def __iter__(self): for i in [self.x, self.y, self.z]: yield i class Moon: def __init__(self, po...
76438dea0f1d490dbcfae2d7206d16594d4c92c7
subhane/TP_python1
/verif.py
254
3.734375
4
def verif(nombre): if nombre % 2 == 0: print("Ce nombre est pair") elif nombre % 3 == 0: print("Ce nombre est impair, mais est multiple de 3") else: print("Ce nombre n'est ni pair ni multiple de 3") print(verif(3))
ccc3461e3e362b590796198a26b154302a8f1071
Engineervinay/Face-Recognition-Based-Attendance-System
/train.py
10,144
3.546875
4
import tkinter as tk from tkinter import Message ,Text import cv2,os import shutil import csv import numpy as np from PIL import Image, ImageTk import pandas as pd import datetime import time import tkinter.ttk as ttk import tkinter.font as font window = tk.Tk() #helv36 = tk.Font(family='Helvetica', size=36, weight='...
78248dcf33c6b1d7b01054ee809b48206b068089
rjugalde/Tareas-1-2018
/Taller/tarea taller 4.3.18.py
472
3.609375
4
#tarea taller 04/03/2018 def p1(n1,n2): x=n1 y=n2 negativo=False l1=[] l2=[] result=0 if x == 0 or y==0: print("El resultado es--> 0") else: if x<0 or y<0: negativo= True while x!=0: l1=l1+[x] l2=l2+[y] x=int(x/2) y=y*2 print(l1,l2) for i in range(0,len(l1)): if (l1[i]%2)==1: res...
ea17f7ef90efb23c55573b0fd249b0555e11d1a6
AnGela-CoDe/Task-one
/Start.py
869
4.28125
4
print("Давайте узнаем площадь данного прямоугольника!") #выводим свойство данной программы a=float(input("Введите длину прямоугольника")) #присваеваем переменной а запрашиваемое и введённое с клавиатуры дробное число b=float(input("Введите ширину прямоугольника")) #присваиваем переменной b запрашиваемое и введённое с к...
06783cb22a658db7f8323c9d188889f46b0e785e
Slothfulwave612/Coding-Problems
/Data Structure/07. Strings/08. minimum_window_substring.py
2,027
4.375
4
''' Find the smallest window in a string containing all characters of another string Given two strings string1 and string2, the task is to find the smallest substring in string1 containing all characters of string2 efficiently. Examples: Input: string = “this is a test string”, pattern = “tist” Output: Minimum windo...
2c75da7ae72d957c7b332c35234727db83788e07
Marcfeitosa/listadeexercicios
/ex050.py
377
3.75
4
"""Exercício 50 Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o""" s = 0 c = 0 for i in range(0,8): n = int(input('Digite um valor: ')) if n % 2 == 0: s += n c += 1 print('A soma de t...
a24db43644e281b46b5cd34bc68a92ee824acd52
neriphy/temperaturas
/temperatura.py
618
4
4
#Programa para convertir de Celsius a Fahrenheit o viceversa #Creado por @neriphy print("Si desea convertir Celsius a Fahrenheit introduzca 1 ") print("Si desea convertir Fahrenheit a Celsius introduzca 2 ") convertir_a = int(input()) if convertir_a == 1: grados = int(input("Introduzca los grados Celsius ")) ...
d29f423a95a6fd4ff10ae88f1a5353edfb1d6111
carrikm/Minesweeper-Python
/minesweeper.py
1,296
4.15625
4
#************************************************************************************************** # Created by Carrik McNerlin # May 5, 2021 # # This is the driver application for playing Minesweeper on an MxM grid with N mines. # Each game uses 2 boards, one to show the player and one that holds the mines and proxim...
b1b0d0fabd6849f1f5f4e59caed496ce5043237b
sudoberlin/python-DSA
/stack_queue.py/circular_queue.py
1,470
3.65625
4
# 34, 45, 67, 78, 89, 12, 23, 31 # 0, 1, 2, 3, 4, 5, 6, 7 # R F # (self.rear + 1) % self.size == self.front # 2%8 == 2 class CircularQueue: def __init__(self, size): self.size = size self.queue = [None for i in range (size)] self.front = self.rear = -1 def enqueue(se...
3ca5cd4aa56ea6fe70a5efd8aac95bc1334efc0f
AhmedAymann/Support-Vector-Regression-SVR-
/Support Vector Resgression.py
1,483
3.5
4
#importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # importing data dataset = pd.read_csv('C:/Users/My Pc/Desktop/machine learning tests/regression/Polynomial Regression/Position_Salaries.csv') x = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2:3].values """ ...
51d5a531c3f7f10d6d89312df54f46e2fbb09d4f
javiermontenegro/Python_Sorting.Algorithms
/HeapSort.py
3,081
4.09375
4
#******************************************************************** # Filename: HeapSort.py # Author: Javier Montenegro (https://javiermontenegro.github.io/) # Copyright: # Details: This code is the implementation of the heap sort algorithm. #*********************************************************************...
1a3e284728c84cb5bfaa83f12886ba491800f1c4
markedward82/pythonbootcamp
/ex18.py
881
4.5
4
#ex18 Names, Variables, Code, Function #Function do three things: #1. They name pieces of code the way variables name and numbers. #2. They take arguement the way your script take argv #3. using #1 and #2 they let you make your own "mini script" or "tiny command" #you can create a function by using the word def in p...
0bb3417bf39a7ce125632a8f353098db7a775ec1
mohitkhatri611/python-Revision-and-cp
/python programs and projects/python tricks to reduce time/output formats.py
788
3.734375
4
if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() print("{:.6f}".format(sum(student_marks.get(query_name))/len(scores))) # this wil...
503386f1465c84feef8a9f36ce552d8a5e1e3c0b
Artarin/Python-Trashbox
/fucking_fibonacci.py
383
3.71875
4
#решение авторов: #n = int(input()) #if n == 0: # print(0) #else: # a, b = 0, 1 # for i in range(2, n + 1): # a, b = b, a + b # print(b) num = int(input()) fMinusTwo = 0 fMinusOne = 1 for i in range (2,num+1): f = fMinusOne+fMinusTwo fMinusTwo = fMinusOne fMinusOne = f if num ...
2979c45d731aabb793df9540d68d5d698284a2c3
terra-namibia/python-training
/circle1.py
493
3.53125
4
# coding: UTF-8 # 三角比を使って円を描画 import matplotlib.pyplot as plt import numpy as np # 角度 th = np.arange(0, 360, 1) # 円周上の点の座標x,y (r * cos, r * sin) r = 3 # 円の半径 x = r * np.cos(np.radians(th)) + 1 # +1:円の中心 y = r * np.sin(np.radians(th)) + 2 # +2:円の中心 # graph plt.axis('equal') # x/yのメモリ単位を揃える plt.plot(x,y, color='blue')...
e098f70098de100d7272047a76cb625c524fcad6
JMSEhsan/Python_Exercises
/Asgmt4/assignmnet4_Ehsan.py
2,362
4.09375
4
print("\n","\bEhsan *** Feb. 04, 2021 *** Team IV *** Assignment Day 4 \n") #1 print("Exe.1- Division remainder of 7 over 5 = ", 7 % 5) #2 if 7 >= 5: print("Exe.2- Checked, 7 is greater than or equal to 5") else: print("Exe.2- Checked, 7 is NOT greater than or equal to 5") #3 print("Exe.3- Binary Shift \...
015e0afe60927a025a01646c23ed73a789f49dca
kylin-zhuo/data-structure-algorithms
/leetcode/python/trees/572.py
2,189
3.96875
4
""" 572. Subtree of Another Tree Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. Example 1...
3a8e2ef64cf374e63430ec23ad677730906c5c06
Yuziquan/LeetCode
/Problemset/super-egg-drop/super-egg-drop.py
3,239
3.78125
4
# @Title: 鸡蛋掉落 (Super Egg Drop) # @Author: KivenC # @Date: 2019-03-02 19:23:14 # @Runtime: 56 ms # @Memory: 13.3 MB class Solution: def superEggDrop(self, K: int, N: int) -> int: ''' 基于动态规划:假设 f {n,m} 表示 n 层楼、m 个鸡蛋时找到最高楼层的最少尝试次数。当第一个鸡蛋从第 i 层扔下,如果碎了,还剩 m-1 个鸡蛋,为确定下面楼层中的安全楼层,还需要 f {i-1,m-1} 次,找到子问题;...
f7ee27121704f23cc14f5b8d8a38ed14ae5d7e6b
CharlesRajendran/go-viral
/backend/ImproveContent/FindPostEmotionSO.py
2,319
3.5
4
import nltk import fileinput from nltk.tokenize import word_tokenize from nltk.corpus import stopwords def FindEmotionsSO(file_name): stop_words = set(stopwords.words('english')) angerSO = 0 antSO = 0 disgustSO = 0 fearSO = 0 joySO = 0 sadnessSO = 0 surpriseSO = 0 trustSO = 0 ...
d9096f4318bbf7144eb98d9e5e0103ce27ee812b
cdagnino/LearningModels
/src/models/finite_transitions_fs.py
6,663
3.53125
4
""" See Aguirregabiria & Jeon (2018), around equation (2) $V_{b_t}(I_t)$ is the value of the firm at period $t$ given current information and beliefs. The value of the firm is given by $$V_{b_t}(I_t) = max_{a_t \in A} \{ \pi(a_t, x_t) + \beta \int V_{b_{t+1}}(x_{t+1}, I_t) b_t(x_{t+1}| a_t, I_t )\; ...
ac6da67bb7824e2bf0a7c86cbf761fa9b0aa78e0
DeanDro/monopoly_game
/cards_classes/cards.py
774
3.96875
4
"""Super class for all cards in the game""" import pygame class Cards: """Name, owner and saleable will be available across all cards""" def __init__(self, name, saleable, board_loc, owner=None): self.name = name self.board_loc = board_loc self.saleable = saleable self.owner ...
146a1ded2a35ba5557d674d7215239426e2c6602
btoll/howto-algorithm
/python/array/best_time_to_buy_and_sell_stock.py
400
3.71875
4
def best_time(prices): left, right = 0, 1 max_profit = 0 while right < len(prices): # Is this profitable? if prices[right] > prices[left]: max_profit = max(max_profit, prices[right] - prices[left]) else: left = right right += 1 return max_profit ...
67aa821716774b31e77be1bc544bb43fd16a83da
TigiGln/Algo
/subparts/BWT.py
2,578
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 16 15:58:34 2021 @author: Thierry Galliano """ from sys import argv ############################################################################### def cryptage(sequence : str): """ Function to encrypt the sequence of interest """ ...
f2b290d79e727801d8b5741a911ae31a3c4f8628
eronekogin/leetcode
/2022/minimum_time_to_collect_all_apples_in_a_tree.py
1,210
3.671875
4
""" https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ """ from collections import defaultdict class Solution: def minTime( self, n: int, edges: list[list[int]], hasApple: list[bool] ) -> int: def walk(currNode: int) -> int: if cur...
54913e8fa5f44b2b2bb9eaefc8b6db3e41323c06
Aasthaengg/IBMdataset
/Python_codes/p02273/s580566466.py
794
3.640625
4
# -*- coding: utf-8 -*- import math class Point_Class: def __init__(self, x, y): self.x = x self.y = y def printPoint(self): print "%f %f" %(self.x, self.y) def koch(n, p1, p2): if n == 0: return sin60 = math.sin(math.radians(60)) cos60 = math.cos(math.radia...
545f0296e290d5e95add6ea24486ae93ef44f771
Davin-Rousseau/ICS3U-Unit4-04-Python
/break_statement_program.py
1,090
4.125
4
#!/usr/bin/env python3 # Created by: Davin Rousseau # Created on October 2019 # This program asks user to pick a number from 0-9 # and tells them if they got it right or wrong # and asks them to keep playing until they get it right import random random = random.randint(1, 9) def main(): # This function makes ...
1738621fb97fe2c32ec48cbe8fc83d57bf31fe65
ngocyen3006/learn-python
/practicepython.org/cowsBulls.py
1,170
3.9375
4
# http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html import random def cowBull(number, guess): if len(number) > len(guess): length = len(guess) else: length = len(number) cow = length bull = 0 for i in range(length): if number[i] == guess[i]: ...
74db2cb716b6061ba7af77c4ef33bb2dc6029e52
igor-correia/URI-python
/Categoria iniciante/1035.py
322
3.609375
4
i = 0 numeros = input().split() A = int(numeros[0]) B = int(numeros[1]) C = int(numeros[2]) D = int(numeros[3]) if B > C and D > A: if (C + D) > (A + B): if C >= 0 and D >= 0: if (A % 2) == 0: i = 1 if i == 1: print('Valores aceitos') else: print('Valores nao aceitos') ...
3325f82cda3f225e1d81f7dbe047aca995e48ea5
qmnguyenw/python_py4e
/geeksforgeeks/python/basic/6_13.py
3,644
3.5625
4
Gun Detection using Python-OpenCV **Prerequisites:** Python OpenCV Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. OpenCV(Open Source Computer Vision Library) is a highly optimized library with focus on Rea...
affbc929ba6de612e1499cd9221ea7bac53ddd03
KevinKnott/Coding-Review
/Month 01/Week 04/Day 03/a.py
3,372
3.671875
4
# Decode Ways: https://leetcode.com/problems/decode-ways/ # A message containing letters from A-Z can be encoded into numbers using the following mapping: # 'A' -> "1" # 'B' -> "2" # ... # 'Z' -> "26" # To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of th...
d72f3166d67b6687d091ecf3a97e05f12a1b756f
priyapriyam/practices_questions
/swap.py
291
3.984375
4
def swap(list, a, b): list[a], list[b] = list[b], list[a] return list list = ["priya","savita","priyanka","ravina"] a, b = 0, 3 print(swap(list,a,b)) float_list=[8.9,9.1,5.9,9.0,1.9] print (swap(float_list,a,b)) number_list=[4,6,7,8,6,5,5,4,8] print(swap(number_list,a,b))
d83c4ec7b43a65900a496f4ac0a4c0289548f69e
Shalom91/Level_0_coding_challenges
/task_0_10.py
443
4.125
4
def common_letters(string_one, string_two): """ prints out common letters between two strings """ common_letters_list = [] string_one, string_two = string_one.lower(), string_two.lower() for i in string_one: if i in string_two: common_letters_list.append(i) remove_dup...
0b4679f1bbf7073bca4165252d7103f83a064f15
dprelipcean/virus_propagator
/utils/binomial_expansion.py
1,423
4.125
4
import numpy as np # Python3 program to print terms of binomial # series and also calculate sum of series. # function to calculate factorial # of a number def factorial(n): f = 1 for i in range(2, n + 1): f *= i return f # Function to print the series def series(A, X, n): factors = list() ...
af25fc26c786cf845632f278cc314e76b905bbc1
Arthur31Viana/PythonExercicios
/ex060.py
359
4.03125
4
#Faça um programa que leia um número qualquer e mostre o seu fatorial. Ex: 5! = 5 x 4 x 3 x 2 x 1 = 120 n = int(input('''Digite um número para calcular seu Fatorial: ''')) c = n f = 1 print(f'Calculando {n}! = ', end='') while c > 0: print(f'{c}', end='') print(f' x ' if c > 1 else ' = ', end='') ...
21c23ae18500bfa28f5bbdad6e74262c8e53b17f
vaibhavyesalwad/Basic-Python-and-Data-Structure
/Python Data Structure/Dictionary/06_RemoveKey.py
396
4.1875
4
"""Program to remove a key from a dictionary""" dict1 = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} key = 3 # dict.pop(key) removes item with key from dictionary & returns value for key print(f'Item with {key} and value {dict1.pop(key)} removed and now dictionary is {dict1}') # alternat...
4b4fff38b31af83396b44b5e8fc213466ffda1f0
emmagrealy/BOB
/isogram.py
501
4.5625
5
def is_isogram(word): """Determine if word is an isogram""" word = list(filter(str.isalpha, word.lower())) return len(set(word)) == len(word) #the filter() method filters the given iterable with the help of a #function that tests each element in the iterable to be true or not. #Determine if a word or ph...
b05dd9b7b2bd335a00350bb2994ccc74f98cb822
thaus03/Exercicios-Python
/Aula17/AulaPrática.py
1,142
4.1875
4
# Listas lanche = ['Hambúrguer', 'Suco', 'Pizza', 'Pudim'] # Adiciona um elemento no final da lista print(f'Lista inicial: {lanche}') lanche.append('Cookie') print(f'Lista após o append: {lanche}') # Adicionar item na posição N lanche.insert(0, 'Cachorro-quente') print(f'Lista após o insert: {lanche}') ## Apagar e...
c1f8a50cbbb3e2124eb61b9be92b1f3076b8c659
vamshivarsa/tikinter_project
/billtable.py
1,438
3.53125
4
from tkinter import * import psycopg2 def submit(): conn=psycopg2.connect(dbname="vamshi",user="postgres",password="davs",host="localhost",port="5432") cur = conn.cursor() name1 = namebox.get() status1=statusbox.get() amount1=amountbox.get() paid_on1=paidbox.get() query='''insert into bill(...
ffc9412aa11275dc8c22c4457cbbbb8d7c3d6fb6
JD-Williams/Nucamp
/1-Fundamentals/assignments/wk05/solution1/guessing_game.py
8,159
4.03125
4
import random import time from textwrap import fill class OutOfBoundsError(Exception): # <- Bonus Task 1 pass #========================= # TASK 1 #========================= def guess_random_number(tries, start, stop): rnd_num = random.randint(start, stop) guesses = [] # <- Bonus Task 3 while tries...
636f5f1bab8e8d54780533e05b73a9487f48c394
samsoon984/learn
/goldenpong.py
612
3.765625
4
from datetime import date def soloXmas(plusYear=int(input("입력: "))): 변수 = 1 xmasDate, goldenSum, pongdangSum = date(2021, 12, 25), 0, 0 for i in range(0, plusYear): xmasDate = date(2021+i, 12, 25) if xmasDate.weekday() in [0, 4]: goldenSum += 1 print(xmasDate, "황금 ...
09568c7fd077b97ab381c873ea5eeca7bbd165d6
edu-athensoft/stem1401python_student
/py210628e_python1b/day11_210805/for_13.py
801
4.375
4
""" multiplication table 1 Python Program to Display the multiplication Table Required: Python for Loop Python Input, Output and Import input from keyboard: 10 Sample Result: 12 x 1 = 12 12 x 2 = 24 12 x 3 = 36 12 x 4 = 48 12 x 5 = 60 12 x 6 = 72 12 x 7 = 84 12 x 8 = 96 12 x 9 = 108 12 x 10 = 120 input from keyboa...
e67dc60949560690d5ee332a7b10b65caedbd4eb
StopDragon/CSE1017
/Assignment/숙제 #5-1.py
453
3.546875
4
# -*- coding: utf-8 -*- def searchWidestGap(list): temp = 0 position = 0 if list == []: return (0,-1) for a in range(len(list)-2): front = abs(list[a] - list[a+1]) back = abs(list[a+1] - list[a+2]) if front < back and temp < back: temp = back posit...
b4d1e68655352b3b5011dbdb7797870d1fe175c7
zhued/discrete_structures
/Program2/Program2 (UbuntuPanda's conflicted copy 2014-02-26).py
6,365
3.5625
4
# Programming Assignment 2 # Edward Zhu import itertools import time #import the graph with open ('input.txt', 'r') as data: datagraph = []; for lines in data: numbers = lines.split() #~ numbers = [int (i) for i in numbers] numbers = map(int, numbers) datagraph.append(numbers) #~ testdata = ([0, 3, 1], ...
ecb7d3fdfc0c734a800f5725e657bb71083075f8
Ashikunnabi/python_programming
/basic/_28_exceptions.py
116
3.65625
4
a = 0 b = 5 try: print(b / a) except ZeroDivisionError as e: print("Number can't be divided by zero.", e)
e824e9b87fc9eef5c5826f4b8e32e8f8aede69bb
yingthu/MySandbox
/1_tree/LC105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py
915
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] ...
ab41b9ca619044afa0d2f3e8c0765d6724aef930
rafaelperazzo/programacao-web
/moodledata/vpl_data/6/usersdata/79/2387/submittedfiles/investimento.py
699
3.921875
4
# -*- coding: utf-8 -*- from __future__ import division #COMECE SEU CODIGO AQUI #Entrada A = input('Digite seu saldo em 2016: ') #Processamento B = A*0.05 + A C = B*0.05 + B D = C*0.05 + C E = D*0.05 + D F = E*0.05 + E G = F*0.05 + F H = G*0.05 + G I = H*0.05 + H J = I*0.05 + I K = J*0.05 + J #Saída pr...
0d3d20bd5d89c642f4886d427fb75c558adbbb66
SophiaTanOfficial/Day01
/greet.py
562
4.15625
4
# name = "Sophia" # name1 = "John" # print("Good morning " + name + "!") # print("Good morning %s" %name) # print("Your name has " + str(len(name)) + " letters in it.") #str converts it to string # age = 18 # print("Hello! My name is " + name + " and I am " + str(age) + " years old.") # print("Let's see, what have we...
942b475b1608a6c7f152d1ad24f59ac7af8ecabc
carnad37/python_edu
/190117/Test02.py
130
3.671875
4
sumNum = 0 num = int(input("정수를 입력해주세요: ")) for i in range(1,(num+1),1): sumNum = sumNum + i print(sumNum)
17b51b46a8e755a4bda346eca3168108f87e8759
jdanray/leetcode
/equationsPossible.py
653
3.703125
4
# https://leetcode.com/problems/satisfiability-of-equality-equations/ class Solution(object): def reach(self, start, dest, graph): seen = {start} stack = [start] while stack: u = stack.pop() if u == dest: return True for v in graph[u]: if v not in seen: seen.add(v) stack.append(v)...
cee01be878648e10b1d7289abf073a5fd08e84af
yuyurun/nlp100-2020
/src/ch01/ans05.py
472
3.640625
4
def create_ngram(text, n=2, mode='str'): """ n-gramを作る Args: text(str) : 対象となる文 n(int) : n-gramのn mode(str) : strかword """ if mode == 'str': l = [s for s in text] else: l = [s for s in text.split(' ')] return [''.join(l[i:i+n]) for i in range(len(l) ...
8c9411679e625809a92b5e22b01f82504348a8da
JeniaJitsev/HIDA_COVID_Alpha_X_hackathon
/code_container/evaluation.py
4,780
3.671875
4
""" Simple evaluation code that can be used to evaluate a submission using cross validation. We need a common codebase for evaluating different methods. Since the data is small, we can afford to use cross validation to get an estimate on the performance with an uncertainty estimate. each submission is a class follow...
833a33a4a59bbf8e010b475790a6890c03f6ea7f
thebigshaikh/PythonPractice
/oddEven.py
197
4.0625
4
inputn=int(input("Hey will you enter a number for me? \n")) if(inputn%2==0): print("the number is even") if(inputn == 4): print("The number is 4!") else: print("Number is odd")
395ccacec3f322902281b0d95a330a627c4fa98c
IlyaTroshchynskyi/python_education_troshchynskyi
/data_structures/hash_table.py
3,226
4.15625
4
# -*- coding: utf-8 -*- """ Implements of simple HashTable. """ class Node: """ Implement simple Node with key, value, next_node """ def __init__(self, key, value, next_node=None): self.key = key self.value = value self.next = next_node def __repr__(self): ret...
e4440886371cb76036b4c803a1c89ea341d97781
mreishus/aoc
/2015/python2015/tests/test_day08.py
1,442
3.5
4
#!/usr/bin/env python3 """ Test Day08. """ import unittest from aoc.day08 import len_code, len_expand class TestDay08(unittest.TestCase): """Test Day08.""" def test_len_code(self): """Test len_code""" str1 = '""' self.assertEqual(len(str1), 2) self.assertEqual(len_code(str1),...
0fc4770edd83af02d18a97e2dc81794427101119
communitylab/data
/_build/jupyter_execute/Chapters/06/viz quantitative.py
5,143
4.53125
5
# Visualizing Quantitative Data <hr style="height:1px;border:none;color:#666;background-color:#666;" /> We generally use different types of charts to visualize quantitative (numerical) data and qualitative (ordinal or nominal) data. For quantitative data, we most often use histograms, box plots, and scatter plots. W...
18f510c84ca54dcdf7de16943d2af62f25c8c487
zhaihongle/zhaihongleck1
/00源哥代码.py/09day/4-while嵌套.py
148
3.859375
4
i = 1 while i <= 4:#排数 #print("%d排"%i) j = 1 while j <=5:#没排多少人 print("*",end = "")#* * * * * j+=1 print("")#换行 i+=1
07dd3ae68dfe021f626d71b1c1090cfe4ea5ca6a
ganlanshu/datastructure
/search2sort/binarySearch.py
1,927
3.90625
4
#coding=utf-8 def binarySearch(alist,item): """ 二分查找,alist必须是有序的,自己想的 """ low = 0 high = len(alist)-1 while low < high: mid = (low+high)/2 if item == alist[mid]: return mid elif item > alist[mid]: low = mid + 1 else: high = mid...
615f99d1a121f99a92629e6d5b2bb71b5f54172e
kwhua/nihao-
/第一阶段/基础/day02/字符串方法.py
1,958
3.578125
4
''' 字符串方法(字符串是不可变类型) 查找字符串的索引 index:从左向右,只能查到第一个元素的索引 rindex:从右向左查到的第一个元素的索引 s ='hello world' s1=s.index('o') s2 =s.rindex('o') print(s1) print(s2) s = 'hello world' x = len(s) s1 = [i for i, x in enumerate(s) if x == 'l'] prin...
c16e847c3b653ed4f09663a7daffacf8101e3093
brandonmorren/python
/C6 functions/oefFunctions/oefening 2.py
280
3.96875
4
def exchange(current_dollar_rate, Euro): return current_dollar_rate * Euro Current_dollar_rate2 = float(input("Current dollar rate (€ -> $): ")) Euro2 = float(input("Your amount in Euro: ")) print("€ " + str(Euro2) + " = $ " + str(exchange(Current_dollar_rate2, Euro2)))
56a91419e20cd9e85770c8b2a2fc559afd881056
marcelogarro/challenges
/FromTheInternet/Rotate an Array.py
481
4.09375
4
import unittest """ Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. """ n = 7 k = 3 arr = [1, 2, 3, 4, 5, 6, 7] def rotate(k, original_array): return original_array[k + 1:] + original_array[:k + 1] class TestLis...
d8c5d381172bf4e6d28caad7d992403f201fe7ea
fbessez/Schoolwork
/COMP211 - Data Structures/Merge Sort and Loop Invariants/hw3a.py
3,158
4.15625
4
def merge(xs, k, size): m = k + size n = k + 2*size i = k j = m res = [] # type: List[int] while i < m and j < n: if xs[i] <= xs[j]: # key comparison: 1 list.append(res, xs[i]) # how many times through loop? i = i + 1 ...
da71812230abdf9dd6f4467c2a25898c08f10e0c
rajinish01/Python_algorithms
/str_format.py
156
3.8125
4
age = 20 name = 'Sannith' string = '''{0} was {1} years old when he wrote this book, why is {0} playing with the python.'''.format(name,age) print (string)
b1aae22cccb22168fd4b2ccda2a0d47fc9c77c89
Shimizu-sp/5CS_AI
/03-SemanticNetwork/s13527.py
1,216
3.96875
4
# -*- coding: utf-8 -*- import sys def main(): is_a = {"鳥":'生物', "オーム":'鳥'} #is-a関係の辞書 has_a = {"生物":'呼吸',"鳥":'翼',"オーム":'モノマネ'} #has-a関係の辞書 print("何を聴きますか?オームの特技が聴きたかったら1を入力してください。オームは呼吸するか聴きたかったら2を入力してください") input_question = input('>> ') #オームの特技について if(input_question == "1"): print("オームの特技は"+has_a["オーム"]+"です...
c448034da979c65ddf33deb74d8af45afe73c864
variostudio/launchsim
/simulator/spacecalc.py
4,088
3.5
4
from simulator.combinedRocket import CombinedRocket from simulator.rocket import Rocket class SpaceCalculator: N = 10 circles = 0 r_min = 9999.0 r_max = 0.0 min_dist = 0.0 land_dist = 0.0 max_dist = 0.0 landing_speed = 0.0 config = '' def __init__(self, min_dist, max_dist, lan...
824dc9cf90f752143da1403c212ba86695196792
el-18-works/solis-octo-luminaria
/study/alislam/analyse.py
759
3.65625
4
#!/usr/local/bin/python3 import re #Check if the string starts with "The" and ends with "Spain": #help(re) m =1 LL =open("guerison.txt").readlines() #for l in open("guerison.txt") : CC =[] NN =[] for l in LL[2:] : if l[0] == '#' : continue x = re.search("^Sourate (.*) \(Chapitre (\d+)\)$", l) if x : s,n =x.group...
5ca367065cfdf4857e51970b2edf66e6d462ebde
blimon/cssi-labs
/python/labs/functions-cardio/reverseString.py
147
4.25
4
print("Welcome to Reverse String!") word = raw_input("Give me a word: ") def reverse_string(s1): print(s1[-1:-len(s1)]) reverse_string(word)
6e87e9c9ffa87c6efe66eb57e31e5559e3f006dd
likewen623/Stylometric-Analyser-PY
/.gitignore/preprocessor_29330440.py
1,185
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon May 21 19:18:43 2018 Name: Kewen Deng Student ID: 29330440 Last modified date: May 24 2018 Description: In this file, I have defined a class that will perform the basic preprocessing on each input text. This class have one instance variable which is a list that...
4761ed2260e2dc194b7309e570cc3cbda1accab9
KilburnBuilding/Leetcode
/581.py
860
3.671875
4
# -*- coding: utf-8 -*- class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ left_index = -1 right_index = -1 total_number = 0 for i in range(1, len(nums)): if nums[i - 1] > nums[i]: ...
22d80ac6dde99a19215ce799c9d1c0da080f7f67
lolotrgeek/TaskLearner
/environments/gym_desktop/gym_desktop/envs/events.py
639
3.609375
4
class KeyEvent(): """ The KeyEvent consumes a key int """ def __init__(self, key=0): self.key = key class PointerEvent(): def __init__(self, x=0, y=0, buttonmask=0, wheel=0): self.x = x self.y = y self.buttonmask = buttonmask self.wheel = wheel class Speci...
1bdab61987badd46e1ea87e494cb25b453256ed4
MollyQI3104/python_assignment
/english_braille.py
11,566
3.703125
4
from text_to_braille import * from char_to_braille import * from to_unicode import * from helpers import * import filecmp from Braille_translator.text_to_braille import file_to_braille, new_filename ENG_CAPITAL = '..\n..\n.o' ENG_NUM_END = '..\n.o\n.o' # You may want to define more global variables here ##########...
94137423adf3eb129eb0b7282797fc591a78ec75
raianyrufino/Advanced-Algorithms
/Lista 1 - Ad hoc/A - Ehab and another construction problem.py
71
3.640625
4
x = int(raw_input()) if x==1: print("-1") else: print x-x%2, 2
9b9e56586ee307c41de3fa892b8384fcbf456770
Justice0320/python_work
/ch4/4-10_to_4-12.py
1,055
4.25
4
# 4-10 Slices my_foods = ['pizza', 'falafel', 'carrot cake', 'burger', 'chips', 'curry', 'chili'] my_foods.append('cannoli') print("My favourite foods are:") print(my_foods) print("\nThe first three items in the list are:") print(my_foods[:3]) print("\nThe items from the middle of the list are:") print(my_foods[2:...
9acdf5e4f59e7f0285be86c145a409b48ae2d592
SR2k/leetcode
/first-round/475.供暖器.py
2,293
3.765625
4
# # @lc app=leetcode.cn id=475 lang=python3 # # [475] 供暖器 # # https://leetcode-cn.com/problems/heaters/description/ # # algorithms # Medium (33.01%) # Likes: 212 # Dislikes: 0 # Total Accepted: 20K # Total Submissions: 60.5K # Testcase Example: '[1,2,3]\n[2]' # # 冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。 # # 在加热器的加热...
c73d6cea0fc85fe3f099591374e35668833a8f1a
sashaobucina/interview_prep
/python/easy/missing_number.py
1,657
3.984375
4
from typing import List def missing_number(nums: List[int]) -> int: """ # 268: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. NOTE: This is my original solution. Time complexity: O(n) Space complexity: O(1) """ N = le...
cb7bb8917ce01c1e13950044a9b16a0304a97b53
aviadlevy/Intro2cs-huji-2014
/ex2/ex2_square.py
1,321
4.21875
4
#!/usr/bin/env python3 def square_printing(n): squareLen="#"*(2*n+1) #define the first and last line #set counters counter=1 counter2=0 eaZugy=1 #counter for the space between the "*" #define the second and the one before last line (only one *) line1="#"+" "*(n-counter)+"*"+" "*(n...
fdfaf5f87a887c8d983bd663d8b91cea516b325e
JoaoPedroPiotroski/Game
/game 0.2.0.py
9,622
3.78125
4
import random print("---- Você começa sua aventura ----") print(" Escolha seu personagem ") print("Você pode escolher entre : ") print("1 - O GUERREIRO que empunha espada e escudo, um personagem bastante equilibrado") print("2 - O MAGO que empunha seu cajado, dando grande quantidade de dano") print("3...
040f2c65b6ffc8d7e1d94f2fca1608f73b0f2bd5
Jeklah/ProjectEuler100
/27/quadratic_primes.py
719
3.765625
4
# project euler problem 27 # Author: Jeklah import itertools import math def is_prime(n): if n <= 1: return False return all(n % i != 0 for i in range(2, int(math.sqrt(n)) + 1)) def quadratic_primes(a, b): n = 0 while True: if is_prime(n ** 2 + a * n + b): n += 1 ...
119cddb1144b75213fa1b8e93cb85c0c7f5bd003
rfenzo/PrograAvanzada
/Curso/Ayudantias/AY05 - Funcional/AC/solucion_en_ayudantia.py
1,600
3.53125
4
from datetime import date from functools import reduce def leer_archivo(path): with open(path) as archivo: splitted = list(map(lambda l: tuple(l.split(";")), archivo)) tuplas = map(lambda t: t[0:5] + tuple(map(int, t[5:11])), splitted) return...
e68cf7c5c99d97df4dc021ba20c7a0fd01ae791b
UF-CompLing/Word-Normalization
/FromLecture.py
1,010
4.21875
4
import re TextName = 'King-James-Bible' ## ~~~~~~~~~~~~~~~~~~~~ ## START OF FUNCTIONS print('opening file\n') input_file = open('Original-Texts/' + TextName + '.txt', 'r') # the second parameter of both of these open functions is # the permission. 'r' means read-only. # # The 'Original-Texts/' part is so that i...
27fccff6186e761d375c0a588b6b4d4ac3acd4f3
sarahghanei/Euler-Project-Programming
/Problem3.py
606
4
4
# # Euler project Problem 3 # def is_prime(n): # res = True # for i in range(2, int(n ** 0.5) + 1): # if n % i == 0: # res = False # return res # # # def max_prime_factor(n): # max_prime = 0 # while n % 2 == 0: # max_prime = 2 # n /= 2 # for i in range(3, int(...
d6a5b613995b62924c65591bad59ddd57981679d
AndersonRoberto25/Python-Studies
/Lista/Trabalhando com listas/lista2.py
1,426
4.59375
5
#Criando listas numéricas #A função range() de Python facilita gerar uma série de números. for value in range(1,6): print(value) #A função range() faz Python começar a contar no primeiro valor que você lhe fornecer e parar quando atingir o segundo valor especificado. Como ele para nesse segundo valor, a saída não ...
fc2cb8401a15c002d9a218d5d71d5c6616da8325
Poppy22/coding-practice
/Leetcode/hashmap-hashset/distribute-candies.py
1,509
3.859375
4
### Set - faster, shorter class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ freq = set() for candy in candies: freq.add(candy) return min(len(freq), len(candies) // 2) ##...
e46460143f9b6075e9967e737e9e7be81d616d9c
anthonyescobar/SampleWork
/WordIndexer 12:05:2016/index.py
1,964
3.78125
4
# Do not import anything other than syand re! import sys import re # this function removes punctuation from a string. # you should use this before adding a word to the index, # so that "asdf." and "asdf" and "asdf," are considered to be # the same word. def remove_punctuation(s): return re.sub(r'[^\w\s]', '', s) a...
08b65597821f33139a38d607394dd4e9bba1d2b0
LizethAcosta/Tareas
/WSQ06.py
384
3.796875
4
# Thais Lizeth Santos Acosta # A01630056 # WSQ06 from random import randint print("Guess what number I'm thinking between 1 and 100!") a = int(input("Number: ")) x = randint(1,100) while (a != x): if (a>x): print ("I'm sorry but is to high.") else: print ("I'm so...
1a3d5f79de1e9cc3506856fb5687cb1a0f5bca7b
VVivid/python-programs
/Strings/4.py
321
3.96875
4
"""Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.""" def change_char(str1): first = str1[0] str1 = str1.replace(str1[0], '$') str1 = first + str1[1:] return str1 print(change_char('restart'))...
d2f2f411684aad65686a12f22299aeedeed23c88
AlanVek/Proyectos-Viejos-Python
/18.py
1,510
4
4
from math import pi opcion="" while opcion!="3": print ("Las opciones son: ") print ("1) Calcular perímetro.") print ("2) Calcular área.") print ("3) Salir.") opcion=input("Ingrese la opción deseada: ") if opcion=="1": print ("Las opciones son: ") print ("1) Triángulo.") print ("2) Cuadrad...
8b72d51599dd35a97724b9fe3aa694a6d3b87a9d
Biddy79/eclipse_python
/Getters_and_setters/main/__init__.py
1,170
4.125
4
from player import Player Adam = Player("Adam") #printing out all attributes of Player class print(Adam.name) print(Adam.lives) print(Adam._level) print(Adam._score) #printing out lives attribute using _get_lives method print(Adam._get_lives()) #setting number of lives using _set lives attribute Adam._set_lives(300...
07ff50d1460c98a3684f4204e9c4f7910256a018
OguzHaksever/UdemyPython3.9
/trhuty_values.py
379
4.21875
4
if 0: print("True") else: print("False") name = input("Please enter your name: ") if name: print("Hello, " + name) # isim girilmezse name(False) olur, # Çünkü boş string, if False ise # else komutu çalış...
185d8d41aaea2872197d1c15724fb44a4480ab23
avviswas/Python-CA2020
/python-week2/Task1.py
1,830
4.375
4
# 1. Create three variables in a single line and assign values to them in such a manner that each one ofthem belongs to a different data type. a, b, c = 2, 2.03, 'string' # 2.Create a variable of type complex and swap it with another variable of type integer. a = complex(1,2) b = 2 a = b print(type(a)) # 3.Swap two n...
9039e403892985b441a497682489411f75822dad
tribadboy/algorithm-homework
/week1/N叉树的层序遍历.py
650
3.71875
4
# -*-coding:utf-8 -*- from typing import List """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if root is None: return [] ...
646e69769250eb55d8a9b4a2c8976d269cb25cd0
Siddharth-22-1994/Python_Sams_lap
/Python1/Duplicate elements in list.py
109
3.765625
4
l1 = [2, 3, 4, 5, 2, 3] l1.sort() for i in range(len(l1) - 1): if l1[i] == l1[i+1]: print(l1[i])
f16e95151b101a27ebd5da1c289ff867e53fa000
taoranzhishang/Python_codes_for_learning
/study_code/Day_09/04list更新方法.py
413
3.8125
4
mylist = [1, 2, 3, 4, 5, 6] print(mylist) for i in range(len(mylist)): # 修改列表必须用索引 if mylist[i] == 2: mylist[i] = -2 print(mylist[i]) print(mylist) ''' for data in mylist:#data相当于副本,改变副本不影响list元素值,修改失败,用于读取不修改 if data==2: data=-2 print(data)#data可以改变,但元素不变 print(mylist) '''