blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
cea6c7c20c36b2778af3140db4437752fb26704b
r3gor/codewars
/Shortest Distance to a Character2.py
385
3.859375
4
def shortest_to_char(s, c): lista=[x for x in s] for i in range(len(s)): if c == lista[i]: lista[i]=0 for i in range(len(lista)): if i == 0 or i == len(lista)-1: continue if lista[i]==0: if lista[i-1]!=0: lista[i-1]=1 if lista[i+1]!=0: lista[i+1]=1 return lista if __name__ == '__main__': print(shortest...
d197e64b0e2f00363dabec892863480a147939ea
geova-25/Fixed_Point_Library
/python_simulation_codes/fixed_point_operations.py
1,464
4.0625
4
#---------------------------------------This functions are the ones to call #---------------------------------------to make a shift of a floating Point #---------------------------------------number as a fixed point #--------------------------------------- #----------------------------------------Shift fractional right...
2c3fded3b47f97a656623a4007589774cf205d53
Safrus/WebDev2020
/PYTHON/informatics/for/3M.py
89
3.515625
4
a=int(input()) cnt=0 for i in range(a): if(int(input())==0): cnt=cnt+1 print(cnt)
37226538bccadc626023685c75ae3141eada7a37
Safrus/WebDev2020
/PYTHON/informatics/for/3I.py
178
3.59375
4
import math a=int(input()) cnt=0 for i in range(1,int(math.sqrt(a))+1): if a % i == 0: if math.sqrt(a) == i: cnt = cnt + 1 else: cnt = cnt + 2 print(cnt)
d614fd1df5ad36a1237a29c998e72af51dec2c99
ahmedbodi/ProgrammingHelp
/minmax.py
322
4.125
4
def minmax(numbers): lowest = None highest = None for number in numbers: if number < lowest or lowest is None: lowest = number if number > highest or highest is None: highest = number return lowest, highest min, max = minmax([1,2,3,4,5,6,7,8,9,10]) print(min, max...
0f441effd8f8537ea1ed97e016e6d7213ae72273
rchenhyy/whatever
/my_abs.py
539
3.828125
4
#!/usr/bin/env python def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x print my_abs(-1) print my_abs(0) print my_abs(1) # print my_abs('abc') # print my_abs(None) def my_abs2(x): if not isinstance(x, (int...
93884eaf8e4905a1ae879b82a94e0e48ab0a515f
Nuveen/Nuveen
/pierdoly.py
88
3.515625
4
x=3.2 y=4.3 if x>y: print("X jest wieksze") else: print("Y jest wieksze")
d201b4e2d4cad0ac19776e475bcd9e4eb4aac35c
RagaiAhmed/Research-Helper
/Mathematics/Combinatorics/Natural.py
1,976
3.984375
4
""" Implementation of combinatorics popular notations in natural numbers """ # For memoization with 0! = 1 , 1! = 1 FACTORIALS = {0: 1, 1: 1} #TODO EXPAND TO NON NATURAL # TODO add decorators for checking input ranges def C(n, r): """ Implements combinations where n and r are natural numbers and n>=r...
ea6964aef360b62a94a815f2c18da081c376872e
agpehlivanoglu/cs50
/ProblemSet6/readability.py
655
3.75
4
from cs50 import get_string def main(): text = get_string("Text: ") letter, spaces, sentences = 0, 0, 0 for i in text: if i.isalpha(): letter += 1 elif i.isspace(): spaces += 1 elif ord(i) == 46 or ord(i) == 33 or ord(i) == 63: sentences += 1 ...
d257bce3eb6182e125765b7294c5ad6e67fb04b6
icrescenti/Dam
/dam_python/exercices/ex3-4.py
381
3.71875
4
#Exercici 3.4 llista = ['Matemàtiques', 'Física', 'Química', 'Història', 'Llengua'] suspeses = [] i = 1 nota_usuari = 0 while ( i < len(llista) ): print("Nota de " + llista[i] + ":") nota_usuari = int(input()) if (nota_usuari < 5): suspeses.append(llista[i]) llista[i] = None i += 1 for...
2e10023a38076c7310d7532b21d0f14a32126ffa
icrescenti/Dam
/dam_python/exercices/ex3-5.py
216
3.765625
4
#Exercici 3.5 parauleta = input() comptador = 0 for c in parauleta: if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'): comptador += 1 print("La paraula compte " + str(comptador) + " vocals")
879b1551f9c0e2e49e795be7bff000d28ca556a5
alexdetrano/projectEuler
/solved/projectEuler_006.py
325
3.796875
4
def sum_of_sq(start, end): return sum([x**2 for x in range(start, end + 1)]) def sq_of_sum(start, end): return sum(range(start, end + 1))**2 start = 1 end = 100 sum_of_sq_val = sum_of_sq(start, end) sq_of_sum_val = sq_of_sum(start, end) print(sum_of_sq_val) print(sq_of_sum_val) print(sq_of_sum_val - sum_of_sq_va...
a43f9f1a65ef0f112a27e3ac6a521bb554d81e04
alexdetrano/projectEuler
/unsolved/projectEuler_019.py
993
3.984375
4
#!/usr/bin/env python """Challenge 19 You are given the following information, but you may prefer to do some research for yourself. • 1 Jan 1900 was a Monday. • Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which h...
e1f131f9e8a61312318b8404eb20a08439d69728
alexdetrano/projectEuler
/solved/projectEuler_024.py
844
3.953125
4
#!/usr/bin/env python3 import itertools ''' Problem 24 ========== A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicogr...
f59fb9d75a1200b8bcf1b4ddc6e7384d191cee51
lepisma/pleiad
/src/pleiad/pleiad.py
6,148
3.625
4
""" The Classifier -------------- - PleiadClassifier Classifier class - WordNode Node class for separate words - Word Class containing each word """ import pickle import dtw import numpy as np from profile import profiles class PleiadClassifier: """ The main word classifier class Works with Word objects Feed wor...
7e22899c704700d2d302fed476d6237c6a0ad4c8
JeonWookTae/fluent_python
/chapter2/list_in_list.py
523
4.125
4
board = [['_']*3 for _ in range(3)] print(board) board[2][1] = 'X' print(board) # [['_', '_', '_'], ['_', '_', '_'], ['_', 'X', '_']] # 참조를 가진 3개의 리스트가 생성된다. board = [['_']*3]*3 print(board) board[2][1] = 'X' print(board) # [['_', 'X', '_'], ['_', 'X', '_'], ['_', 'X', '_']] l = [1,2,3] print(id(l)) l *= 2 print(id...
e5a7f02e6d94f0c17988faa1904737d09dd76a7b
Pantoofle/food-chain-simulator
/python/Animal.py
4,180
3.71875
4
from display import Color from math import sqrt from random import randint import pygame class Animal(): def __init__(self, x, y): self.color = Color.WHITE self.x = x self.y = y self.size = 10 self.vision = 1 self.speed = 10 self.hunger = 0 self.st...
8a93d7e9df5b74c0a06a09e6088719b450ebc1fc
PPDonwhelan/Licenta
/rngtests.py
18,607
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sat May 20 12:00:27 2017 @author: MoldovanM2 """ from math import sqrt import sys import chi2stats class EmpiricalTest: """A single empirical test of a random number generator. EmpiricalTest( aGenerator, samples ) -- creates the test object run() -- generat...
239b2d672873288c80062d8b9bcca5da449aa95a
maiteandres/Curso-Python
/Ejercicios_23032018/Ej5 ist Overlap.py
1,220
3.75
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 22 16:15:25 2018 @author: 106416 """ """ Ejercicio 5:Write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Extras: Randomly gener...
98accc0af95218f7da09595824fb36e830158615
neurolabusc/Python27-for-Lazarus
/demos_lazarus/Demo04/test_script_demo04.py
425
3.921875
4
print ('Current value of var test is: ', test) test.Value = 'New value set by Python' print ('New value is:', test) print ('-----------------------------------------------------') class C: def __init__(Self, Arg): Self.Arg = Arg def __str__(Self): return '<C instance contains: ' + str(Self.Arg) + '>' print ...
fba00c66fd0a0912cc95dd76c50a0ca729d3c626
rakesh90084/practice
/listmembership.py
136
3.734375
4
students=["santhu","shika","gulshan","sandhya","arif",45,67,78] name=4 if(name in students): print("present") else: print("absent")
68f31900dae00a0c8124b26f382a4d5b72b2539c
ArbelRivitz/Four-in-a-row-game
/four_in_a_row.py
2,974
3.65625
4
############################################################# # FILE : four_in_a_row.py # WRITER : arbelr, noamiel,207904632, 314734302,Arbel Rivitz, Noa Amiel # EXERCISE : intro2cs ex12 2017-2018 # DESCRIPTION: # In this excercise we made the game four in a row. This game is moduled to different parts. There is s...
46ac593e74d82d8c6267666117410aa59a50ba45
SilasA/CIS-HW
/CIS-465-Project/main.py
894
3.859375
4
#!/usr/bin/python3 import sys from DFA import DFA def usage(): print("Usage: main.py [filename]") print("\tfilename\tthe name of the file with input strings") print("\toptions \tt - output the tokenized string") # starting point def main(): if (len(sys.argv) <= 1): usage() return f...
8b29e20ea03e912647a001ca2113500745801e1f
KimSeonBin/algo_practice
/acmicpc/10769.py
377
3.640625
4
import re sen = input() happy = 0; sad = 0 happy_reg = ':-\)'; sad_reg = ':-\(' p = re.compile(happy_reg) result = p.findall(sen) happy = len(result) p = re.compile(sad_reg) result = p.findall(sen) sad = len(result) if happy > sad: print('happy') elif happy < sad: print('sad') elif happy == 0 and sad == 0: ...
ea2cfde4b444ad790d1be13b96d311f16a133f26
ntdthanh1409/B-i-t-p-ch-ng-4
/Viết chương trình lặp giải phương trình bậc nhất n lần với các tham số nhập vào từ bàn phím.py
318
3.796875
4
import math n=int(input("n=")) a=float(input("a=")) b=float(input("b=")) for i in range(n): if a==0: if b==0: print("phương trình vô số nghiệm") else: print("phương trình vô nghiệm") else: x=-b/a print("nghiệm của phương trình =",x)
7514b01440bce0d018b75336580e4d7732edcce6
MTevangelista/learning-python
/list-of-python-exercises-brazil/sequential-structure/02.py
187
4.125
4
# Faça um Programa que peça um número e então mostre a mensagem: O número informado foi [número]. num = float(input('Informe um número: ')) print('O número informado foi: ', num)
83a4c53e87de632557d46b06cdfa433eba28c206
MTevangelista/learning-python
/list-of-python-exercises-brazil/sequential-structure/04.py
359
3.765625
4
# Faça um Programa que peça as 4 notas bimestrais e mostre a média. note1 = float(input('Informe a sua primeira nota: ')) note2 = float(input('Informe a sua segunda nota: ')) note3 = float(input('Informe a sua terceira nota: ')) note4 = float(input('Informe a sua quarta nota: ')) media = (note1 + note2 + note3 + note...
850f4e82207746deeb94cc8d53aec3d059c48eb1
MTevangelista/learning-python
/list-of-python-exercises-brazil/sequential-structure/11.py
634
4.09375
4
# Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: # - A) o produto do dobro do primeiro com metade do segundo . # - B) a soma do triplo do primeiro com o terceiro. # - C) o terceiro elevado ao cubo. nInt1 = int(input('Informe um número inteiro:\n')) nInt2 = int(input('Informe outro núm...
ae6d0c37675842f2cb50cbd78008997e37d31713
sanscore/selenium-chrome-screenshot
/src/chrome_screen/webdriver.py
9,604
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ChromeScreenshot is a wrapper class for the default Chrome webdriver which lacks the capability to take a full-page screenshot. https://bugs.chromium.org/p/chromedriver/issues/detail?id=294 """ from __future__ import ( absolute_import, division, print_function, un...
2d0296850e751d63ecace778990168ee34cbb2d5
emgrebe/Python-Pong
/pong.py
3,127
3.96875
4
import turtle # Creating window wn = turtle.Screen() # Title to game wn.title("Python Pong") # Color of background wn.bgcolor("black") # Size of window wn.setup(width=800, height=600) # Speeds up game wn.tracer(0) # SCORE score_a = 0 score_b = 0 # PADDLE A - LEFT paddle_a = turtle.Turtle() # Speed of ...
b440e4f3ba970cbc9e960483b8a6de8edfef71ce
szhou12/MachineLearning4PublicPolicy
/pa2/Read.py
572
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 12 17:38:27 2018 @author: JoshuaZhou """ import pandas as pd import os def read_data(filename): ''' Read data. Input: filename (str): file name Output: df: pandas dataframe ''' if 'csv' not in filename:...
fa050769df11502c362c3f7000dae14a0373a5c9
jbenejam7/Ith-order-statistic
/insertionsort.py
713
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 29 18:02:06 2021 @author: djwre """ import random #Function for InsertionSort def InsertionSort(A, n): #traverse through 1 to len(arr) for i in range(1, n): key = A[i] #move elements of arr [0..i-1], that are #great...
94675e6986cce683013e18ce9d169a18116ebaae
Scott3142/pyglet-boat-race
/src/main.py
528
3.515625
4
def main(): selection = input("Which tutorial would you like to run?\n\n[1] Window\n[2] Boat\n[3] Movement\n[4] Full game\n\nEnter selection: ") if selection == "1": import tut1_window tut1_window.play() elif selection == "2": import tut2_boat tut2_boat.play() elif selection == "3": import...
50e838bfda9bcfd5bb23515c4f5ef3cf5a449156
cp-helsinge/CP4-20
/game_attributes/story.py
21,331
4.03125
4
'''============================================================================ Story board The story board is a list (Array) of levels. index is 0 - number of levels. Each level consist of a list of game objects, that occur on that level. Including background, player, music etc. In short: all things that occur in ...
40dbcc88799b4028f0a46a470b479c193ad1e273
cp-helsinge/CP4-20
/game_functions/common.py
385
3.6875
4
"""============================================================================ Common function ============================================================================""" import re # CamelCase to snake_case def cc2sn(str): return re.sub(r'(?<!^)(?=[A-Z])', '_', str).lower() # snake_case to CamelCase def sn2c...
a303f4898b68383162cb27f89c6df95c2f52125a
Jimut123/rkmveri-labs
/ComputerVision/Projects/cv20_proj1/cv19_proj1/code/student_code.py
5,013
3.75
4
import numpy as np #### DO NOT IMPORT cv2 def my_imfilter(image, filter): """ Apply a filter to an image. Return the filtered image. Args - image: numpy nd-array of dim (m, n, c) - filter: numpy nd-array of dim (k, k) Returns - filtered_image: numpy nd-array of dim (m, n, c) HINTS: - You may not u...
6af3851ff3a024a5b39919ecb1fa8fb2d9f62f90
rabi-siddique/LeetCode
/Arrays/3Sum.py
1,034
3.8125
4
''' Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Example 2: I...
9a6829d0e2e6cd55e7b969674845a733a14d31d2
rabi-siddique/LeetCode
/Lists/MergeKSortedLists.py
1,581
4.4375
4
''' You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] m...
6c6c62108fbb01a68cf9c4a810d4af671bd9f7b7
rabi-siddique/LeetCode
/Lists/RemoveDuplicatesFromSortedList.py
805
3.859375
4
''' Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Input: head = [1,1,2] Output: [1,2] Input: head = [1,1,2,3,3] Output: [1,2,3] ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(sel...
cefa96e652aeacca35c67a0fb2811fa62c415fce
rabi-siddique/LeetCode
/Trees/RecoverBST.py
2,403
4
4
''' You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? Example 1: Input: root = [1,3,null...
757e649a1e33a545007df56cdb8d7c7eee4d6049
rabi-siddique/LeetCode
/Arrays/3Sum_2.py
1,756
3.84375
4
''' Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Example 2: I...
3fa710396073b333b1f7ad27831bbc339cdd38cb
rabi-siddique/LeetCode
/Trees/KthSmallestInBST.py
1,068
3.9375
4
''' Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree. Example 1: Input: root = [3,1,4,null,2], k = 1 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3 Constraints: The number of nodes in the tree is n. 1 <= k <= n <= ...
e9130d6b6600644e530356e9cad0b77587af9440
rabi-siddique/LeetCode
/Trees/DeletionInBST.py
1,723
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if root is None: retu...
7ceb46692052f1c0902ef80a20dd44b8561dff0d
rabi-siddique/LeetCode
/Lists/AddTwoNumberII.py
1,248
4.03125
4
''' You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Fo...
676a661f863758532c0ca7cabfb8cb42aa63827a
PoroTomato99/Python_Interacting_OS
/Managing_File_With_Python/create_file_csv.py
1,123
4
4
import os import csv # Create a file with data in it def create_file(filename): with open(filename, "w") as file: file.write("name,color,type\n") file.write("carnation,pink,annual\n") file.write("daffodil,yellow,perennial\n") file.write("iris,blue,perennial\n") file.write("poinsettia,red,perennia...
9224cd23b3356407fe077a79089d0bdccbe7faa8
JuaoP/trabalho1
/Ex5.py
959
3.78125
4
combustivel = str(input("Digite o tipo de combustível que você colocou:")). strip().capitalize() litro = float(input ("Digite a quantidade de litros que você colocou:")) if combustivel == "A": alcool = 1.90 custo = litro * alcool if litro <= 20: desconto1 = (custo * 3)/100 print("O desconto de ...
51ca34bc19ce84aec7c373282de5bc10b26994f9
TeamMX/mXpress
/Scripts/here_to_sample_kafka.py
878
3.578125
4
""" This script converts a single HERE csv file into a format suitable for use as an input to a kafka stream. """ import calendar import time import sys import pandas as pd def date_str_to_timestamp(date_str): return calendar.timegm(time.strptime(date_str, "%Y-%m-%d %H:%M")) def extract_telemetry(path): ...
fb76f3cf9227ee0dececf83bec22ddc54037f34a
geetimaRai/movie_trailer_website
/shapes_turtle.py
926
4.0625
4
import turtle def draw_shapes(): window = turtle.Screen() window.bgcolor("pink") draw_square("square","purple",2) draw_circle("circle", "blue", 2) draw_triangle("triangle", "red", 3) window.exitonclick() def create_turtle(shape, color, speed): newTurtle = turtle.Turtle() newTur...
47749e7e9fd4cd9dffd8ed63d49cd48f16bc2eeb
AndrewsAcheampong/Raspberry_pi_project
/intro_to_python/reverse_evens.py
119
3.609375
4
def evens(a , b): i = b while(i >= a): i -= 2 print(i) evens(10 , 20)
01c1a731a16d2885117d44e28e9c3643e7fdf6a6
AndreiCordis/Explore_US_Bikeshare_Data
/bikeshare.py
11,750
4.5
4
import time import pandas as pd # Dictionary that contains data for the three cities: Chicago, New York City, Washington CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } # This function gets the users' inputs as filters for the ...
eab56d33b10dc3ce33146a36512441c4855764d3
kana/py-monad
/maybe.py
1,339
3.625
4
#!/usr/bin/env python ''' >>> # Set up >>> import functools >>> curry = functools.partial >>> def flip(f): ... return lambda x, y: f(y, x) >>> def safe_div(dividend, divisor): ... if divisor == 0: ... return Nothing ... else: ... return Just(dividend / divisor) >>> safe_rdiv = flip(safe_div) >>> # Typica...
5c14a0578797af3c4fa90de7640486015e7a1ac9
ogerasymenko/pbc_ogerasymenko
/pbc/tools/numbers_summ.py
1,190
3.953125
4
import argparse from pbc.func_decorators import func_info @func_info def num_func(arg): """Function accept string with integers separeted by comma, and returns type list""" num_list = [] arr = [] if type(arg) == list: num_list = arg elif type(arg) == tuple: num_list = list(arg...
3b70d014952ca9765d53ec62a9b6ec117f62d0a4
lpt-tlemcen/SNFDL
/NVE-LJ-co/NVE.py
17,482
3.625
4
import math read_input = open ("NVE_input_data.txt", "r") # Ouverture du fichier "NVE_input_data.txt" pour la lecture des # données de simulation with open('NVE_input_data.txt') as f: for line in f: a = line.split() N = int(a[0]) # Nombre de part...
47df9f345a3147c9d85bf6f76aed22feea26b34a
ankoor7/Complete-Python-3-Bootcamp
/Project_2_Blackjack/deckOfCards/card_test.py
619
3.71875
4
import unittest from deckOfCards.card import Card from deckOfCards import constants class CardTest(unittest.TestCase): @classmethod def setUp(self): self.two_of_hearts = Card(constants.HEARTS, 'Two') def test_card_has_suit(self): self.assertEqual('Two', self.two_of_hearts.rank) s...
a1bb9f12950c7c8d7fafce4be8440ef122e8d5a7
VadzimPiauho/pycalc
/pycalc/poland_notation_function.py
2,193
3.59375
4
from pycalc.parse_epression import operators from pycalc.exception import MyException def poland_notation(expression_parse): """ Function of converting an expression to a reverse polish notation :param expression_parse: separated expression :return: modified expression for the reverse polish notation ...
05d9a5b6bc02a70975add629bf1ad58091599930
weingart01/ComputacionInteligentePACMAN
/P4 - java/P4_146683_158688_148574/Tagging/2/src/etique.py
2,111
3.625
4
#! /usr/bin/env python import sys import os from collections import defaultdict #Importamos los archivos a etiquetar input_file1 = sys.argv[1] entrada1 = open(input_file1, "r") input_file2 = sys.argv[2] entrada2 = open(input_file2, "r") #Importamos el archivo del Modelo de Lenguaje input_file3 = sys.argv[3] entrad...
bb621e5515ccaff68bcc6ddce300d94760ec8656
adbmd/torchcde
/example/example.py
7,138
3.921875
4
###################### # So you want to train a Neural CDE model? # Let's get started! ###################### import math import torch import torchcde ###################### # A CDE model looks like # # z_t = z_0 + \int_0^t f_\theta(z_s) dX_s # # Where X is your data and f_\theta is a neural network. So the first th...
3b320f39e67ee647b15be2c72b9aa20dd9fb2af4
zhugeshenren/InformationPlatform
/app/Extension/BaseField.py
316
3.515625
4
# 定义一个基础的Field 主要作为后期 ORM的开发,前期只是表明存在这个结构 class Field(object): def __init__(self, name, column_type): self.name = name self.column_type = column_type def __str__(self): return '<%s:%s>' % (self.__class__.__name__, self.name)
ea058deb08de668438c9cd998543c01432096637
Nie-Mand/Py4KidsWorkshops
/workshop1.py
396
4.03125
4
print("Bienvenue Dans Notre Formulaire") nom = input("Nom : ") prenom = input("Prenom : ") stars = int(input("Ton Evaluation : ")) pourquoi = input("Pourquoi tu veux nous Evalue? ") plus = input("Tu as Quelque Chose pour dire? ") nom_complet = nom + " " + prenom feedback = "Bonjour, je suis {}, je vous donne {} STAR...
142e035d92d5a82457384a9943e0bc64992b8621
MJHutchinson/PytorchPrivacy
/pytorch_privacy/optimizer/wrapper_optimizer.py
1,262
3.625
4
from abc import ABC, abstractmethod class WrapperOptimizer(ABC): """ Abstract class for wrapping up base PyTorch optimisers. This exists to allow either a standard or DP optimiser to be passed to a method or class with an identical interface, as extending the base optimisers to do differential privacy...
55478830138986cdd8bd3ba0a11356e0b42a51e2
bmapa-iscteiul/SudokuSolverV2
/GUI.py
8,190
3.515625
4
import pygame from tkinter import * from tkinter import messagebox from SudokuSolver import valid, solve from SudokuAPI import generateSudoku import time pygame.font.init() WINDOW_WIDTH = 540 WINDOW_HEIGHT = 600 SQUARE_SIZE = 60 ROWS = 9 COLS = 9 sudoku = generateSudoku() class Grid: def __init__(self, board): ...
908b6bcc6fafe6cb9c190d1e3841ab1e1a01e970
manoharp/algo
/merge_sort.py
722
4.09375
4
def merge(list1, list2): result = [] while len(list1) > 0 and len(list2) > 0: if list1[0] <= list2[0]: result.append(list1[0]) list1 = list1[1::] else: result.append(list2[0]) list2 = list2[1::] for i in (list1, list2): result.extend(i) if len(i) > 0 else '' return result def merge_sort(num_li...
55d2c65bb61b82e52e00c2f2f768399f17e78367
evanmascitti/ecol-597-programming-for-ecologists
/Python/Homework_Day4_Mascitti_problem_2.py
2,766
4.40625
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 1 21:16:35 2021 @author: evanm """ # assign raw data to variables observed_group_1_data = [1, 4, 5, 3, 1, 5, 3, 7, 2, 2] observed_group_2_data = [6, 7, 9, 3, 5, 7, 8, 10, 12] combined_data = observed_group_1_data + observed_group_2_data # define a func...
96dd44f30b3097f2ff8caa97427ec6109268ca6e
David-98/Horario
/generador.py
4,543
3.578125
4
# Función de comparación para el ordenamiento por selección. def comp(a, b): if a%2 == 0: if b%2 == 0: if a <= b: return True return False return True else: if b%2 == 0: return False if a <= b: return True return False # Ordenamiento por ...
d43fe9e9a6ead7efb44089f010ab2314bdbae924
Flykun/fluent_python
/字典和集合/字典/字典推导式.py
296
3.5625
4
''' 常用的字典推导式 ''' dial_codes = [ (86, 'China'), (91, 'India'), (1, 'US'), (62, 'Indonesia'), (55, 'Brazil') ] country_code = {country:code for code, country in dial_codes} # {'China': 86, 'India': 91, 'US': 1, 'Indonesia': 62, 'Brazil': 55} print(country_code)
271d9a7c9325b17ad3282a7277df0d799bc99668
Flykun/fluent_python
/数组/sort.py
1,468
3.65625
4
''' sorted方法与排序 ''' '''1. sorted方法''' fruits = ['grape', 'respberry', 'apple', 'banana'] print(fruits) # ['grape', 'respberry', 'apple', 'banana'] print(sorted(fruits)) # ['apple', 'banana', 'grape', 'respberry'] # ['respberry', 'grape', 'banana', 'apple'] print(sorted(fruits, reverse=True)) print(sorted(fruits, key=...
bee76b5c0a2278bf3548872db27c52b2596a79ab
obDann/project-archive
/MatrixDesign/pt2/a1.py
83,999
4.125
4
class MatrixIndexError(Exception): '''An attempt has been made to access an invalid index in this matrix''' class MatrixDimensionError(Exception): '''An attempt has been made to perform an operation on this matrix which is not valid given its dimensions''' class MatrixInvalidOperationError(Exception): ...
01fa867054336f81d03a98a3f9b489fcfa078b8a
jameswhitney/scraping
/scraping.py
1,507
3.546875
4
############################################### # This script is used to scrape a test # # website and decrypt any messages contained # # within the html of the site # ############################################### # import libraries needed to simplify the scraping process import requests im...
b33973eb0714d992fdccd08ed66588930020244e
ckubelle/SSW567-HW1
/hw01triangle.py
2,062
4.125
4
import unittest import math def classify_triangle(a,b,c): if a == b and b == c: return "Equilateral" if a == b or b == c or a == c: if int(a*a + b*b) == int(c*c): return "Right Isosceles" else: return "Isosceles" if int(a*a + b*b) == i...
5d4549072b6254a240a53e87bf50dfebd64b5d41
NorthcoteHS/10MCOD-Max-VERHOEF
/modules/u4_programming/lists/userFaves.py
599
3.8125
4
favourites = [] ratings = [] quit = input("do you want to quit? y/n ") while quit == "n": movies = input("what is one of your favortie movies? ") rating = input("how would you rate this movie out of 10? ") favourites.append(movies + " " + (rating + "/10")) ratings.append(rating + "/10") quit = input...
82be5ed80c0764390328e99950c56adcfe5f0fda
tetrapharmakon/PyEsercizi
/fibonacci.py
689
3.953125
4
#!/usr/bin/env python3 # ESERCIZIO: # implementare la funzione di fibonacci sia ricorsivamente che iterativamente # definizione ricorsiva # vorrei un analogo funzionale della definizione standard in Haskell: # | feeb :: [Integer] # | feeb = 1 : 1 : zipWith (+) feeb (tail feeb) def feeb(n): fib_list = [ a+b | a in f...
8217430edee6262ed4c0d315c7200024521664b8
D-Bits/Conversions
/tests/test_temp.py
1,530
3.828125
4
from unittest import TestCase from temperature import( fahrenheit_to_celsius, celsius_to_fahrenheit, celsius_to_kelvin, kelvin_to_celsius, fahrenheit_to_kelvin, kelvin_to_fahrenheit ) # Temperature unit tests class TempTests(TestCase): # Test that 1 degree fahrenheit = -17.22 degrees cels...
478e8daa99bfbe5e07da9629d4d6f52b12766b96
Web-Qwelcer/python3
/lib/DiscountCard.py
1,665
3.6875
4
import random from datetime import datetime as date class DiscCard: def __init__(self): self.__number = random.randint(10000000, 99999999) self.__money = 0 self.__disc = 1 self.__date = date.now().strftime("%d-%m-%Y") def buy(self, cost: float): if cost > 0: ...
61d600cedbe8787e0b899db666dbb64576598e98
wilfriedogouwole/PatternsPython
/observeur/ObservateurConcret.py
553
3.65625
4
from abc import abstractmethod from Observateur import Observateur from Sujet import Sujet from SujetConcret import SujetConcret class ObservateurConcret(Observateur): _sujet: SujetConcret _temperature:int def __init__(self, suj:Sujet): self._sujet=suj print("Creating a instance of Obs...
3908b9fc7495c30ffa85d33703c0010ef7caa8b4
bumunlim/kyupy
/src/kyupy/circuit.py
13,807
3.984375
4
"""Data structures for representing non-hierarchical gate-level circuits. The class :class:`Circuit` is a container of nodes connected by lines. A node is an instance of class :class:`Node`, and a line is an instance of class :class:`Line`. """ from collections import deque class GrowingList(list): def __setite...
cf49413033f636936cd23de0148cfa8a845adc22
UmerAhmad/Type-Snipe---Python-PyGame
/TypeSnipe.py
23,755
3.703125
4
# Umer Ahmad # January 8, 2018 # This program is a game where you can shoot ships by typing out the words on them import pygame import sys import random #Pre - Requisites for python, initalizing music usage and pygame, setting screen size and caption pygame.mixer.pre_init(44100, -16,1,512) pygame.init() pygame....
a296f3462ef51455b7c8c2efee81cee26779fd17
kumarikumari/Keras-Deep-Learning-Cookbook
/Chapter08/word2vec/helper.py
2,608
3.53125
4
from keras.utils import np_utils from keras.preprocessing.text import Tokenizer import numpy as np def to_categorical(y, num_classes=None): """Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy. # Arguments y: class vector to be converted into a...
373ecc01e393f54d7d67e3fcba648bc9bdae323f
Teresa-Rosemary/Text-Pre-Processing-in-Python
/individual_python_files/word_tokenize.py
880
4.15625
4
# coding: utf-8 import nltk from nltk import word_tokenize def word_tokenize(text): """ take string input and return list of words. use nltk.word_tokenize() to split the words. """ word_list=[] for sentences in nltk.sent_tokenize(text): for words in nltk.word_tokenize(sentences): ...
f13969f83d86d7e4c4e609776cf799629b91ca39
Ayyappan97/may14python
/chess game.py
11,807
3.546875
4
import chess class Condition: def range(x,y): return x > 8 and y > 8 def if_figure(board,x,y): return board[x][y].sl == '.' def same_team(x1,y1,x2,y2,board): if board[x1][y1].team == board[x2][y2].team: return True else: return False def s_cho...
f202520bdb3ab5101451b0e7648ec8b70f1c2fb4
andrewcampi/Maze-Pathfinding
/mousestack.py
3,644
4.15625
4
# Andrew Campi # mousestack.py # This file defines the mouse object, which contains functions to solve the maze. from MazeUnsolveableError import * from MazeStartExitError import * from pyliststack import * class Mouse(): def __init__(self): pass def find_maze_paths(self, maze, starting_row, star...
edc0b364bba650cdf7960b2ccf7ddb3515b19d66
ammarnajjar/adventofcode
/y2018/day01/day01.py
1,130
3.59375
4
import os from typing import Iterator from typing import List def split_input_by_line(input_str: str) -> List[int]: return [int(x.strip()) for x in input_str.split('\n') if x] def sum_lines(input_str: str) -> int: return sum(split_input_by_line(input_str)) def gen_input(input_list: List[int]) -> Iterator[...
60154b97d18346acc13abb79f1026e4cf07f80e0
scott-currie/data_structures_and_algorithms
/data_structures/binary_tree/binary_tree.py
1,400
4.125
4
from queue import Queue class Node(object): """""" def __init__(self, val): """""" self.val = val self.left = None self.right = None def __repr__(self): """""" return f'<Node object: val={ self.val }>' def __str__(self): """""" return ...
9964fcd07621271656f2ad95b8befd93f6546a54
scott-currie/data_structures_and_algorithms
/data_structures/stack/stack.py
1,756
4.15625
4
from .node import Node class Stack(object): """Class to implement stack functionality. It serves as a wrapper for Node objects and implements push, pop, and peek functionality. It also overrides __len__ to return a _size attribute that should be updated by any method that adds or removes nodes from th...
134ad277c30c6f24878f0e7d38c238f147196a64
scott-currie/data_structures_and_algorithms
/challenges/array_binary_search/array_binary_search.py
788
4.3125
4
def binary_search(search_list, search_key): """Find the index of a value of a key in a sorted list using a binary search algorithm. Returns the index of the value if found. Otherwise, returns -1. """ left_idx, right_idx = 0, len(search_list) - 1 # while True: while left_idx <= right_idx: ...
16f21ae65b3d5e3aba3f44decb5a1a4c556c95a5
scott-currie/data_structures_and_algorithms
/challenges/multi-bracket-validation/multi_bracket_validation.py
900
4.25
4
from stack import Stack def multi_bracket_validation(input_str): """Parse a string to determine if the grouping sequences within it are balanced. param: input_str (str) string to parse return: (boolean) True if input_str is balanced, else False """ if type(input_str) is not str: raise...
d46fc6f5940512ae2764ba93f4ad59d920ea16c4
rentheroot/Learning-Pygame
/Following-Car-Game-Tutorial/Adding-Boundries.py
2,062
4.25
4
#learning to use pygame #following this tutorial: https://pythonprogramming.net/displaying-images-pygame/?completed=/pygame-python-3-part-1-intro/ #imports import pygame #start pygame pygame.init() #store width and height vars display_width = 800 display_height = 600 #init display gameDisplay = pygame.display.set_m...
c28bbe2d6f981451c534bc7bb10a593d4ade2a20
parody-error/AdventOfCode
/day01.py
580
3.828125
4
input_path = 'input.txt' def fuel_mass(mass): return mass // 3 - 2 def total_fuel_for_mass(module_mass): total_mass = fuel_mass(module_mass) required_fuel_mass = fuel_mass(total_mass) while required_fuel_mass > 0: total_mass += required_fuel_mass required_fuel_mass = fuel_mass(requ...
8816beed5c6fca06f136e14ab7ed54bad7ca3c34
lpizarro2391/HEAD-FIRST-PYTHON
/lists1.py
298
4.0625
4
words= ["hello", "word"] print(words) car_details=["toyota","RAV4",2.2,-60807] print(car_details) odd_and_end = [[1,2,3],['a','b','c'],['one','one','three']] print(odd_and_end) word='Milliways' vowels=['a','e','i','o','u'] ./. for letter in word: if letter in vowels: print(letter)
49fe160812ab26303e82a2bead21905940f5e626
lpizarro2391/HEAD-FIRST-PYTHON
/vowels3.py
331
4.15625
4
vowels=['a','e','i','o','u'] word=input("Provide a word to searh for vowels: ") found=[] for letter in word: if letter in vowels: if letter not in found: found.append(letter) for vowel in found: print(vowel) found={} for k in sorted (found): print(k,'was found', found[k],'...
244ea6794b5d389822c2966cd16288eec23b404c
afgiel/letterpress
/src/lexicon.py
819
3.75
4
from lex_node import * START = '<START>' END = '<END>' class Lexicon: def __init__(self): self.root = LexNode(START) def add_word(self, word): curr = self.root word = word.strip() for letter in word: if curr.has_next(letter): curr = curr.get_next(letter) else: new_node = LexNode(letter) ...
643b9299a54103ac1e5c3d2ba02752815af3c31a
ThiraTheNerd/pass-locker
/credentials.py
1,329
3.71875
4
import random import string import pyperclip class Credentials(): user_accounts= [] def __init__(self,account_name,user_name,password): ''' Initializes the first instance of the credentials object ''' self.account_name = account_name self.user_name = user_name self.password = password ...
6f3e6a174dd6b3fe6d5033693ba992e1f3f47c81
Perpe74/Python
/4_obliczenia_i_algorytmy/iloczyn_skalarny.py
241
3.5625
4
a = [1, 2, 12, 4] b = [2, 4, 2, 8] def dot_product(v1, v2): if len(v1) != len(v2): raise ArithmeticError('vector lengths should match!') return sum([el[0] * el[1] for el in zip(v1, v2)]) print(dot_product(a, b))
82a1b73deef18353b9762c653feb446aaecd9d8c
Perpe74/Python
/2_praca_z_plikami/struktura_katalogu.py
617
3.6875
4
import os def print_list(directory, depth): elements_list = os.listdir(directory) for element in elements_list: full_path = os.path.join(directory, element) line = "" for i in range(depth): line += " " if os.path.isdir(full_path): print(line ...
a0e4c3feb2b27548e37c583aa5c091110329d73a
logan-ankenbrandt/LeetCode
/RemoveVowels.py
1,043
4.21875
4
def removeVowels(s: str) -> str: """ 1. Goal - Remove all vowels from a string 2. Example - Example #1 a. Input i. s = "leetcodeisacommunityforcoders" b. Output i. "ltcdscmmntyfcfgrs" - E...
e696cb31e3dd97c552b6b3206798e74a29027b0d
logan-ankenbrandt/LeetCode
/MajorityElement.py
1,072
4.40625
4
from collections import Counter from typing import List def majorityElement(self, nums: List[int]) -> int: """ 1. Goal a. Return the most frequent value in a list 2. Examples a. Example #1 - Input i. nums = [3, 2, 3] - Output i. 3 ...
1c71385f56e1db3bd351d1a50e33634a46533480
logan-ankenbrandt/LeetCode
/AllCharactersEqualOccurence.py
1,944
4.09375
4
import snoop @snoop def areOccurrencesEqual(s: str) -> bool: """ 1. Goal - Return true if all the characters in the string have the same occurences 2. Examples - Example #1 a. Input i. s = "abacbc" b. Output...
150c6c8f6e603b1ab89367e04150829b11c31df3
logan-ankenbrandt/LeetCode
/MostCommonWord.py
1,404
4.125
4
from typing import List from collections import Counter import re def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: """ 1. Goal - Return the most common word in a string that is not banned 2. Examples - Example #1 a. Input ...
441be31aa36e6c446bc891e5cb84e0ee9abdb924
logan-ankenbrandt/LeetCode
/CountSubstrings.py
1,979
4.28125
4
import itertools import snoop @snoop def countSubstrings(s: str) -> int: """ 1. Goal - Count the number of substrings that are palindromes. 2. Examples - Example #1 a. Input i. "abc" b. Output i. 3 c. Explanation ...
c4bdc5eb1225d1885b89d1d2781c66602bf2e594
EliasPeeters/primeCalc
/primeVisual.py
780
3.625
4
import matplotlib.pyplot as plt primes = [] with open('data.txt') as my_file: for line in my_file: prime = line.split('\n')[0] primes.append(int(prime)) blocklength = 1000 biggestBlock = round((primes[len(primes)-1]/blocklength)+0.49) x = [] y = [] for number in range(biggestBlock+1): x.app...
ca85a99734fa7cb447b0f852fd0f7b61f8a432fe
xprmnts/data_structures_and_algorithms
/algorithmic_toolbox/unit_1/gcd/gcd.py
198
3.859375
4
#Uses python3 def gcd(a, b): if b == 0: return a elif b == 1: return b else: return gcd(b, a % b) data = input() a, b = map(int, data.split()) print(gcd(a, b))