blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
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))
5110936e39117ad59aabf0a69b03f11627b43def
The-Riz5-Iz6-Wiz4/PythonExercise1
/RunwayLengthRizky.py
315
3.890625
4
#input, v for velocity, a for acceleration v = float(input("Enter the plane's take off speed in m/s: ")) a = float(input("Enter the plane's acceleration in m/s^2: ")) #Formula for min runway length Runway = (v**2)/(2*a) #Output print("The minimum runway length for this airplane is", round(Runway, 4), "meters")
a3ae007c55ee2cfe220cd9094b4eaa38822ded38
CountTheSevens/dailyProgrammerChallenges
/challenge001_easy.py
803
4.125
4
#https://www.reddit.com/r/dailyprogrammer/comments/pih8x/easy_challenge_1/ # #create a program that will ask the users name, age, and reddit username. have it tell them the information back, #in the format: your name is (blank), you are (blank) years old, and your username is (blank) #for extra credit, have the program...
d23e945fb14965f2d07e327149378f79389e26bc
emanuele1234/esercitazione-22-03-2020
/main.py
364
3.953125
4
nome=input('inserisci il tuo nome ' ) età= input('inserisci la tua età ') DoveVivi=input('inserisci la città in cui abiti ') Fam=input('inserisci il numero di persone nella tua famiglia ') print(" ciao " + nome + " hai " + età+ " anni " + " vivi a " + DoveVivi + " nella tua famiglia siete " + Fam ) x=10 b=4 for i in ...
2b9725c92b14019c5dbf3add29d24f99c37c0554
ramneekc/Python-practice
/Prime_Factors.py
480
4.09375
4
#Function to find prime factors of a number def prime_factors(x): number =2 arr = list() while (number <= x): if (x % number) == 0: #Checks if remainder is 0 arr.append(number) #if remainder is 0, appends the number in the list x = x/number #Then keep div...
9ad6bdfc6dd78ccf4974011677b0b2d2a8e7ecab
Arsemon4ik/my_projects_OOP
/Figures(1.10.1)/Figures.py
585
3.84375
4
class Circle: def __init__(self, x=0 ,y=0 ,width=0 ,height=0): self.x = x self.y = y self.width = width self.height = height def GetInf(self): return print("Circle ({0}, {1}, {2}, {3}). ".format(self.x,self.y,self.width,self.height)) class Recktangle: def __ini...
748b1fc72ef44444603c1ddb5d523361b2fef57d
joedave1/python
/permutethecollectionofnumbers.py
345
3.890625
4
def permutethenumber(nums): res_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) res_perms = new_perms return res_perms a = [1,2,3] print("before permutation: ",a) print("after permutations:...
7230422542419f317702d1ccd90bca72f6271c63
joedave1/python
/dletionofdictionary.py
127
3.609375
4
d={"red":10,"blue":34} if "red" in d: del d["red"] print(d)d={"red":10,"blue":34} if "red" in d: del d["red"] print(d)
fec114dd44a3b0725fed2699e1bf3b311969e1ab
joedave1/python
/patternreverse.py
211
3.734375
4
def pattern(n): for i in range(0,n): for k in range(n,i,-1): print(" ",end="") for j in range (0,i+1): print("*",end="") print("\r") n=int(input()) pattern(n)
0ac9dce99d8fa19c1b685d6b29ac8dab23176d40
dmsmiley/Python_FunProjects
/higher-lower_guessing_game.py
869
4.09375
4
#creating guessing game from 1-100. computer tells user if the num is higher or lower. congrats message when correct guess. print out num of guesses. allow users to restart import random import sys def end_game(): print("\nThank you for playing!") print("Good bye!") print(input("Press ENTER to exit")) ...
64db6b4bc1cbdbbd32f0ff61f7ccc9b555a93f62
pillieshwar/heaven
/dict_of_bdays.py
768
4.03125
4
#!/usr/bin/python # -*- coding: utf-8 -*- from datetime import date from datetime import datetime def dict_of_bdays(): today = date.today() d1 = today.strftime("%d/%m") dict = { '17/07': 'Eshwar', '01/03': 'Devi', '04/11': 'Nana', '02/06': 'Amma', '04/09': 'Krishna',...
199cc666d97a3fdc6e1afc98ec06c33f005ae051
iSkylake/Algorithms
/Tree/ValidBST.py
701
4.25
4
# Create a function that return True if the Binary Tree is a BST or False if it isn't a BST class Node: def __init__(self, val): self.val = val self.left = None self.right = None def valid_BST(root): inorder = [] def traverse(node): nonlocal inorder if not node: return traverse(node.left) inorder....
7c6895415c7f493062c06626e567fa32c3e66928
iSkylake/Algorithms
/Array/Merge2Array.py
735
4.15625
4
# Given two sorted arrays, merge them into one sorted array # Example: # [1, 2, 5, 7], [3, 4, 9] => [1, 2, 3, 4, 5, 7, 9] # Suggestion: # Time: O(n+m) # Space: O(n+m) from nose.tools import assert_equal def merge_2_array(arr1, arr2): result = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= ...
4c06aaff66f7cd2dfd918d4249988da2375ec831
iSkylake/Algorithms
/Array/DynamicArray.py
641
3.609375
4
class Dynamic_Array: def __init__(self): self.array = [None for i in range(2)] self.capacity = 2 self.fill = 0 def incrementSize(self): tempArray = self.array self.capacity *= 2 self.array = [None for i in range(self.capacity)] for i in range(self.fill): self.array[i] = tempArray[i] def push(self,...
92803502bd1d37d5c73015816ba141e760938491
iSkylake/Algorithms
/Linked List/LinkedListReverse.py
842
4.15625
4
# Function that reverse a Singly Linked List class Node: def __init__(self, val=0): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, val): new_node = Node(val) if self.length == 0: self.head = new_node else:...
54cbfa4a99036b2435dd5568eca342d1a7a972a4
iSkylake/Algorithms
/Array/LongestPalindrome.py
1,542
3.921875
4
# Given a string, determine the longest substring palindrome # Example: # "OnlyBananaIsAlowed" => 5 # Suggestion: # Time: O(n^2) # Space: O(n) from nose.tools import assert_equal # def longestPalindrome(n, s): # max_lenght = 0 # for i in range(n): # left = i # right = i + 1 # count = 0 # while left >= 0 ...
bfbbd4597dc0bd440c79c7caacf6b8a9da719db3
iSkylake/Algorithms
/Array/IslandCoordinate.py
725
3.765625
4
matrix = [ [0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 1, 1], [0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 0], ] def islandCoordinate(matrix): coordinates = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0: if i == 0 and j == 0 or i == 0 and matrix[i][j-1] == 1 o...
7b96cb85af8b54357dc5a1a134016d6e34b1430d
NAruneshwar/SSW810
/HW08_Arun_Nalluri.py
3,480
3.59375
4
import os import datetime from prettytable import PrettyTable def date_arithmetic(): """ This function performs date Operations""" date1 = "Feb 27, 2000" dt1 = datetime.datetime.strptime(date1,"%b %d, %Y") #changing the date format into python date dt2 = dt1 + datetime.timedelta(days=3) date2 ...
670c181474a898dedcab7c157a324d51e811a9a8
NAruneshwar/SSW810
/HW04_Arun_Nalluri.py
4,989
4.21875
4
import unittest def GCD(x,y): """Takes two inputs and returns the Greatest common divisor and returns it""" while(y): x, y = y, x % y return x class Fraction: """Class Fraction creates and stores variables while also doing operations with fractions""" def __init__(self,numerator,d...
82a0de9056535e13b6096bf799a206446410dc6d
verronique/git-repo
/lesson1_normal.py
3,288
3.75
4
#__author__ = Veronika Zelenkevich # Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа. # Например, дается x = 58375. # Нужно вывести максимальную цифру в данном числе, т.е. 8. # Подразумевается, что мы не знаем это число заранее. # Число приходит в виде целого беззнакового. # Подск...
9fa9a917c2e1b2087edd8e93461fa62b780e32d0
annafawn/CSC231---Introduction-to-Data-Structures
/Lab 02 - General Python and Classes/GeneratingPolygons.py
1,201
3.703125
4
import math, csv class RegularPolygon: def __init__(self, num_sides,side_length): self.num_sides = int(num_sides) self.side_length = float(side_length) def compute_perimeter(self): return round(self.num_sides * self.side_length, 2) class EquilaterialTriangle(RegularPolygon): def ge...