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
a320245a767c870f70f1c21686c206b321764cf0
capncrockett/beedle_book
/Ch_09 - Simulation and Design/volleyball_compare.py
2,881
4.0625
4
# volleyball_compare.py # A program to investigate potential advantage for rally scoring or # standard scoring in a series of volleyball games. from volleyball_1 import * def print_intro(): print("\nThis program simulates volleyball games in an effort to \n" "investigate whether rally scorin...
f759d2714063a7520a42a45e4ca8b4bf58d53e37
capncrockett/beedle_book
/Ch_08 - Loop Structures and Booleans/prime_checker.py
720
4.34375
4
# prime_checker.py # A positive number n > 2 is prime if no num between 2 and # the sqrt of n (inclusive) evenly divides n. import math def prime_check(n): sqrt_n = int(math.sqrt(n)) if n > 2: if n == 3: print("3 is prime") for i in range(2, sqrt_n + 1): ...
e9543a36d3cc89e88294035db335cf273c7b037a
capncrockett/beedle_book
/Ch_05 - Sequences/average_word_len.py
998
4.3125
4
# average_word_len # Find the average word length of a sentence. def main(): print("This program finds the average word length of a sentence.") print() sentence = input("Type a sentence: ") word_count = sentence.count(' ') + 1 words = sentence.split() letter_count = 0 for ...
91c3e90eef835d01283493bb2e56c654b67e6f01
capncrockett/beedle_book
/Ch_06 - Functions/summarizer.py
204
3.546875
4
# summarizer.py def sum_list(nums): total = 0 for i in nums: total = total + i return total def test(): nums = list(range(10)) print(sum_list(nums)) test()
0105745524ada80476a7051e1f4ed779db0bcaa3
capncrockett/beedle_book
/Ch_09 - Simulation and Design/craps_1.py
1,725
3.984375
4
# craps_1.py # A program that simulates craps. from risk_battle import d6 def roll_two(): dice_1, dice_2 = d6(), d6() dice_tot = dice_1 + dice_2 # print(f"{dice_1} + {dice_2} = {dice_tot}") return dice_tot def main(): win = loss = 0 for i in range(25): natural = [7...
87cce00ae5b9ca7753f355237abc8cd65c5de284
techyshiv/Tkinter_Project
/Tkinter_Project3.py/aboutus.py
748
3.78125
4
from tkinter import * from tkinter import messagebox import sqlite3 class AboutPeople(Toplevel): def __init__(self): Toplevel.__init__(self) self.geometry('550x550+550+200') self.title('About Person') self.top=Frame(self,height=550,width=550,bg='#ffa500'...
5567d2a9a476516d799661c4fc474ed4ca935a71
CmWork/STAKCommands
/testmethodology/utils/weight_ops.py
3,483
3.921875
4
import math def allocate_weighted_list(total_count, weight_list, percentage=True, allow_fraction=False): ''' total_count is an integer value weight_list is a list of float weight values to distribute total_count percentage is True if the weight list is a list of ...
22201b34f6deb8103760cec328f5347f298af92c
edkins/bus_map
/setup/pretty_compact.py
296
3.609375
4
import json import sys data = json.load(sys.stdin) if not isinstance(data, list): raise ValueError('Expecting list') print('[') i = 0 for i in range(len(data)): string = json.dumps(data[i]) if i == len(data)-1: print(string) else: print(string + ',') print(']')
d9d04f9b8e83d2e339b512c374eeadd803b8cc82
BapeHiks/Pythonista
/coding/first-gui-.py
2,306
3.5
4
#!python2 # coding: utf-8 # Очень простой первый эксперимент по созданию GUI с использованием Pythonista # на iPad2. # шуметь при прикосновении. # внутренностей MS Windows from scene import * from random import random import sound # Базовый класс для элементов управления class Window (Layer): # Создать окно по умо...
fae153eeca5a491f9a435a2c6af09768650f72fa
LostSam423/Bash-De-Bug
/lineNos.py
920
3.53125
4
import tkinter as tk linenosfg="white" linenosbg="#101010" ## Line Numbers # Contains the line numbers on the left of text area class LineNo(tk.Canvas): ## Constructor def __init__(self, *args, **kwargs): tk.Canvas.__init__(self, *args, **kwargs) self.textwidget = None self.configure(bg=linenosbg) ## At...
d8ef08d32236a5101bf6117817f36b2db51ff962
LostSam423/Bash-De-Bug
/highlighter.py
4,794
3.578125
4
import tkinter as tk import time import yaml ## Syntax Highlighting ## Highlights certain keywords in bash, strings and numbers in distinguishable colours. This is done on each key release event. class Highlighter: ## Constructor to initiate the variables # @param text_widget The text widget in tkinter for w...
a7a921940f1cedee399c3d732f7a2cb4869979ef
DaanvanMil/INFDEV02-1_0892773
/assignment6pt3/assignment6pt3/assignment6pt3.py
367
4.25
4
x = input ("how many rows? ") printed = ("") #The printing string n = x + 1 #Make sure it is x rows becasue of the range for a in range(n): #Main for loop which prints n amount of lines for b in range(a): #For loop which adds a amount of asterisks per line printed += '*...
3efa2260198021c2ee3ffe4465a201cf9455f91c
DaanvanMil/INFDEV02-1_0892773
/Assignment41c/Assignment41c/Assignment41c.py
143
4.09375
4
number = input("Give me a negative number and I will give the absolute value: ") print "The absolute value of this number is: ", abs(number)
960163aa2628ade2341ff6a17f6c0d73ab6b33f8
qiwx2012/pythonProject
/www/test/testyield.py
350
3.609375
4
def yieldTest(n): for i in range(n): yield call(i) print('i=',i) #做一些其它事情 print('do something') print('end.') def call(i): return i*2 #使用for循环 # for i in yieldTest(5): # print(i,',') def func(): for i in range(5): yield i # f =func() for i in func(): print(i,',...
4c687faa942587e54da9a4e4cdcc491865c93b82
Billoncho/TurtelDrawsTriangle
/TurtleDrawsTriangle.py
684
4.4375
4
# TurtleDrawsTriangle.py # Billy Ridgeway # Creates a beautiful triangle. import turtle # Imports turtle library. t = turtle.Turtle() # Creates a new pen called t. t.getscreen().bgcolor("black") # Sets the background to black. t.pencolor("yellow") # Sets the pen's color...
afe126a8abe523b0d5293ecf41cff540682f4096
Sahyoun98/CS498
/assignment 2/list-1/reverse3.py
74
3.609375
4
def reverse3(nums): nums[0], nums[-1] = nums[-1], nums[0] return numss
bcfcff11b862780b080f521c70be1ef9a931887e
GrIc/trainings
/learnPythonTheHardWay/ex5.py
589
3.890625
4
# -*- coding: utf-8 -*- my_name = "Guillaume" my_age = 27 my_height = 173 # cm my_weight = 62 # kg my_eyes = "Brown" my_teeth = "quite white" my_hair = "Brown" print "Let's talk about %s." % my_name print "He's %d cm tall." % my_height print "He's %d kg heavy." % my_weight print "Actually that's not too he...
e2aceab7d1200e3deae3fd1f5023804ca93da0c6
NereoJ/Examen
/Examen2d.py
874
3.53125
4
import numpy as np import matplotlib.pyplot as plt plt.axis([-200,200,-200,200]) plt.axis('on') plt.grid(True) #Dibujar el circulo tomando como centro 0 y 0, junto a un radio de 40 r = 8*5 xc = 0 yc = 0 #puntos de inicio y final p1=0*np.pi/180 p2=360*np.pi/180 dp=(p2-p1)/100 xlast=xc+r*np.cos(p1) yla...
a19f2aa56614fa511ded29625bb7639a2923322b
rnag/aws-teams-logger
/aws_teams_logger/utils/date_util.py
576
3.71875
4
""" Utilities for interacting with dates and times. """ from datetime import datetime, timezone import pytz from ..constants import LOCAL_TZ # UTC timezone (no offset) UTC = timezone.utc # Local timezone object # # Adding this globally, in case `LOCAL_TZ` is set as an invalid time zone. local = pytz.timezone(LOCAL...
ea5205340a151e3b52d0502360e7fcfec2dbe4b7
rnag/aws-teams-logger
/aws_teams_logger/utils/decorators.py
1,809
3.625
4
""" Project-specific decorators """ import functools from datetime import timedelta from logging import Logger from typing import Optional from .time_util import preferred_clock from ..log import LOG def record_time(f=None, log_message: str = None, log_func=print): """ Decorates a function to also log its ex...
900aff3da512dde0010e8cdc2e4fcf68152b8934
loganmccaul/CSCI3104-Algorithms
/trieAssignmentKit/trieClass.py
3,403
4.0625
4
#LastName:McCaul #FirstName:Logan #Email:logan.mccaul@colorado.edu #Comments: from __future__ import print_function import sys # We will use a class called my trie node class MyTrieNode: # Initialize some fields def __init__(self, isRootNode): #The initialization below is just a suggestion. ...
dda45d6db4c7e91eafd0ad635fb913bd30ff5820
hwangpo/ce-5362-webroot
/3-Readings/PCHinR-LectureNotes/Archive-Junk/4-SVNewton/PythonScripts/WhatToSolve.py
386
3.59375
4
# external functions module name: WhatToSolve.py # import built in function for e^x, cosine from math import exp, cos, sin # Define the function def func(x): func = exp(x) - 10*cos(x) - 100 #using the name as the temp var return func # Define the derivative function def dfdx(x): # dfdx = exp(x) + 10*sin(x)...
06f22b1d1be1f76985adde59a4d00beab37a26fa
cpe202fall2018/lab0-clmendez
/planets.py
349
3.84375
4
def weight_on_planets(): weight_earth= int(input("What do you weigh on earth? ")) weight_mars= weight_earth * .38 weight_jupiter= weight_earth * 2.34 print("\nOn Mars you would weigh", weight_mars, "pounds." "\nOn Jupiter you would weigh", weight_jupiter, "pounds.") if __name__ == '__mai...
55eb79671bcc26fb01f38670730e7c71b5e0b6ff
vymao/SmallProjects
/Chess/ChessPiece.py
956
4.125
4
class ChessPiece(object): """ Chess pieces are what we will add to the squares on the board Chess pieces can either moves straight, diagonally, or in an l-shape Chess pieces have a name, a color, and the number of squares it traverses per move """ Color = None Type = None ListofPieces = [ "Rook", ...
279f2542c582c7ae1f74655cad81f2dfeaac6873
chuck1l/vehicle_analysis
/src/vehicle_average_pricing.py
2,229
3.796875
4
import pandas as pd import numpy as np def create_range(data): df = data.copy() miles_cond = [ df['VehMileage'] == 0, df['VehMileage'].between(1, 10000), df['VehMileage'].between(10001, 20000), df['VehMileage'].between(20001, 30000), df['VehMileage'].between(30001, 400...
e2811f517871e517995b8ed870cab17b54cf5bc4
jrojasvalvo/valvo_canasta
/logic.py
6,796
3.796875
4
#!/usr/bin/env python import random import Copy class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def points(self): if self.suit == "H" or self.suit == "D" and self.rank == "3": return 100 elif self.rank == "2" or self.rank == "A": ...
91660664f26b6149e37550d8972d786a219542f1
vlavrent/NLP-Book-Classifier
/clear_phase/clear_data.py
3,236
3.6875
4
import pandas as pd import re def characterToBegin(text): if(len(text)>0): c = text[0] chars = ['>',"<",'[',']','.',',',';','(',')',' '] for char in chars: if (c == char): return True return False def replaces(input): #1st phase : re...
43af10f0a923e13fef297a0a84c7cba67d160f26
dmwiine/Binary_Search
/binary_search.py
792
3.640625
4
class BinarySearch(list): def __init__(self,a,b): super(BinarySearch, self).__init__(range(0,(a*b)+1,b)[1:]) self.length = a def search(self,item): first = 0 last = len(self)-1 found = False count = 0 result = {} if item == self[-1]: return {"count":count, "index":last} if item == self[0]: ...
49e452747a9a019aec7cef09fd23abb9eb2ce101
hwang-17/forpythonstudy
/contact_list.py
1,407
4.1875
4
''' this is a practice of dict from fishC forum ''' print('§---欢迎使用通讯录程序---§') print('§---1:查询联系人资料---§') print('§---2:添加新的联系人---§') print('§---3:删除已有联系人---§') print('§---4:退出通讯录程序---§') contacts = dict() while 1: instr = int(input('\n请输入相关的指令代码:')) if instr == 1: name = input('请输入联系人姓名') ...
ae6c7c9cd6a4ba02d4b60766fedab594414286d3
Naimish240/MIT-OCW-6.006
/lec 1/peak_finding_1d.py
991
3.984375
4
# --- Program to find a local peak in a one dimentional array --- # Import statement for random numbers in list from random import randint l = [] # Randomly initialize the array for i in range(10000000): l.append(randint(0,10000000)) # Method 1 : Linear searching print(" Method 1 ") if l[0]>=l[1]: print("...
8248881285dde45b5b7c8f6053f3f97b89dcbc84
AndreaScarpino/web-caesar
/caesar.py
1,602
3.984375
4
import string def alphabet_position(letter): """receive a letter and return its numeric position""" alph2pos = {} alph2pos = { "a" : 0, "A" : 0, "b" : 1, "B" : 1, "c": 2, "C": 2, "d": 3, "D": 3, "e": 4, "E": 4, "f": 5, "F": 5, "g": 6, "G": 6, "h": 7, "H": 7, "i": 8, "I": 8, "j": 9, "...
ba2d38f492ba13678372b6aeb068b1bb5fdc02af
over-cart/backend-side
/test.py
379
3.75
4
def listToNum(numList): num = 0 for i in range(0,len(numList)): if numList[i] > 255: numList[i] = 255 elif numList[i] < 0: numList[i] = 0 num += numList[i] << 8*i return num def numToList(num,size=16): l = [] mask = 0xFF for i in range(0,size): l.append(int((num & (mask << 8*i)) >> 8*i)) return l ...
5bb913e760a2a9cfea66379b5752f19c61ccd5d0
FVentur/school_proyects
/clasificar.py
1,144
3.78125
4
x=0 while (x<4): print (" T.P") print ("----------------") print (" MENU PRINCIPAL") print ("----------------") print ("1) cargar datos") print ("2) listar datos") print ("3) clasificar datos de la lista") print ("4) salir") x=int(input("ingrese una opcion: ")) ...
fb35517496b71b71fbacd14a8e5f25c90d132bd6
edy44/pool-python-calculator
/sample/operations.py
2,021
3.984375
4
#!/usr/bin/env python3 from math import * from evaluate import Evaluate class Operations: position = 0 result = '' memory = '' def __init__(self, results, button = ""): self.results = results self.button = button self.evaluate = Evaluate() def operation(self): i...
d8bc071aba1c639a3d17a2b87ccd45f51530da3d
ronny-souza/Lista-Exercicios-04-Python
/Exercicio02.py
1,107
4.1875
4
# QUESTÃO 02 - Faça um programa que percorre uma lista com o seguinte formato: # [['Brasil', 'Italia', [10, 9]], ['Brasil', 'Espanha', [5, 7]], 'Itália', 'Espanha', [7,8]]]. # Essa lista indica o número de faltas que cada time fez em cada jogo. Na lista acima, no jogo entre Brasil e # Itália, o Brasil fez 10 faltas ...
eaf9b966926a4249ea2833fd7ede1d935026419d
mitalijuneja/Python-1006
/Homework 2/engi1006/data.py
477
3.75
4
#### # Mitali Juneja (mj2944) # Homework 2b Problem 2 = contains functions for the csv data #### def datasetInfo(dataset): ''' Takes the dataset as an N x M list of lists. Returns the following statistics as a dictionary: rows: N from above, as an integer columns: M from above, as an integ...
01099d699d3e8b9919b117704f36d1c95ee75bcc
mitalijuneja/Python-1006
/Homework 5/engi1006/advanced/pd.py
1,392
4.1875
4
######### # Mitali Juneja (mj2944) # Homework 5 = statistics functionality with pandas # ######### import pandas as pd def advancedStats(data, labels): '''Advanced stats should leverage pandas to calculate some relevant statistics on the data. data: numpy array of data labels: numpy array of labels...
958e9a0a0459eb4187d7496e7dca7a02555b063c
Eddie02582/Leetcode
/Python/917_Reverse Only Letters.py
1,414
3.96875
4
''' Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions. Example 1: Input: "ab-cd" Output: "dc-ba" Example 2: Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: "Test1ng-Leet=code-Q!" Output: "Qedo...
471114d82d3003a88b85635597de7ab194db489f
Eddie02582/Leetcode
/Python/130_Surrounded Regions.py
1,119
3.53125
4
# # @lc app=leetcode id=130 lang=python3 # # [130] Surrounded Regions # # @lc code=start from collections import deque class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ from collections import de...
313203c5848b530b92939aa79db632b7ead62107
Eddie02582/Leetcode
/Python/100_Same Tree.py
1,461
3.875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree__(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ ...
6d489fbfb1f02918117a56ce3d570955a96d0c09
Eddie02582/Leetcode
/Python/260_Single Number III.py
2,522
3.890625
4
''' Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Example: Input: [1,2,1,3,2,5] Output: [3,5] Note: The order of the result is not important. So in the above example, [5, 3] is ...
53387aa9685dfc71ddb977e261e5b5404ef78309
Eddie02582/Leetcode
/Python/229_Majority Element II.py
1,746
3.8125
4
''' Given an integer array of size n, find all elements that appear more than ? n/3 ? times. Note: The algorithm should run in linear time and in O(1) space. Example 1: Input: [3,2,3] Output: [3] Example 2: Input: [1,1,1,3,3,2,2,2] Output: [1,2] ''' class Solution(object): def majorityElement(self, nums): ...
7eecbd7e0dc804099708a8d9a5718d15b6237ac5
Eddie02582/Leetcode
/Python/002_Add Two Numbers.py
1,411
3.828125
4
''' You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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. ...
b115063a0e34c310951a3e70ffde53ff9d1f62f2
Eddie02582/Leetcode
/Python/022_Generate Parentheses.py
2,074
3.625
4
class Solution: def generateParenthesis(self,n): res = [] self.helper(n ,n,"",res) return res def helper(self,left,right,out,res): if left < 0 or right < 0 or left > right: return if left == 0 and right == 0 : res.append(...
44cb1a541f6b6c2913891299a3ab0918e141a198
Eddie02582/Leetcode
/Python/036_Valid Sudoku.py
1,626
3.5625
4
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ #1.row for row in range(9): count = {} for col in range(9): n = board[row][col] if n != "." and n...
bd367cea336727a2ccbd217e8e201aad6ab42391
Eddie02582/Leetcode
/Python/069_Sqrt(x).py
1,565
4.40625
4
''' Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example 1: Input: 4 Output: 2 Example 2: Input: 8 ...
ef5e3b08084b712e924f564ec05a235e157ce482
Eddie02582/Leetcode
/Python/003_Longest Substring Without Repeating Characters.py
2,886
4.125
4
''' Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 E...
260fcb4b1e5f41b9346366332a3aed046572713a
Eddie02582/Leetcode
/Python/367_Valid Perfect Square.py
365
3.9375
4
''' Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false ''' class Solution(object): def isPerfectSquare(self, n...
5a78767f1b7cd9184af343c62c96dfc575ab7a86
Chencx901/leetcode
/problems/plusOne.py
738
3.640625
4
# Given a non-empty array of digits representing a non-negative integer, # plus one to the integer. # The digits are stored such that the most significant digit # is at the head of the list, and each element in the array contain a single digit. # You may assume the integer does not contain any leading zero, # except...
f25646b42a79186f1461379172cdb42adc4b455e
Chencx901/leetcode
/problems/MajorityElement.py
401
3.796875
4
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. Input: [3,2,3] Output: 3 class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ a = sorted([(x,nums.count(x))...
ed6e6d9293ebdd66b98817a32db65134ea3c8d83
Chencx901/leetcode
/problems/missingNumber.py
367
3.828125
4
# Given an array containing n distinct numbers # taken from 0, 1, 2, ..., n, find the one that is missing from the array. # Example 1: # Input: [9,6,4,2,3,5,7,0,1] # Output: 8 class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n...
6eea3786ce9dd5aea1ed3e3d49db716fd970d1b7
TheWildJarvi/JarviBrot
/FixedPointScript.py
472
3.796875
4
from fxpmath import Fxp inputs = input('sign, integers, fractional:').split(', ') sign = bool(inputs[0]) integers = int(inputs[1]) fractional = int(inputs[2]) words = integers + fractional + sign #x = (Fxp(number, bool(sign), words, fractional)) #print(x.bin(frac_dot=True)) while True: number = float...
b34977331a8f620c267ae294ddf3977cccf3f8f9
ratansingh98/design-patterns-python
/factory-method/FactoryMethod.py
1,328
4.34375
4
# # Python Design Patterns: Factory Method # Author: Jakub Vojvoda [github.com/JakubVojvoda] # 2016 # # Source code is licensed under MIT License # (for more details see LICENSE) # import sys # # Product # products implement the same interface so that the classes # can refer to the interface not the concrete produc...
0451c1f49acb96f6bae5b8e753a4f8573874c85b
ratansingh98/design-patterns-python
/template-method/TemplateMethod.py
985
3.96875
4
# # Python Design Patterns: Template Method # Author: Jakub Vojvoda [github.com/JakubVojvoda] # 2016 # # Source code is licensed under MIT License # (for more details see LICENSE) # import sys # # AbstractClass # implements a template method defining the skeleton of an algorithm # class AbstractClass: def template...
5513562b84170f92d6581dc1da83414705338443
ratansingh98/design-patterns-python
/abstract-factory/AbstractFactory.py
1,921
4.28125
4
# # Python Design Patterns: Abstract Factory # Author: Jakub Vojvoda [github.com/JakubVojvoda] # 2016 # # Source code is licensed under MIT License # (for more details see LICENSE) # import sys # # Product A # products implement the same interface so that the classes can refer # to the interface not the concrete pro...
a54da3f3b88701da5305fb3b1b14d4692fdb1558
crishonsou/hackerrank_solutions_submissions
/hackerhank_absolute_diagonal_difference.py
212
3.765625
4
def diagonalDifference(arr): diagonal1 = 0 diagonal2 = 0 for i in range(len(arr)): diagonal1+= arr[i][i] diagonal2+= arr[i][len(arr)-i-1] return (abs(diagonal1- diagonal2))
3e85b8b36feb94313382bbe2c17fbd356309a730
maximzubkov/ML_course
/projects/project1/implementations.py
8,577
3.828125
4
import numpy as np def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True): """ Generate a minibatch iterator for a dataset. Takes as input two iterables (here the output desired values 'y' and the input data 'tx') Outputs an iterator which gives mini-batches of `batch_size` matching elements fr...
80681f1fffeede6be7d2b10d1bc93c9bffd3e9c6
techrabbit58/KataFizzBuzz
/main/fizzbuzz/__init__.py
4,695
3.53125
4
""" Ten common and less common methods for counting FizzBuzz. """ from functools import partial from itertools import cycle, count from typing import List, Iterator class FizzBuzz: map = ((3, 'Fizz'), (5, 'Buzz')) fizzes = ['Fizz', '', ''] buzzes = ['Buzz', '', '', '', ''] encoding = [3, 0, 0, 1, 0, 2...
1b30655c32cde731d8ff104b5bd47c1b58e185df
cahehe/unbeatable-tic-tac-toe
/Unbeatable Tic-Tac-Toe/3x3.py
6,576
3.84375
4
#Unbeatable traditional tic tac toe game developed using the minimax Algorithm from math import inf import random import sys class ticTac: def __init__(self): self.board = [i for i in range(1,10)] self.human = "" self.AI = "" self.moves = 0 def availMoves(self):#Scans the board and checks which spots are ...
d95c8a80d72ac4ed180e73bc6aca4db4dbfd2436
LongLeonardoLe/one-hidden-layer-nn
/forward.py
833
4.09375
4
# This file performs the forward phase using sigmoid activation function # It contains of functions that # - calculates sigmoid activation # - softens the outputs using softmax operation # - forwards to the next layer from math import exp # sigmoid activation function def sigmoid(weight, x): z = 0.0 # g...
8ca58b8869a01a606fa7a27b6ca0979b9d7c1e2d
charlywhitlow/DFA_Equivalence
/dfa.py
7,998
3.546875
4
"""Command line tool to determine the equivalence of DFAs""" # Theory of Computation Coursework # Equivalence of DFAs import sys def read_DFA(filepath): '''Read input file with encoded DFA, and return DFA dictionary''' # get lines array with open(filepath, "r") as file: lines = file.readlines() ...
7642bf29311603e93ac7adac8a17bc1090058cbf
mattroseman/InterviewCheatSheet
/Sorting/Quicksort/quicksort_test.py
761
3.671875
4
import unittest from quicksort import quicksort class TestQuickSort(unittest.TestCase): def test_empty_list(self): self.assertEqual(quicksort([]), []) def test_simple_sorted_list(self): self.assertEqual(quicksort([1,2,3,4]), [1,2,3,4]) def test_simple_unsorted_list(self): self.as...
906741fbdcc1b8320c30d3ce1acba94339fe608a
kowsicavelusamy/guvi_codekata
/pythonvowel.py
104
4.03125
4
z= ('a','e','i','o','u') i=input() if i in z: print("vowel") else: print("not a vowel")
1d97718ad7c23f925f9fb0228c146af0fd0e8659
Nedashkivskyy/NedashkivskyyV
/Лаб 6 Недашківський.py
1,119
3.890625
4
from collections import namedtuple class Library(object): def __init__(self): self.books = [] def addBook(self, book): self.books.append(book) def searchBookYear(self, year): for book in self.books: if book.year == year: return book ...
42b361868e3829ad9eaee1e8a520c3dcbda23f8f
moahmmednms/beginnar-set1-
/vowel_or_Consonant.py
269
3.984375
4
a=input() if( (ord(a) >=97 and ord(a) <=122) or (ord(a) >= 65 and ors(a) <=90)): if(a=='a' or a=='e'or a=='i'or a=='o'or a=='u'or a=='A' or a=='E'or a=='I'or a=='O'or a=='U'): print("Vowel") else: print("Consonant") else: print("invalid")
86de62c7efce530f2fa7db3d5a551c7e1f934a4e
Astitwa-Agarwal/tathastu_week_of_code
/day5/program2.py
518
3.875
4
def nextGreatest(arr): size = len(arr) max_from_right = arr[size - 1] arr[size - 1] = -1 for i in range(size - 2, -1, -1): temp = arr[i] arr[i] = max_from_right if max_from_right < temp: max_from_right = temp def printArray(arr): for i in range(0,len(arr)): ...
7dc4a7cd2f0cea643673ee0ace3ccd2b8b5cf117
bliiir/python_fundamentals
/16_variable_arguments/16_01_args.py
345
4.1875
4
''' Write a script with a function that demonstrates the use of *args. ''' def my_args(*args): '''Print out the arguments received ''' print('These are the arguments you gave me: \n') for arg in args: print(arg) # Call the my_args function with a string, a number and a copy of itself my_args(...
61f6f83df075a12cade4de46d6961aec64cb237b
201leandro/nagro-teste
/main.py
1,223
3.609375
4
""" Projeto: Teste Nagro Tarefa: Teste Nagro Fonte: Elevador.py Autor: Leandro Oliveira Data: 20/09/2017 Empresa: Nagro Obs: Funcao principal para simulacao das rotinas de um elevador social Ultima alteracao - Leandro Oliveira - 21/09/2017 """ from Elevador import Elevador elevador = Elevador() # pylint: disable...
33b5d333599ea1471875c8495b67c0a642497c35
YCullen/LeetcodePractice
/0_intersection.py
862
3.84375
4
import pdb def intersection(start1,end1,start2,end2): k1 = (end1[1]-end1[0])/(start1[1]-start1[0]) k2 = (end2[1]-end2[0])/(start2[1]-start2[0]) p1_x =max(start1[0],start2[0]) p2_x =min(start1[1],start2[1]) def a_line(x,k,x0,y0): return k*(x-x0) + y0 if p1_x - p2_x > 1: return [] ...
80af3874703bc28aa1707bb080aa25c332d5569a
YCullen/LeetcodePractice
/0_RotateMatrix.py
533
4.125
4
import pdb def rotate(matrix): # 矩阵转90度的本质是把第i行换到第-i列 N = len(matrix) matrix_copy = [[0 for i in range(N)] for j in range(N)] for i in range(N): for j in range(N): matrix_copy[i][j] = matrix[i][j] for i in range(N): tmp = matrix_copy[i] for j in range(N): ...
4513363261cf50bd1a22c52f818d7ce3b51d0077
HJ3EQG/TIC
/Ciclo1 - PYTHON/reto_3/practica/nuevo.py
754
3.546875
4
def carga_paises(): mayor = 0 pmayorp = "" # pais mayor poblacion i=0 paises={} while i < 10: nom_pais=input(f"Nombre del pais {i+1}: ") pob_pais=int(input(f"poblacion del pais {i+1}:")) paises[nom_pais]=pob_pais i=i+1 for nombre in paises: if pai...
b1e1f73b87d89927cf8eb9af1c687498cd956729
vcampos4545/Sudoku
/solver.py
1,444
3.875
4
import numpy as np def solve(board, pygame_board): """ Returns a solved grid using backtracking and recursion """ # TO DO: Fix solve and somehow get solved board in variable for row in range(len(board)): for col in range(len(board[row])): if board[row][col] == 0: ...
d7fd7a9aac17da65af8e924f0f595cce5c6df748
Salmon555/ml_project
/data_processing_functions.py
2,009
3.59375
4
### functions for data_processing def txt_to_dictionary(name) -> dict: ###read .txt file into a dictionary dic={} file = open(name+'.txt','r') for line in file.readlines(): line = line.strip() k = line.split(' ')[0] v = line.split(' ')[1] list_ = v.split(",") ...
cf1d92c0821e5bc526fb920787b2306f18f5358e
GilliamD/Digital-Crafts-Day-4
/day_of_the_week.py
320
4.28125
4
day = int(input("Day 0-6? ")) if day == 0: print("Sunday") elif day == 1: print("Monday") elif day == 2: print("Tuesday") elif day == 3: print("Wednesday") elif day == 4: print("Thursday") elif day == 5: print("Friday") elif day == 6: print("day") else: print("Thats\'s not a day, Bud.")
cfbdcdfc75e6237365b4bd78b69a881266a1c68e
junho-one/algorithm
/programmers/kakao/blockGame.py
3,306
3.640625
4
from collections import deque def solution(board): def canFall(row, col) : for i in range(0, row) : if board[i][col] != 0 : return False return True def check_vertical_Rect(row,col) : numbers = set() zero = 0 blocks = [] for i in ra...
2a175ae89eb9169a624a823a9752a35d60381ad5
junho-one/algorithm
/programmers/hash/camouflage.py
957
3.515625
4
from collections import defaultdict def solution(clothes): cloth_dict = defaultdict(list) total = 1 for cloth in clothes: cloth_dict[cloth[1]].append(cloth[0]) # 모든 경우의 수 : (의상 종류 별 개수 + 1) 를 종류 별로 모두 곱한 값 # +1은 각 종류에서 안 입고 있는 경우까지 포함하기 위해 for cloth in cloth_dict.keys()...
e60d8bfb7bc27ab1e37b8094929d3a7d2860ad0e
junho-one/algorithm
/programmers/graph/wordChange.py
1,248
3.5
4
from collections import defaultdict, deque def different(sent1, sent2) : diff = 0 for i in range(len(sent1)) : if sent1[i] != sent2[i] : diff += 1 if diff == 1 : return True else : return False def solution(begin, target, words): def bfs(start) : queue...
21f8644dbf0103a7764f2ac8bc1a86d9c2babc25
junho-one/algorithm
/programmers/graph/travelPath.py
634
3.609375
4
# 여행 경로 # 오일러 서킷, 오일러 트레일을 찾는 문제이다. # 시작점이 ICN으로 고정이니까 그냥 오일러 서킷을 찾는 코드를 짠 뒤 ICN으로 시작하면 된다. from collections import defaultdict def solution(tickets): def go(vertex): while graph[vertex]: next = graph[vertex].pop() go(next) answer.append(vertex) graph = defaultdict(...
0fdded2ee2141b7e3857a4f9edf5f309a20ebae9
williamjiamin/Pure_Python_for_DS_ML
/11.感知器(Perceptron)/2.full_test_run.py
1,303
3.53125
4
# Created by william from lexueoude.com. 更多正版技术视频讲解,公众号:乐学FinTech def predict(row, weights): activation = weights[0] for i in range(len(row) - 1): activation += weights[i + 1] * row[i] return 1.0 if activation >= 0.0 else 0.0 def opt_weights(train, learning_rate, how_many_epoch): weights = [...
c805e2b9e864a800b8be5a4d48e0a92f4d09cb33
DariuszOstolski/courses
/python/a2/a2.py
5,527
4.0625
4
# Do not import any modules. If you do, the tester may reject your submission. # Constants for the contents of the maze. # The visual representation of a wall. WALL = '#' # The visual representation of a hallway. HALL = '.' # The visual representation of a brussels sprout. SPROUT = '@' # Constants for the directio...
e067783f261af980364fec3bace0818a0008169f
neylsoncrepalde/BotEducacaoSuperior
/motivation.py
1,713
3.53125
4
""" Posts de motivação Bot Educação Superior @author: neylson.crepalde """ from twython import Twython import random import time from auth import ( consumer_key, consumer_secret, access_token, access_token_secret ) twitter = Twython( consumer_key, consumer_secret, access_token, access_to...
fd685017f14b93499556a37715b83ebaa20d38e2
audiomilan/modernpy
/Lesson4/math.py
275
4.03125
4
import turtle import math bob = turtle.Turtle() print(bob) def polygon(a, b, c): ... def circle(t, r): circumference = 2 * math.pi * r n = int(circumference / 3) + 1 length = circumference / n polygon(t, n, length) circle(bob, 100) turtle.mainloop()
26988fbffc06483598303e0d3367516101326677
altincampbell121690/cisClassSearch
/UIclassSearch.py
3,109
3.6875
4
''' Console UI for class search Name: Sjaakar * ALTIN * Campbell Date 17MAR2018 Description: This program is an application that helps a user look up CIS classes. The app uses data from this CIS web page. ''' from cisclasses import CISclasses ''' In this lab I used three classes UI, CIS classes,...
d8c4df937b053802bf6429af439a53cc6fa54b8c
Mousto097/Python-intro-to-computing
/part_two/arithmetic_test_for_elementary_school.py
1,966
4.09375
4
import random # Author: Mamadou Bah def performTest(operation): ''' Execute the arithmetic test for a student for multiplication or addition operations and return the number of correct answers ''' correctCounts = 0 # Test the student with exactly 10 questions for i in range(1, ...
ab38fe30a1406763defd6fe2614727f3935ac1d5
Mousto097/Python-intro-to-computing
/part_two/arithmetic_test_for_elementary_school_v2.py
1,631
3.90625
4
import random # Author: Mamadou Bah def doTest(operation): '''The user is tested with 10 questions that are randomly distributed between multiplication and addition''' result = False # Randomly generates two-positive one-digit integers first_number = random.randint(0, 9) second_num...
33b5a44798bbd27be2e0651c3acf4010e0731318
Mousto097/Python-intro-to-computing
/part_one/find_distance_between_two_stars.py
3,306
4.25
4
# Author: Mamadou Bah # Function for part A def convert_sideral_years_into_seconds(): "Converts a given number of sidereal years into seconds" # Take input from user for the number of light-years number_of_light_years = float(input("Input a number of light-years: ")) # Conversion of a give...
60502e0434d2fb907f2befd231dfa07fdc814f8a
rdrdrd/bikeworks
/socket_examples/py_sockets.py
798
3.515625
4
#!/usr/bin/env python3 import socket PORT = 8080 IP = '127.0.0.1' # Create a socket object with a TCP nature with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # bind our socket to port 8080 s.bind(('127.0.0.1', 8080)) # listen for incoming connections s.listen(30) # accept a connecti...
b1ace0b2cc6a8281d0d1582b17cc301cbeb347d4
Biju-vinoth/LPHW
/ex15.py
629
3.5
4
''' #============================================================================= # FileName: ex15.py # Desc: file modules # Author: Honglong Wu # Email: wuhonglong@genomics.cn # Version: 0.0.1 # Created: 05/03/2015 # History: #=================================================...
877645631876df072b875dfa41f4b4be08524d9d
Biju-vinoth/LPHW
/ex30.py
797
4.09375
4
''' #============================================================================= # FileName: ex30.py # Desc: if/elif/else practice # Author: Honglong Wu # Email: wuhonglong@genomics.cn # Version: 0.0.1 # Created: 08/03/2015 # History: #========================================...
f9c93557e4c76746321eccfee7e9e0a7a551fd42
Biju-vinoth/LPHW
/PDA/PDA.py
5,805
3.703125
4
''' #============================================================================= # FileName: PDA.py # Desc: The basic pipeline of data analysis with python # Author: Honglong Wu # Email: wuhonglong@genomics.cn # Version: 0.0.1 # Created: 18/03/2015 # History: #=================...
1628425868b8f8ee7be4204da73e2422284188a9
Biju-vinoth/LPHW
/ex33.py
574
4.0625
4
''' #============================================================================= # FileName: ex33.py # Desc: while loop # Author: Honglong Wu # Email: wuhonglong@genomics.cn # Version: 0.0.1 # Created: 09/03/2015 # History: #===================================================...
609fc7970d1e8a9a1fc194c10d0ae73975e6c428
jfeidelb/Projects
/PythonTextGame.py
2,237
4.34375
4
from random import randint import operator print("This is an educational game where you will answer simple math questions.") print("How many questions would you like to answer?") questionInput = input() def MathQuestion(questionInput): questionLoop = 0 score = 0 try: #loop to control number of que...
2a3d6620775c209bc652b29ad74f5557f1240463
Shrrgn/some_python_code
/class_complex.py
865
3.890625
4
#class that workiimg with complex numbers class Complex: def __init__(self, real = 0.0, imaginary = 0.0): self.real = real self.imaginary = imaginary def __repr__(self): return "Complex({!r},{!r})".format(self.real,self.imaginary) def __str__(self): return "{}{:+d}i".format(self.real,self.imaginary) ...
5fb8e54c20c5ce3b09c77fc1931473ac350d044d
pneumoo/practice
/EulerProject/EP9.py
765
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 15 13:27:18 2015 @author: Brian """ """ Special Pythagorean triplet Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean trip...
9d679c27ff6ca7789a05b14b62247c10522d2a3e
katrek/learningbook
/lists/write_list.py
314
4.03125
4
# This program saves a list of string to a file def main(): cities = ['Kiev', 'Kharkov', 'Dnepr'] # Open a file for writing outfile = open('cities.txt', 'w') # Write the list to the file for item in cities: outfile.write(item + '\n') # Close the file outfile.close() main()
7e9b1b9f40727f241256aff9252e599ffac63705
katrek/learningbook
/dictionary/file.py
746
3.609375
4
# Dictionary # the clear method # dictionary.clear() print('Clear method') phonebook = {'Chris' : '555-1111', 'Katie' : '555-222'} print(phonebook) phonebook.clear() print(phonebook) # the get method # dictionary.get(key, default) print('Get method') phonebook = {'Chris' : '555-1111', 'Katie' : '555-222'} value = ph...
383cf5c58b65554c25ba6c29ec5805c5e6abfbde
thekushkode/lists
/lists.2.py
1,321
4.375
4
# List Exercise 2 # convert infinite grocery item propt # only accept 3 items # groc list var defined groc = [] #build list while len(groc) < 3: needs = input('Enter one grocery item you need: ') groc.append(needs) #groc2 list var defined groc2 = [] #build list while len(groc2) < 3: needs2 = input('Ente...
334647913df8c462e4cb3544b84e09bb4e44522a
weipinl/pythonBootCamp
/Day4/highestScore.py
342
3.703125
4
student_scores = input("Input a list of student scores ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) maxNum = 0 for score in student_scores: currentScore = score if currentScore > maxNum: maxNum = currentScore else: c...
ca81875568ba3dff6584eee4ca89da5185213afe
alexandruserban/me-thinks-it-is-like-a-weasel
/weasel.py
4,691
3.734375
4
""" Simple script which generates the phrase 'ME THINKS ITS LIKE A WEASEL' using an extremely simple genetic algorithm. This was completely inspired and based off what Richard Dawkin's performs in his book 'The Blind Watchmaker' as a way of explaining accumulations of small change through the use of cumulative selectio...
146e417446269c6e7c910629beaf21ee72ac8b2c
jeff007ali/leetcode
/may-leetcoding-challenge/D07-CousinsInBinaryTree.py
790
3.71875
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 isCousins(self, root: TreeNode, x: int, y: int) -> bool: def recurr(node, parent, level...