blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
dfc14297ca445802ff7bedce07bebaecf903231c
Beebkips/UWTCodingDojo
/Beginner - Python, Pygame/Lesson 1 - My first game/mygame.py
1,691
3.859375
4
""" One step movement of ball object """ import pygame pygame.init() run = True # background screen = pygame.display.set_mode((640,480)) screenrect = screen.get_rect() background = pygame.Surface(screen.get_size()) background.fill((255,255,255)) background = background.convert() # ball ballsurface = pygame.Surface(...
373bbd7975453f2177a1959128af6bb066437440
FaridWaid/sms4-kuliah-komputasinumerik
/simpson13.py
702
4.0625
4
# Mendefinisikan fungsi agar menjadi integral def f(x): return 1/(1 + x**2) def simpson(a,b,n): # mencari nilai h h = (b - a) / n # Mencari jumlah sementara integrasi = f(a) + f(b) for i in range(1,n): k = a + i*h if i%2 == 0: integrasi = integras...
72554c4c493e46952747b4efa7ce8b8578f6e436
ParkerCM/csci1133-python
/lab4.py
2,478
3.5625
4
import turtle import random def mul(a, b): count = 0 product = 0 if a < b: limit = a num = b else: limit = b num = a while count < limit: product += num count += 1 print(product) def race(): def distance(): return random.randint(1, 15...
dc3e6a8b1df43a62c035a38c49e86d37ad07a898
Ast3risk-ops/My-Stuff
/list_input.py
195
3.859375
4
grocery = [] while True: item = input("What item would you like to add to your list? > ") grocery.append(item) if item == "": grocery.remove(item) break print(grocery)
713009979001d667357fbc357a84e78c74b51ba2
Cassidyyan/sorting-_algirithms
/merge_sort.py
1,376
4.5
4
# merge sort algorithm # divide and conquer algorithm, once broken down, compares indexes and merges back into one array # recursive function, calls itself to keep dividing itself till size becomes one def merge_sort(arr): # this whole chunk breaks down the array if len(arr) > 1: # finds the mid of the a...
8e6ffaab5667566004c127a873d6fae4cd90c768
hoshinotsuki/DataStructures_Algorithms
/interviewcake/balanced_binary_tree.py
3,366
3.96875
4
import unittest # TODO: better to use DFS as it reaches to a leaf easier than BFS def is_balanced(root): # BFS nodes = [root] children = [] min_depth = None depth = 0 while len(nodes) > 0: current = nodes.pop(0) if not min_depth: if not current.left and not current...
9ede6aece473b6ce865a8a05acde5e9f28c720ec
drylynch/garfieldtextadventure
/garfield.py
29,242
4
4
# why am i doing this """ TODO maybe do * make in pygame ? """ import os import platform import collections """ text based clone of garfield, released pc and ps2, 2004 by hip games garfield has to clean the house up cause odie fucked it or something move garfield around the house with his trusty vacuum cleaner a...
299ded98a59a3b5693d9527df8de9e4a2b7503ba
mikelitoluistro/python-scripting
/Class.py
728
3.625
4
class character: name = "Name" hp = 100 mp = 50 atk = 12 lvl = 1 characterOne = character() characterOne.name = "Miki" characterOne.hp = 150 characterOne.mp = 80 characterOne.atk = 50 characterOne.lvl = 8 characterTwo = character() characterTwo.name = "yssa" characterOne.hp = 150 ...
0f817cc81829eb1de9821697e2de5cd538ed055b
lt910702lt/python
/day02/02 作业讲解.py
907
3.84375
4
# 9题:输入12个月份,对应12种输出 mounth = input("请输入对应月份: ") if mounth == '一月': print("一月") if mounth == '二月': print("二月") if mounth == '三月': print("三月") if mounth == '四月': print("四月") if mounth == '五月': print("五月") if mounth == '六月': print("六月") if mounth == '七月': print("七月") if mounth == '八月': pri...
9bbec1ea854e21164b920c638c50610351d15656
ShaoboZhang/CS6601
/Assignment3/probability_tests.py
6,655
3.8125
4
import unittest from Assignment3.submission import * """ Contains various local tests for Assignment 3. """ class ProbabilityTests(unittest.TestCase): #Part 1a def test_network_setup(self): """Test that the power plant network has the proper number of nodes and edges.""" power_plant...
a5d9baacbfcc4aa95451e5123c8417d632f0e6a1
bijenderk82/py
/start.py
280
3.9375
4
import random num = random.randint num = random.randint(1,100) while True: print("guess a number between 1 and 100!") guess = input() i = int(guess) if i == num: print("you guess right!!!") break elif i < num: print("try higher") elif i > num: print("try lower")
b6a4bc56253c82493045d22e5f3c4aeea7d8e95e
wsapiens/PyCodeChallenge
/test/Encircle.py
1,332
3.9375
4
# !/bin/python3 import math import os import random import re import sys # # Complete the 'doesCircleExist' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING_ARRAY commands as parameter. # N = 0 E = 1 S = 2 W = 3 # N 0 # W 3 + E 1 # S 2 def doesCircleExis...
0203b4307611073fcc7d6f5ee8fa1f3b40cdfc26
peck94/LinodeProjects
/pycfg/Grammar.py
7,245
3.578125
4
import random class Rule(object): """ General rule object. Rules can be executed. """ def __init__(self): pass # execute this rule in the context of a given grammar def execute(self): pass class TextNode(Rule): """ Text nodes just return strings when executed. ...
c5e246d80d913609178a0b8a4cdabd9f91458b3e
theminer3746/2110101_Com_Prog
/String/String_P5.py
128
3.90625
4
bit = input() count = 0 for x in bit: count += int(x) if count % 2 == 0: print(bit + '0') else: print(bit + '1')
7b2eb7c75eac0a380e9896673b9278330aa54db5
hstabelin/Python-cursoC0d-r
/manipulacao_arquivos/desafio.py
984
3.875
4
import csv from urllib import request def read(url): with request.urlopen(url) as entrada: # guarda o arquivo da url na variavel entrada with open('cidades.txt', 'w') as saida: # criei o arquivo de saida e dei permissão print('Baixando CSV....') dados = entrada....
e79c322446b8ff41d76a4a5b4c9c70df16db1285
CharmSun/my-leetcode
/py/235.lowest-common-ancestor-of-a-binary-search-tree.py
779
3.765625
4
# # @lc app=leetcode id=235 lang=python3 # # [235] Lowest Common Ancestor of a Binary Search Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAnc...
297093bcf18617d725d529d7e302480361a74c84
alu-rwa-prog-1/assignment-7-code-masters
/classses_sudoku.py
1,414
4.28125
4
#Authors: Marthely237 and Sammyiel # Importing unittest to help in the class Test import unittest class Sudoku: """method init: initialize the game with n x n number of spaces in grid""" ## Instance variables # self.value = 0 # self.row = row # self.column = column # self.block = (row // ...
92e333d4da83bf9fc876ab1e4225817f6491a5bb
rahulraj9/udemy-python-bootcamp
/DAY3/bmi2.py
679
4.21875
4
height = float(input("Enter the height in m:- ")) weight = float(input("Enter the weight in kg:- ")) body_mass_index = round(weight / height ** 2) if body_mass_index < 18.5: print(f"your body mass index is {body_mass_index} and you are underweight") elif body_mass_index < 25: print(f"your body mass index is ...
4494ed25642104537112687dbeac64e133542fa8
Stevewho/Computational-Learning
/BNN/Tensorflow_NN.py
2,311
3.671875
4
''' 1. nomalize data 2. Testing data is for course submittion ''' import tensorflow as tf import numpy as np # normalize https://stackoverflow.com/questions/21030391/how-to-normalize-array-numpy def normalized_one(a, axis=-1, order=2): l2 = np.linalg.norm(a, order, axis) l2[l2==0] = 1 return a / np.expand_dims(...
b9fa0bebeb312c75277c5a2106d75ec27bcf618a
lucianoww/Python
/pybrexer0013.py
1,058
3.921875
4
''' #13) Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: a) Para homens: (72.7*h) - 58 b) Para mulheres: (62.1*h) - 44.7 ''' erro = 0 texto = '' pesoideal = 0.00 altura = 0.00 ...
febd24e1d2b430a54c3a63a1f2088c1dc23e8cf0
akoichig/Hackerrank
/WorldCodeSprint/WorldCodeSprint6_BeautifulSet.py
1,791
3.59375
4
def comm(): n=3 for d in range(n): print("\td = {}".format(d)) for x in range(1+int((n-d)/2)): y = x+d z = n-y-x print("{} {} {}".format(x, y, z)) N=1 T = [['x'], ['x', 1]] loc = [[1,1]] def L(d): T = d[0] loc = d[1] new = [[0]] newloc = [] ...
1cbd367cec132648de78b9bacec88146553c705b
WAT36/procon_work
/procon_python/src/atcoder/arc/past/A_020.py
126
3.640625
4
a,b=map(int,input().split()) if(abs(a)<abs(b)): print("Ant") elif(abs(a)>abs(b)): print("Bug") else: print("Draw")
c6b27267368339eee12117d8e626365ff1b5b452
kevynfg/estudos-geral
/estudos-python/estaciopy.py
775
4.15625
4
print("Hello World") #importar função do próprio Python import math, random, smtplib, time, tkinter #Operações matemáticas e random raizquadrada = math.sqrt(5) fatorial = math.factorial(10) print(fatorial) print(raizquadrada) print(random.randrange(20)) #gera um número aleatorio de 0 a 19 print(random.uniform(0.0, ...
d64bc83dcbfb1e546ed17914fcb3162352f08148
thespacewa1ker/2_Machine_N_jobs_problem
/job_sequence.py
2,156
3.875
4
# Here i'm solving using johnson's Algorithm #User Input : the total number of jobs jobs = int(input("Enter the Number of Jobs :")) # Here i'm solving for 2 machines and n jobs # taking user input of Machine -1 and Machine-2 machine_1 = [] machine_2 = [] # Creating the empty list to store the shortest job of m...
17b63310fd71172a49d617821b2c7b948a0157f8
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/vhyros001/question3.py
1,862
3.828125
4
"""Assignment 9 question 3 check if a sudoku grid is valid Ross van der Heyde VHYROS001 14 May 2014""" def checkRows(grid): """Checks if the rows of the grid are valid""" valid = True for i in range(9): for j in range(0, 10): if grid[i].count(str(j)) > 1: v...
980bc5c71e9273f39333377b69d7e964289c4ab3
m-amoit/Python-recap
/BuildingSkills/flowers.py
785
3.90625
4
from swampy.TurtleWorld import * from mypolygon import * world = TurtleWorld() bob = Turtle() bob.delay = 0.001 def petal(t, r, angle): ''' draw a single petal using 2 arcs t: turtle r: radius of arc angle: angle that subtends the arc ''' for i in range(2): arc(t, r, angle) lt(t, 180-angle) def flower(t,...
59d324d9ebb9b38fa56f9ce33fa7f1f716606097
eryykr/Python-Projects
/Project 2 - Noughts and Crosses/n_and_c.py
2,378
3.765625
4
import time import os #function for converting state of game into displayed output def display(state): output = (''' | | {} | {} | {} ______|______|______ | | {} | {} | {} ______|______|______ | | {} | {} | {} | | '''.form...
d88b44f90a5ea46ab6079d88a802f78978f54ce1
vstadnytskyi/auxiliary
/ubcs_auxiliary/os.py
7,258
3.78125
4
def find(topdir, name=[], exclude=[]): """A list of files found starting at 'topdir' that match the patterns given by 'name', excluding those matching the patterns given by 'exclude'. Parameters ---------- topdir (string) name (list) exclude (list) Returns ------- file_list (li...
88e961bd5ea7de5fd3060075a99cc2bb42b04014
corenel/lintcode
/algorithms/112_remove_duplicates_from_sorted_list.py
1,678
4.15625
4
""" Remove Duplicates from Sorted List ---------------------------------- Given a sorted linked list, delete all duplicates such that each element appear only once. Example 1: - Input: 1->1->2 - Output: 1->2 Example 2: - Input: 1->1->2->3->3 - Output: 1->2->3 Reference: - https://algorithm.yuanb...
f9694d4ea13ce1e7d067f829f2c1a6cec5e6db6d
Absurd1ty/week_4_problems
/min_to_visit_all.py
778
3.75
4
"""On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. You can move according to the next rules: In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit...
72040b8282790a44b6e017cf4257a196378cb8f9
dainst/cilantro
/service/utils.py
1,174
3.65625
4
import os def get_all_file_paths_from_dir(dir_path: str): """ Return a list of the paths of files in a given directory with sub-dirs. :param str dir_path: The directory to get the paths from :return: list of the file paths. """ file_list = [] for entry in os.scandir(dir_path): if ...
9368127280c27260ef3f94bf625d9010d12a2c17
ghazamu/mycode
/challenges/thursday.py
379
3.921875
4
#!/usr/bin/env python3 def sortList(list): short = 0 medium = 0 long = 0 for i in list: if len(i) < 5: short += 1 elif ((len(i) > 5) and (len(i) < 10)): medium += 1 elif (len(i) >= 10): long += 1 print ("Short: " + str(short)) print ("Medium: " + str(medium)) print ("long: " + str(long)) mylist ...
47e64fba735d30e6cedc2cc7ff8c104090c0f7ff
ammumal/-algorithmPractice
/10872 팩토리얼.py
147
3.859375
4
n = int(input()) def recursion (n) : fac = 1 if n == 1: return 1 else: return n * recursion(n-1) print(recursion(n))
fd8acd9f26ea80553099e8f0b3a682cfcd7ab962
Atuan98/Demo_py1
/Lession_6/btvn_6.py
329
3.75
4
import string def nhap(): str = input("Hay nhap chuoi de kiem tra: ") return str def is_pangram(str, alphabet): i = 0 for ky_tu in alphabet: if ky_tu in str: i += 1 if i == 26: print(f"Chuoi {str} la pangram") else: print(f"Chuoi {str} khong la pangram") b = string.ascii_lowercase a = nhap() is_pangram...
01628e740b8f827fed27a8b8546bcfc1dd278d62
Alqahybi-512/Projects4Workshop
/ATM solution/atm.py
1,632
3.828125
4
class ATM: def __init__(self, balance, bank_name): self.balance = balance self.bank_name = bank_name self.withdrawals_list = [] def withdraw(self, request): print("Welcome to " + str(self.bank_name)) print("Current balance = " + str(self.balance)) print "========...
6254903dc8dcb8c79e4435cb9882f5145fe03499
MishalKumar/Python_Assignments
/country_code.py
688
4.28125
4
# Problem statement ''' Given a Phone number in the format +91-0431-2503333 split them and store in a tuple and identify the country. ''' def countrycode(phone_number): tuplelist = tuple(phone_number.split('-')) print(tuplelist) for k, v in country_n_codes.items(): if v in tuple...
eaf5e488d89befa5ebc83a3f22908fd3ee524a10
AndersonANascimento/PythonExercicios
/desafio025.py
245
3.9375
4
# Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome NOME = 'SILVA' nome = input('Informe o nome: ') check = '' if (NOME in nome.upper()) else 'não' print('{}, {} possui {} no nome.'.format(nome, check, NOME))
d748f319ef478b80ef39cedfc23097fc438edccb
Aranccar/Code
/Solway/KRSUORIG29 BB-коды.py
3,046
3.734375
4
# Выдает Wrong Answer; пока не знаю почему name = input("") name=name.replace('[b]', '_eldiiar_[b]_eldiiar_') name=name.replace('[B]', '_eldiiar_[b]_eldiiar_') name=name.replace('[/b]', '_eldiiar_[/b]_eldiiar_') name=name.replace('[/B]', '_eldiiar_[/b]_eldiiar_') name=name.replace('[i]', '_eldiiar_[i]_eldiiar_') name=n...
c50bc86999e805641191ab1a517ea8f6ee334d20
EPkravec/python_base
/lesson_006/mastermind.py
706
3.5
4
from mastermind_engine import generate_number, valid, process print(' Ну что же сыграем в игру ') print(' ------------------------------- ') print(' Введите четырех значное число') print(' ------------------------------- ') generate_number() while True: number = input(" Введите число") if not valid(number): ...
55af13edf5fcb6fa248479c3a42a9f5737565de7
sabs773/Python
/RandomGenerator.py
417
3.921875
4
import numpy as np # arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) # print('2nd element on 1st dim: ', arr[0,0,2]) #slicing 2-D arrays # arr = np.array([1, 2, 3,4,5,6,7]) # print(arr[::2]) # arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) # print(arr[0:2,1:4]) #slicing 3-D arrays with ...
68b6263391698ca5df71f4047cb9afcaa3d58d9b
Prdcc/manim-Student-Shapers
/RealFunctions/InvertibilityIntro.py
14,237
3.625
4
from manimlib.imports import * import numpy as np def doubling_line(x): return 2*x def hidden_flat_line(x): return 0 def parabola(x): return x**2 def cubic(x): return (0.5*x)**3 def invCubic(x): x*=8 if(x >= 0): return x**(1./3.) else: return -((-x)**(1./3.)) class Cubi...
c946c230e197900cdd516033377402f440b07545
MarceloGomez92/Proyectos
/03_personal-info.py
418
3.59375
4
# -*- coding: utf-8 -*- """ Created on Mon May 4 15:02:12 2020 @author: dell """ nombre=input("Cual es tu nombre? ") print("\n") apellido=input("Cual es tu apellido? ") print("\n") lugar=input("Donde vives? ") print("\n") edad=input("Cual es tu edad? ") space=" " print("\n") print("Buenas tardes"+s...
cffa7221e9102fa5912c21a909e0f00087e12b36
grassyboulder/Quadratic-function-solver
/quadratic.py
925
3.828125
4
import math def testplot(a=-1,b=0,c=0): import matplotlib.pyplot as plt xz = [x for x in range(-10,11,1)] yz = [a*x**2+b*x+c for x in xz] oz = [0]*len(xz) plt.plot(xz,oz,'k-') plt.plot(xz,yz,'o-') plt.show() def quadratic(a,b,c): if b**2-4*a*c < 0: return "no real solu...
22d9bcc12bdb08a56a0e311324a6e23c13c037ad
NithyaBharathy/Python-beginner-code_snippets
/inputs.py
317
3.890625
4
# input a single string in python i = input("Enter input here: ") print(i) # typecast input - replace int with float, bool if required i = int(input("Enter number here: ")) print(i) # input list l=[] n= int(input("Enter number of elements: ")) for i in range(0, n): ele = int(input()) l.append(ele) print(l)
0f8fa1ace0beb8ae83bd5617afa8a19c86b8e4cf
santosli/python_datamining
/leventest.py
444
3.828125
4
s = raw_input("First string:") t = raw_input("Second string:") def lev(s,t): s,t,d=' '+s,' '+t,{} for i in xrange(len(s)): d[i,0]=i for j in xrange(len(t)): d[0,j]=j for j in xrange(1,len(t)): for i in range(1,len(s)): if s[i] == t[j]: d[i,j]=d[i-1,j-1] else: d[i,j]=min(d[i-1,j],d[i,j-1],d[i...
f108fa359155ccfe7fe0957df09ed912d0ba7fc4
DarkTyr/python_work
/python_doxygen_examples/multi_file/classA.py
1,536
3.75
4
class ClassA(): def __init__(self, instantA, instantB=0x1C): '''!@brief Creates a ClassA object This ClassX object is being used as a DoxyGen/Docstring/Python example @param instantA An integer value @param instantB An integer value with a default of 0x8BAD ''' ...
8012f76c6cf3f3d5dcbe799fb094aca32b91358e
chinnychin19/l3y-lossy-text-compression
/ngram_decoder.py
6,704
4.25
4
""" Note: An n-gram is a sequence of n words. In this training, we want to train based on n-grams. We'll match each n-gram of encodings to the original final word in the encoding Example: string: "Hello there I am a robot" encoded string: "h3o t3e i a0m a r3t" 3-gram 1: "h3o t3e i" --> i 3-gram 2: "t3e i a0m" ...
08b975612fb77f943800b1c7496c0ef8f1b3bd01
jrog20/8ball
/8ball.py
823
4.21875
4
""" File: 8ball.py Write a program to simulate a magic eight ball. The program should let the user type a yes or no question and pick a random answer from a set of 6 predetermined answers. """ import random PROMPT = "Ask a yes or no question: " def main(): question = input(PROMPT) while question != "": ...
ef5e845ae59203ee4baa4c6c760d59db294ebac3
pradeep-528/pradeep
/append_nm.py
151
4.09375
4
#!/usr/bin/python # appending names def append(): x=raw_input("enter first name:") y=raw_input("enter second name:") print x+y append()
ca2a0f68b3c8db8e57eb5f6d68123722a44c1ceb
gustanik/CNA340_Python
/turtlesWoComments.py
1,010
3.890625
4
import turtle import random wn = turtle.Screen() wn.bgcolor('lightblue') wn.title("Turtle Race") lance = turtle.Turtle() andy = turtle.Turtle() lance.color('red') andy.color('blue') lance.shape('turtle') andy.shape('turtle') andy.up() lance.up() andy.goto(-100, 20) lance.goto(-100, -20) start = turtle.Turtle() # O...
21648b4c978560ff5ee35b36d248ccfa2353234c
666sempron999/Abramyan-tasks-
/Integer(30)/9.py
411
4.0625
4
''' Integer9 ◦ . Дано трехзначное число. Используя одну операцию деления нацело, вывести первую цифру данного числа (сотни). ''' A = int(input("Введите А: ")) while A > 999 or A < 100: print(A) A = int(input("Введите А: ")) a,b = divmod(A,100) print('Новое число - ',a)
9c3de80466678b31a4e895357250f54d825207d8
RichardRuth/Python_Rectangle_Calculator
/rectangles.py
1,763
4.59375
5
#!/usr/bin/env python3 #COP2002.0M1 Programming Logic #Module 13 Project 13-1 Rectange Calculator Program #Submitted by Richard Ruth # Program obtains rectangle height and width data from user, and # and calculates and displays duration of travel, as well as estimated date of arrival and time of arrival # Rectangle...
0e72a5edc26bc7daf1aeb0f6c32ac873cf7354c6
garimasinghgryffindor/holbertonschool-machine_learning
/unsupervised_learning/0x02-hmm/2-absorbing.py
937
3.875
4
#!/usr/bin/env python3 """ Determines if a markov chain is absorbing """ import numpy as np def absorbing(P): """ Determines if a markov chain is absorbing :param P: square 2D numpy.ndarray of shape (n, n) representing the transition matrix :return: True if it is absorbing, or False on failure ...
122e4ea963bf710e9accfae8fc7a726d6a501de7
google238/coder
/jianzhioffer/二维数组中的查找.py
506
3.640625
4
# -*- coding: utf-8 -*- """ 在一个二维数组中(每个一维数组的长度相同), 每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 """ class Solution: # array 二维列表 def Find(self, target, array): for item in array: if target in item: return True return False
7cf73f2928c0ec9032b67a26a08ccf46b3664ac0
serhiistr/Python-test-telegram
/classmethod.py
1,581
4.0625
4
# Class # Название класса пишутся с большой буквы class Dog(): # __init__ специальный метод, который автоматически выполняется при создании # каждого нового экземпляра класса. Т.е. отвечает за базовый функционал, # который будет отрабатываться каждый раз при создании нашего обьекта (собака :)) # self - указывает, чт...
d3329492b3a0c76c3770ec0b4848471117bf0e37
Muthu123456789/muthukiller
/fact.py
182
4.0625
4
num = int(input()) factorial = 1 if num < 0: print("invalid") elif num == 0: print( 1) else: for i in range(1,num + 1): factorial = factorial*i print(factorial)
5d7b2839f9b27995a998c01fe32688ac8c744d66
fancent/CSC311
/A2/q3_materials/nn.py
14,405
4.5625
5
""" Instruction: In this section, you are asked to train a NN with different hyperparameters. To start with training, you need to fill in the incomplete code. There are 3 places that you need to complete: a) Backward pass equations for an affine layer (linear transformation + bias). b) Backward pass equations f...
104bd40e38b212aa8d52362d86bd06e221e5d39a
alveraboquet/Class_Runtime_Terrors
/Students/tom/Lab 10/lab_10_peaks_valleys.py
913
4.03125
4
data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] # length is 21 peak_location = 0 peak_value = 0 data_length = len(data) def peak (data, data_length): peaks = {} x = 0 while x < data_length-3: if data[x] < data[x + 1] and data[x + 1] > data[x + 2]: peaks.update({x...
866e5dc298dd20c0c1be74d10d676a53b3216632
HubblEDev1/Ejercicios-de-python
/pf_03.py
1,034
3.671875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 00:35:55 2019 @author: HiramGC 3. Given a text message containing only letters (lowercase) and spaces, write a Python program to returns the minimum click distance to produce the message. To calculate the distance, you can only move in the keyboard up, down, right and...
6ebf7fe253333f896dd6d6c7bf3f9f7a25be6d76
Jungeol/algorithm
/leetcode/easy/155_min_stack/django.py
1,039
3.796875
4
""" https://leetcode.com/problems/min-stack/ Runtime: 48 ms, faster than 99.36% of Python3 online submissions for Min Stack. Memory Usage: 16.2 MB, less than 100.00% of Python3 online submissions for Min Stack. """ class MinStack: def __init__(self): """ initialize your data structure here. ...
ded8f9ba743df9d4a77022099e4b98fb0f335cb2
sharkseba/taller-progra
/EjerciciosGuía1/ejercicio8.py
274
4.0625
4
#Escriba un algoritmo que solicite dos números y calcule la función f(x, y) = 2x + 3y2. # Entradas x = float(input('Ingrese el valor de x: ')) y = float(input('Ingrese el valor de y: ')) # Proceso resultado = 2*x + 3*y**2 # Salidas print('El resultado es',resultado)
ca999a37bbfc582c756ee59e21638daaff0d5e36
maxotar/algorithms
/tests/test_insertionSort.py
192
3.546875
4
from algorithms.insertionSort import insertionSort def test_insertionSort(): alist = [4, 6, 8, 7, 5, 1, 2, 3, 9] insertionSort(alist) assert alist == [1, 2, 3, 4, 5, 6, 7, 8, 9]
a5aace972d0792ee05e4e41204bbd28d47d45fc9
Jocelyn9090/CS1301xII_extra_ex
/RemoveCapitals.py
3,857
4.78125
5
#Write a function called remove_capitals. remove_capitals #should accept one parameter, a string. It should return a #string containing the original string with all the capital #letters removed. Everything else should be in the same #place and order as before. # #For example: # # remove_capitals("A1B2C3D") -> "123" # r...
3421fa2c157c8ac9681819a6858df7fa482ecc4a
qnadeem/solutions_to_some_programming_puzzles
/ninth/prB.py
2,565
3.890625
4
x = raw_input() while( x!= "#"): x = x.split() N = int(x[0]) A = int(x[1]) B = int(x[2]) pos = [] for i in range(N): x = raw_input() pos.append(int(x)) pos.sort() cost = 0 index = 0 #till N WIFI = [] while index != N: ...
153e8acc663f1899927b538baecc4c509a546c0f
wangyunpengbio/LeetCode
/146-LRUCache.py
1,112
3.953125
4
class LRUCache: # 自己的python 3 写法,超时 def __init__(self, capacity: int): self.queue = [] self.queuecapacity = capacity def get(self, key: int) -> int: # print("get",self.queue) curLen = len(self.queue) i = curLen - 1 while i >= 0: item = self.queue....
08f1e1f9f7d0572fbd280d61e238a9332cff095e
deinoo/python
/flyNerd/zad7_04.py
949
4.3125
4
''' Write a simple program that will execute a user-specified number of times. Each time the loop is started, it will ask for natural number and then display information: - is the number a multiple of 3? - is the number a multiple of 4 - 'Yay' if the number is divided by both 3 and 4 - display an asterisk if none of ...
a538527157c8a90292b49c45cef2bd42caf89fa7
mmveres/python05_12_2020
/ua/univer/lesson04/recursion.py
260
3.78125
4
# n! = n*(n-1)! 5! = 5*4*3*2*1 def fact_rec(n): if n==0 or n==1: return 1 return n * fact_rec(n-1) def fact_iter(n): fact = 1 for i in range(2,n+1): fact*=i return fact if __name__ == '__main__': print(fact_iter(5))
105555e6d57e3453ed6ebf96f8405e6cf231f28b
lizchow/CodeITSuisseEntryChallenge2021
/robot.py
2,257
3.65625
4
from datetime import timedelta class Robot: HOURS_PER_SHIFT = 8 BREAK_HOUR = 1 def __init__(self, standard_day, standard_night, extra_day, extra_night): self.std_day_rate = standard_day self.std_night_rate = standard_night self.extra_day_rate = extra_day self.extra_night_r...
2c15e83a07b09281f4e7fdfdccd19913153307b8
bus1029/HackerRank
/ProblemSolving/Implementation/DesignerPDFViewer.py
613
3.546875
4
#!/bin/python3 import math import os import random import re import sys # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): word = word.upper() # Using ASCII heights = [h[ord(w)-65] for w in word] # for w in word: # if height <= h[ord(w)-65]: # height =...
c1433e9aced160aad6ff8e1c6bdd929f9c16ac6b
positroncascade/StochasticTurbulenceGeneration
/updater.py
4,821
3.9375
4
# Make the code agnostic to python version # In Python 2 the print function is special and called without parenthesis # also '/' is used for integer division (5/2 == 2) while in Python 3 that # role is reserved for '//' (5/2 == 2.5 and 5//2 == 2) from __future__ import print_function,division import sys if sys.version_...
eb47f050d4a93ab710d2849648fb122ba3362370
Jthami05/Artificial-Intelligence
/Project4/population.py
1,090
3.59375
4
from Tour import Tour class Population: # passing populationSize won't change the actual population size, b/c we use populationSize() which gets the length of the tour. def __init__(self, populationSize, initialize, numCities): self.tours = [] for i in range(0, populationSize): self.tours.append(None)#*p...
f345e85a421862125d5d0a758e4397c1ca4e9746
Iigorsf/Python
/ex038.py
454
3.953125
4
#Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: #O primeiro valor é maior #O Segundo valor é maior #Não existe valor maior, os dois são iguais num= int(input("Digite um número: ")) num2= int(input("Digite outro número: ")) if num > num2: print("O primeiro valor é ...
5cdc4fe57eadb539fab1d76aa3b42906a39cff95
mengdage/practices
/monotone/next.py
924
3.59375
4
def next_smaller(nums): ns = [-1] * len(nums) stack = [] stack.append(len(nums) - 1) for i in range(len(nums) - 2, -1, -1): # pop invalid indexes while stack and nums[stack[-1]] > nums[i]: stack.pop() # check if a vlaid index exists if stack and nums[stack[...
c707d967ac3009fa72490788a7f10614feec3a2d
willwearing/cs-guided-project-graphs-ii
/src/lesson.py
2,509
3.8125
4
class GraphNode: def __init__(self, value): self.value = value self.edges = [] def __repr__(self): return f"GraphNode({repr(self.value)})" # Build this by hand here a = GraphNode("A") b = GraphNode("B") c = GraphNode("C") d = GraphNode("D") e = GraphNode("E") f = GraphNode("F") g = Gra...
0c83c9d54c0e6c8063386586dbb3d0f17217b53c
odysseus/rl_blackjack
/blackjackgame.py
8,326
4.125
4
from deck import * class Hand: """A list of cards representing a single hand in blackjack""" def __init__(self, cards=[]): """Initializes the cards list""" self._cards = cards self._soft = False def __str__(self): """The string representation of the list and contained car...
347188cbfae2505c4b0b283ce43ba29a630aa914
mangeshii/hackerrank-python-practice
/Strings/door_mat.py
978
4.21875
4
''' Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: Mat size must be N*M. (N is an odd natural number, and M is 3 times N.) The design should have 'WELCOME' written in the center. The design pattern should only use |, . and - characters. In...
09e4402734181f8e3834c373b7e9f375bb9dc217
dhrumil-shah/leetcode-python
/19-removeNthNodeFromEndOfList.py
727
3.65625
4
""" 19. Remove Nth Node From End of List """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: nodeArray = [] node = head whil...
7735804b50d69a9cba755209863a766e5bb46df3
pranavgarg/algorithms
/ik/strings/binary_search_recursion.py
432
3.875
4
''' binary search using recursion ''' def binary_search(s,t): l = len(s)-1 print find(s,t,0,l) def find(s,t, start, end): if start > end: return -1 mid = start + (end - start) / 2 if s[mid] == t: return mid elif t < s[mid]: return find(s, t, start, mid-1) else: ...
6d38c97f0dc2e4799b42a5175907ca96f8651846
mh70cz/py
/misc/pyr.py
329
3.96875
4
'''build a pyramid via recursive funcion''' def pyr_rec(height, right_shift=0): '''recursive pyramid''' if height == 1: return right_shift * " " + "*" else: line = right_shift * " " + ((height -1) * 2 + 1) * "*" return pyr_rec(height - 1, right_shift + 1) + "\n" + line print(pyr_rec...
e4a3f89debc0811970e92f94e670aefb7a44b2f8
uma-c/CodingProblemSolving
/hash/is_happy.py
1,043
4.03125
4
''' Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle w...
d755a66589c50124ce117861a6ce6ad2a7c085c2
fossabot/SchoolProjects_v2
/22_is_prime.py
633
4.15625
4
"Write a Program to show whether the entered number is prime or not" def is_prime(number:int) -> bool: # Edge Cases if number == 1: return False # loop through all numbers from 2 to number and check remainder for i in range(2, number): if number % i == 0: return False retur...
ffe4c4a614ad3ae36d02531ed69bcdb13f0d2ef5
jonstrutz11/AdventOfCode2020
/08.py
2,895
3.828125
4
"""Advent of Code - Problem 8""" from typing import List def read_instructions(filepath: str) -> List[str]: """Read instructions from file.""" with open(filepath, 'r') as infile: instructions = [line.strip() for line in infile.readlines()] return instructions class BootCode(): """Store and ...
a3f473e0dee8485f7fbf23c38f769381251a8deb
SurajPatil314/Leetcode-problems
/Binary Tree/balance_BST.py
1,269
3.984375
4
''' Given a binary search tree, return a balanced binary search tree with the same node values. A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1. If there is more than one answer, return any of them. ''' # Definition for a binary tree node. # clas...
6248dcac9712dd23122b89ec9bafdc42748a15b5
zzerr0/Neural_Network
/3neurons_layer.py
426
3.875
4
#neural network with 3 layers of neurons import numpy as np; inputs = [ 1.0, 2.0, 3.0, 2.5 ] #no. of inputs given to a Neuron weights = [ [ 0.2, 0.8, -0.5, 1 ], [ 0.5, -0.9, 0.26, -0.5 ], [ -0.26, -0.27, 0.17, 0.87 ] ] #each list of weight is for a particular neuron biases = [ 2.0, 3....
0dedf97398814068cc8b8f93d07c41525c67a46c
shakibusman/python-course
/Day2.py
2,423
3.8125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #work hours done by employees workhours = [('Johann',100),('Ben',200),('Anant',300)] # In[2]: #employee of the highest salary def eotf(wh): current_max = 0 eotm = '' for e,h in wh: if h>current_max: current_max=h eo...
f9796d98a8ffb85ee6cfb8dc4fe3451e2e4c4d2e
csal90/CSC-243
/dictPractice2.py
1,077
4.03125
4
# names() prompts users to enter names of students repeatedly until the user # presses ENTER without typing in a name, at this point this function prints out # for each name the number of times when the name has been entered. # names() # Enter a name: Valirie # Enter a name: Johnson # Enter a name: Tommy # Enter a name...
34157ee78617ce9e241e6ba5406340af3535e591
SergioKulyk/Stepic
/Математика и Python для анализа данных/4 Неделя 2 - Векторы, Матрицы/4.2 ПРАКТИКУМ - Сходство текстов (кошачья задача) в Python/4.2.1.py
376
3.953125
4
# Шаг 1.1 - открытие файла # Откройте файл text.txt и выведите его содержимое на печать. # # Sample Input: # # Text about cats # Text about Anacondas # Sample Output: # # Text about cats # Text about Anacondas with open('text.txt', 'r') as file: text = file.readlines() for line in text: print(line.strip())
f823ac1bccfa039126562b209cda9c2ac501b60b
alexmorenoec/turing-test-v2
/helper.py
2,738
3.578125
4
import re from random import random def chat_tag(display_name): return "{:<5} >> ".format(display_name) def info_message(message): return "INFO: " + message def normalize_text(text): """ Remove all punctuation and lower the text. Also, strip whitespace off the ends of the text. Args: ...
e999218da467bf8f8329c0dce841922a4f7314cf
burrelle/CS325-FinalProject
/fp.py
4,843
4.09375
4
#!/usr/bin/env python3 import sys from math import sqrt, pow import time MAX_MINUTES = 3 # make sure we received the right number of arguments if len(sys.argv) < 2: print("error, no file name specified") print("correct usage: python3 fp.py [filename.txt]") sys.exit() # this function creates an initial t...
aac74859970ef2694b17ee0a5220bc87ab7019be
lawy623/Algorithm_Interview_Prep
/Algo/Leetcode/010RegularExpressionMatching.py
781
3.84375
4
# do not waste time in hard problem class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ res = re.search(p,s) if res and res.group() == s: return True return False # ok recursion class Solution(o...
4f82d0041eca111e037aa72db9de40523a91c0c5
RAJANNITCS/Pyhton_practice
/func_extra_useful_stuff.py
199
3.5
4
# def add(a,b): # '''this function takes 2 number and return their sum''' # return a+b # print(add.__doc__) # print(len.__doc__) # print(max.__doc__) # print(sum.__doc__) print(help(len))
8a04fe87fb45732924c71a5da4792d1f051a254c
abjola/PSSP_notebook
/_build/jupyter_execute/Slurry_Adsorption.py
7,075
3.625
4
# 8. Batch Slurry Adsorption In this notes we will use an example problem to introduce material balances in slurry adsorption processes. We will consider a Batch, process configuration and then its extension to a continuous process configuration. ## 8.1 Problem Statement A water purification process is carried out v...
22bd36b96cf1017e564f7774afc46992f47f209b
Rago-Mateus/Python
/Exercicios/ex013.py
318
3.84375
4
salario = float(input('Qual o salário do funcionário?')) dissidio = float(input('Qual foi o dissídio deste ano (em decimais separado por ponto):')) salario_aumento = salario * (1+dissidio) print('O salário original do funcionário era {} e com dissídio de {} ficou {}.'.format(salario,dissidio,salario_aumento))
44acce80c1da1121f2180673d588c31466a57f6c
marketmodelbrokendown/1
/notebook/mit/allinone/student.py
2,062
3.921875
4
import datetime from dateutil.relativedelta import relativedelta class Person: def __init__(self, name): """Create a person:common attributes name and birthdate""" self.name = name # 1 fullname:firstname lastname or 2 lastname try: lastBlank = name.rindex(' ') # ' 'lastName ...
6247085684c24327a1589951c1557668ca5490cd
bmiraski/deadball
/baseball.py
2,851
3.640625
4
from player import Player import dice class Base(): """ defines the state of the bases """ def __init__(self, occupied = False): """ creates a base """ self.occupied = occupied self.runner = 0 first = Base() second = Base() third = Base() charles = Player(6, 34, "R") ...
c1f041b94ba6e2116c26d7dd81ff1c0cc27752bd
icharki/testGit
/san_antonio.py
826
4.0625
4
# -*- coding: utf8 -*- import random quotes = ["Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !", "On doit pouvoir choisir entre s'écouter parler et se faire entendre."] characters = ["alvin et les Chipmunks", "Babar", "betty boop", "calimero", "casper", "le chat potté", "Kiriko...
8d2d3cd8dfade712f9667a691883de16a4f23474
Prabhat2002/Python_based_game_begineer
/Python_Based_Game.py
2,424
4.03125
4
import random import math def guess_game(): low = int(input("Enter Lower Range:- ")) up = int(input("Enter Upper Range:- ")) random_number = random.randint(low, up) chance=round(math.log(up - low)) print("You've only " , chance , " chances to guess the integer!\n") temp=0 count = 0 while(count < chance): c...
be6b3f1dcf763edeca761b1a52f5f1d32ae73cda
PrzemyslawPiotrowski/PythonBootcamp
/kurs4/kartkowka.py
574
4
4
class Animal: def __init__(self, name, age): self.name = name self.age = age def sound(self): return "Knock Knock" animal = Animal("Turtle", 1000) print(animal.name) print(animal.age) print(animal.sound()) class Dog(Animal): def sound(self): return "How How" class Cat(A...
a32462ef7b4b353a43f74418870fe6c8b9d1af03
thekaleidoscope/PyProject
/gui.py
3,719
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 14 01:26:40 2018 @author: Parv , Yadhu """ from tkinter import * #import tkinter as Tk from MovieBooking import * def admin_window(): window = Toplevel(root) #l=Label(window,text="test") #l.pack() global id_entry,name_entry,tseats_entry,price_entry,id_rem...
56f8b0b349a9deb12ef0b21fa64038a08cc5d139
ByteCommander/AdventOfCode
/2016/aoc2016_3a.py
371
3.546875
4
# Advent Of Code 2016, day 3, part 1 # http://adventofcode.com/2016/day/3 # solution by ByteCommander, 2016-12-03 data = open("inputs/aoc2016_3.txt").read() counter = 0 for line in data.splitlines(): a, b, c = map(int, line.split()) if a + b > c and a + c > b and b + c > a: counter += 1 print("Answer:...