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
c6096f1ce07d429c01c9c764c260f3e06e7e7e05
yashjshah/Hackerrank
/Python/Errors and Exceptions/Exceptions/exceptions.py
237
3.734375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT for _ in range(int(input())): try: a,b = (int(x) for x in input().split()) print(a//b) except Exception as e: print("Error Code:", e)
4e4e2f59e84765b404017f892ec967835dd53521
lily48/oop-python
/Refactoring/refactoring_4_encapsulation/game.py
552
3.5
4
from player import Player class Game: def __init__(self, num_players, win_score=100): self.win_score = win_score self.players = [] for num in range(num_players): self.players.append(Player(num + 1)) def run_game(self): while True: for player in self.pla...
702f3edd1d8e8beaed701a57ccc65fe02d3e0e36
yadavavinash/Project
/Calculator/Calculator.py
1,142
3.984375
4
from logo import logo import os clear = lambda: os.system('clear') #add def add(a,b): return a+b #subtract def subtract(a,b): return a-b #divide def divide(a,b): return a/b # multiply def multiply(a,b): return a*b operations = { "+" :add, "-" :subtract, "/" :divide, "*" :multiply } def calculator(): # for...
28ec4b31b7ab22c9939c504a9b5c7d6d2c5b5c37
hamzajana974/Python_Task
/pythonPractice/greatPer.py
1,208
4.03125
4
# rows = int(input("Kindly enter digit for print Pyramid: ")) # k = rows +1 # # for i in range(rows): # for j in range(k): # print(end=" ") # # k = k-1 # for j in range(i+1): # print("* ",end="") # # print() # # for i in range(rows, 0, -1): # for j in range(0, rows - i): # p...
5387dddc6c51de7b50f2e49ee1df001dde6fdc3b
AgentSuraj/Python-Calculator
/Calculator.py
679
4.0625
4
print("AS Calculator V2.01") while(True): n1 = float(input("Enter your Fist Valu:")) op = input("Enter your Operator[+,-,*,/]:") n2 = float(input("Enter your Second Valu:")) if op=="+": print("Your Result=>", n1+n2) elif op=="-": print("Your Result=>", n1-n2) elif op==...
6fc391ff470652ce68263cffd6126a39de7beb65
chaudharikeyur/Basic-Library-Management-System-try-
/LibraryManagement.py
4,107
3.8125
4
import random class Library: # lend = 0 def __init__(self, bookname, nameofbuyer, id): self.bookname = bookname self.nameofbuyer = nameofbuyer self.id = id def displaydetails(self): return "name {} has lent a book {} having id {}.".format(self.nameofbuyer , self...
4f53050f561880a221ce6d20f1539bef2aa79880
owen694/introcs
/python/pell_lab.py
504
3.90625
4
def pell_iter(n): a = 1 b = 2 for i in range(3, n+1) : c = 2 * b + a a = b b = c return c def pell_tree(n): if n == 0 or n == 1: return n i = 2 * pell_tree(n - 1) + pell_tree(n -2) return i def pelltester(p, n): for i in range(1, n + 1): ...
3cae29b71ef6c489dd960504264e8d724c069d2b
aishwarya1505/aishwarya-python
/13.py
312
3.890625
4
#ask the user for a number and #print the table of that number till 20. n=int(input("enter value: ")) a=1 while(a<21): print(a,"x",n,"=",a*n) a=a+1 ----------------- output cl316@soetcse:~/aishwarya$ python3 13.py enter value25 25 50 75 100 125 150 175 200 225 250 275 300 325 350 375 400 425 450 475 500
6ae2ca437f3ab8cf0d1be97a77dbc98052177ca5
StarGazer1915/SatisCalculator
/StatisCal/SatisCalMain.py
1,794
3.796875
4
import json # -------------------- FUNCTIONS -------------------- # def loadRecipes(): """ Loads the .json file containing the items of Satisfactory. @return: dict """ with open("DataFiles/Resources.json") as file: return json.load(file) def getItemsRequired(data, givenItem): """ ...
53d904590b85adaded32612aee7debc84eb9ea8a
peake-s/Simple-pattern-recogntion-opencv
/circuit.py
2,500
4
4
#----------------------------------------------------------------------- # File : circuit.py # # Programmers: Samuel Peake and David Wells # # Program #: Final Project # # Due Date: 05/05 # # Course: EGRE 347, Spring 2021 # # Pledge: I have neither given nor received unauthorized aid on this program. # # D...
a652b527a2cb0bbef22acc67127d1ce90116c251
olref/PythonSnippets
/basicCurses.py
797
3.734375
4
# -*- coding: utf-8 -*- import curses def main(self): screen = curses.initscr() screen.border(0) #main loop while True: #write title on the first line (x=0) screen.addstr(0,15, 'My great menu') screen.addstr(8,2, '1 - What is the answer to life ? ') screen.addstr(9,...
03b844b995951c241e925f6122eedad02ce60ceb
nabo715/LearningPython
/File_processing2.py
672
3.734375
4
# Use words.txt as the file name # Use the file name mbox-short.txt as the file name sum_final = 0 count =0 fname = raw_input("Enter file name: ") try: fh = open(fname, r) except: print("Enter a valid file name") exit() for line in fh: if not line.startswith("X-DSPAM-Confidence:") : co...
302c289c80da947a8f9bce1c87799b824c65ade0
Wopple/fimbulvetr
/src/client/counter.py
1,365
3.546875
4
class Counter(object): def __init__(self, value, minimum, maximum): self.value = value self.minimum = minimum self.maximum = maximum self.restricted = False if self.minimum > self.maximum: raise Exception if not self.isWithinBounds(): raise E...
ed214a60d38ef26dd783db5dbd275e08f3b6af84
W-Glenton/Checkers-Game-With-MiniMax-AI
/move.py
5,713
3.8125
4
from piece import Piece #from board import Board class Move: def __init__ (self,x1,y1,x2,y2): self.x1=x1 self.y1=y1 self.x2=x2 self.y2=y2 def getCoOrds(self):#return coords (only used in debugging) return self.x1,self.y1,self.x2,self.y2 def skipsearch(self,state,pla...
e703dc14fc87e2cb8f6918352b4c2c4b4d168ef7
wljave/subentry
/basics_test/Student_Management_System.py
2,136
3.890625
4
# 查看代码和注释,并运行 # 创建一个人事系统类 class HrSystem: # 创建存储员工名字的变量 name name = '' # 创建存储员工工资的变量 salary salary = 0 # 创建存储员工绩效的变量 kpi kpi = 0 # 定义录入员工信息的类方法 @classmethod def record(cls, name, salary, kpi): cls.name = name cls.salary = salary cls.kpi = kpi...
c723daca9957c23c6b9bc087651dcd0cc42ecbb3
wljave/subentry
/basics_test/python_PK.py
3,299
3.828125
4
#提示:调用模块需在开头写上import 模块名,这里需要用到random模块 import random import time def game(): #保存成绩,胜利得1分、失败-1、平局不得分 player_score = 0 #用来保存玩家成绩 enemy_score = 0 #用来保存敌人成绩 for i in range(1,4): time.sleep(1.5) # 让局与局之间有较明显的有时间间隔 #print(' \n——————现在是第'+str(i)+'局,ready go!——————') # 作...
698706f3ead1059e4830699724ea79cda4732ad8
wljave/subentry
/basics_test/schedule.py
726
3.953125
4
# 请根据所学,补全一下代码: class Calendar: # 日程安排的日期 date = '2020-08-08' # 时间清单,以字典形式给出,键位事件,值为安排的时间 things = {'给父母买礼物': '9:00', '学习': '10:00', '和朋友聚会': '18:30'} @classmethod def thing_done(cls, thing): # for i in cls.things: # print('{}: {}'.format(i, cls.things[i])) ...
ba6b8f91755f812122ac9480cf5a667cc3138ffa
vijaynchakole/Proof-Of-Concept-POC-Project
/Directory Operations/Project_file_Directory_Operations.py
6,367
3.71875
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 17:30:14 2020 @author: Vijay Narsing Chakole Absolute and Relative Pathnames in UNIX A path is a unique location to a file or a folder in a file system of an OS.A path to a file is a combination of / and alpha-numeric characters. Absolute Path-name An absolute path ...
133249b5665e99fb2291cff6ab49e0c1cb6c800c
vijaynchakole/Proof-Of-Concept-POC-Project
/Directory Operations/Directory_File_Checksum.py
2,950
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 01:02:26 2020 @author: Vijay Narsing Chakole MD5 hash in Python Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password st...
c92353f16a34985726f8ebffb38f9c441f0f87c2
nithiye/python-challenge
/PyPoll/Resources/Main.py
1,775
4.0625
4
# The dataset is composed of three columns: Voter ID, County, and Candidate. #Your task is to create a Python script that analyzes the votes and calculates each of the following: import os import csv #csvpath election_path_csv = os.path.join('..','03-PYTHON','Instructions','PyPoll','Resources','election_dat...
eb16fde47f322b29772f79d169a75849986129b0
minkyeong417/loop
/loop.py
301
3.859375
4
total = 0 count = 0 while True : s_input = input('Enter a number: ') if s_input == 'done' : break try: i_input = int(s_input) except: print('Invalid input') continue total = total + i_input count = count + 1 print(total, count, total/count)
e58166de3185a3b12ede68e42b36989b0362461a
lizzzcai/python-bloomfilter
/bloomfilter.py
1,135
3.59375
4
# simple hash function class Hash: def __init__(self, cap, seed): self.cap = cap self.seed = seed def hash(self, value): ret = 0 for i in range(len(value)): ret += self.seed * ret + ord(value[i]) return ret % self.cap class BloomFilter: def __init_...
7e14adb54af74496c7acd7445fb2cb6a64fe9821
rctorr/CUDAB2CCDMX2001
/Sesion-02/genera_claves.py
1,501
3.609375
4
# Importación de módulos import random # Lee el valor de número de claves n esCorrecto = False # Bandera para el ciclo while while not esCorrecto: n = input("Cuantas claves a generar n: ") esCorrecto = n.isdigit() if not esCorrecto: print("El valor ", n, " no es un entero, por favor ingresa un ent...
55a88ec1030e27242386ef17c3293a160e404a92
zubayer01/python_snake_game
/sanke.py
1,549
4.03125
4
from turtle import Turtle class Snake: def __init__(self, snakes=3): self.snakes = snakes self.snake = [] self.createSnake(self.snakes) def createSnake(self, num): posX = 0 for i in range(num): part = Turtle() part.shape('square') ...
12bcd42d7f837aab4f89d50e421a09483b844dfb
phani482/Project-Euler
/2.py
795
3.96875
4
""" Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valu...
dbc82e04ccf3ed5a5fc9b2b4b93071ae2b49212d
SariBeg137216/python_practices
/Review/Basics.py
248
3.734375
4
# str = "pynative" # # print(str[::2]) # for i in range(6): # for j in range(i): # print(i, end='') # print() def Tax(income): tax = 1000 income -= 20000 tax += income * 20 // 100 return tax print(Tax(60000))
10178ffd3c2309c75ff681529b1891802b364366
SariBeg137216/python_practices
/Review/JSON.py
2,177
3.546875
4
import json from collections import namedtuple # data = {"key1": "value1", "key2": "value2"} # sampleJson = """{"key1": "value1", "key2": "value2"}""" # print(json.dumps(data)) # jsdata = json.loads(sampleJson) # print(jsdata['key2']) # # sampleJson = {"key1": "value1", "key2": "value2"} # json_data = json.dumps(sampl...
b2a77dd6b8fe303e7c79e4ba2a0ffff00480cfce
Verissimosem2/programacao-orientada-a-objetos
/listas/lista-de-exercicios-03/questão1.py
222
4.09375
4
numero = int (input("Por favor digite o primeiro numero: ")) numero_2 = int (input("Por favor digite o segundo numero: ")) if numero > numero_2: print("Numero maior: ",numero) else: print("Numero maior: ",numero_2)
a1e3f0f77b787e2d3e1c4716b1267fc96a588e07
Verissimosem2/programacao-orientada-a-objetos
/listas/lista-de-exercicios-03/questão9.py
904
4.25
4
numero = float (input("Digite o primeiro numero: ")) numero2 = float(input("Digite o segundo numero: ")) numero3 = float(input("Digite o terceiro numero: ")) if numero > numero2 and numero > numero3: if numero2 > numero3: print("",numero) print("",numero2) print("",numero3) if numero3 > ...
43826523caafece2afc785c74bb8af072aa65103
Verissimosem2/programacao-orientada-a-objetos
/listas/lista-de-exercicios-02/questao2.py
80
3.609375
4
print ("Selecione um numero: ") numero = int (input()) print("Numero: ",numero)
b71ce556b6e5321716063d5f349607834f6d1a4a
Verissimosem2/programacao-orientada-a-objetos
/listas/lista-de-exercicios-02/questao3.py
149
3.921875
4
numero = int (input("Digite o primeiro numero: ")) numero_2 = int (input("Digite o segundo numero: ")) print ("Soma dos numeros: ",numero + numero_2)
7f00eaa32c60892cfac6d4fd3aa52ddc6e724559
olgakirova/stepic.ru
/1.12.3.draft.py
119
3.5625
4
a = float(input()) b = float(input()) c = input() if c == "pow": print (a**b) if c == "dev": print (a//b)
fad2721d43b9fd2aa0c03e84211a856715500c60
olgakirova/stepic.ru
/2.1.2.py
94
3.53125
4
a = int(input()) b = int(input()) d = 1 while d%a != 0 or d%b != 0 : d+=1 print (d)
ce257747bdc05e1a3b56f7518d113fb20687a03a
tipped-fedora/assignment
/exersise1.py
309
3.8125
4
#revision exersise1 #robert fox def main(): number1 = float(input("please enter your first number: ")) number2 = float(input("please enter your second number: ")) if number1==number2: print("These numbers are the same") else: print("these numbers are not the same")
1813167706fd9ee7c8abca3c952565bd5df12d1d
jatinad101/python_practice
/DSA-Python/DSA-20210104T054818Z-001/DSA/Python_programs/DSApy/Recursion/combination.py
205
3.796875
4
def fact(n): res = 1 for i in range(2, n+1): res = res*i return res def combination(n, r): return ( fact(n) / (fact(r) * fact(n-r))) n = 5 r = 3 print(int(combination(n, r)))
6aee76a3dc0914a5530a4b2f9e0c5d13496a3fa7
jatinad101/python_practice
/DSA-Python/DSA-20210104T054818Z-001/DSA/Python_programs/DSApy/Sorts/counting_sort.py
383
3.8125
4
def countingsort(mylist, high): counter = [0] * (high+1) for i in mylist: counter[i] += 1 startpoint = 0 for i in range(len(counter)): while 0 < counter[i]: mylist[startpoint] = i startpoint += 1 counter[i] -= 1 #driver code arr = [5, 3, 2, 3, 6,...
338d4e4689cfd115325da4f26e08a6a9b19457db
hamzahmed05/Algorithms-coursework
/Algorithms/week4-DynamicProgramming.py
8,321
4.15625
4
##################### # Fibonacci Numbers # ##################### #naive, recursive def fib(n): 'n-th Fibonacci number' if n <= 1: return n else: return fib(n-1)+fib(n-2) #memoized version def memfib(n): 'n-th Fibonacci number' return memfib_r({0:0, 1:1}, n...
64b26cda74696f7afafa766dc66070b85c86d340
PopDiana/blocks_world_problem
/src/random_state_generator.py
1,151
3.890625
4
import random def state_generator(number_of_blocks): # A function which generates a random state for the blocks world problem # number_of_blocks - the number of blocks of the problem random.seed() # initialize random seed no_of_stacks = random.randint(1, number_of_blocks) # generate random nu...
33af83aa6bacea076fc13540c8be2d0ee20a08c8
dawes206/leet-code
/21.Merge_Two_Sorted_Lists_2.py
975
4.0625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: left = l1 right = l2 root = ListNode(None) node = root while left and right: if left.val<=rig...
d229cbafdffb09e18f1f58c9f7f51bfbf408d018
dawes206/leet-code
/965.help.py
1,007
3.84375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isUnivalTree(self, root): left_correct = (not root.left or root.val == root.left.val and self.isUnivalTree(root.left)) right_correct = (not...
0e26e04c52f6a29e9968e921e0be81d37d03bcfb
dawes206/leet-code
/563.binary_tree_tilt.py
2,852
3.890625
4
# 1 # / \ # 2 3 # / \ / \ # 5 4 3 6 # # is tilt 11-12 # or |4-5|+2 - |6-3|+3 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: #def findTilt(se...
610d4a88661c399aa9d4f3bed95c3fc4326f3ccc
Xarangi/Word-Search-Game
/main.py
7,080
3.84375
4
import random import os #initialising two lists, the first list will be the list that is printed and the second list is used in the background to check for the words crossword=[] crosswordx=[] #store_list is a 2D list storing data regarding the score (dictionary can be used too) store_list=[] player_cnt='0...
18414a25189a7b727f46e7051a22fbfbc4cb9f0d
onahump/PythonCourse
/EncapsulatingCode/functions.py
945
4.09375
4
def hello_world(): print("Hello world!") hello_world() def print_name(name): print(f"Hello {name}") print_name("Juan") output = print_name("Pancho") #Assigning function result into a variable def add_two(num): #Adding two return num + 2 result = add_two(2) print(result) #Multiple arguments def add(num...
c2302e91ca49f3c43cb1aa34888128b107d3e703
aeksei/py110-2020-autumn-2
/3/add.py
525
3.515625
4
import argparse def main(): parser = create_parser() args = parser.parse_args() print(args.a + args.b) def create_parser(): parser = argparse.ArgumentParser() parser.add_argument('a', type=int, help='Первое число для сложения') parser.add_argu...
f781b28cb6777cd53ea1ef20bd2604867b9a2b24
naeem-bebit/data-analysis
/python-note/basicpython.py
1,134
3.515625
4
import itertools from unittest.mock import Mock import json mock = Mock() data = json.dumps({'a':1}) # print(data) json = mock json("a") json.dumps({"a":1}) # print(json) # print(dir(json)) print(json.assert_called_once()) print(json.dumps.assert_called_once()) # List Comprehension nums = [1, 2, 3, 4] a = [] for ...
434e3f04eaa06b999d35ddc79abf1ee05d3ca903
naeem-bebit/data-analysis
/linear-regression/linear-regression.py
1,800
3.734375
4
"""Linear regression Boston dataset.""" # Load libraries from sklearn.linear_model import LinearRegression from sklearn.datasets import load_boston import warnings # Suppress Warning warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd") # Load Boston data (X & Y) ...
464407edaa522186de9312b3d067f5fb2509f6db
AdrianVargas07/BomberMan
/MARDA/FabricaLaberinto/GameView.py
7,046
3.59375
4
import pygame import os.path from abc import ABC, abstractmethod ''' MARDA class showing game menu screen ''' class GameView(ABC): pygame.init() def __init__(self, windowWidth, windowHeight): ''' Construct a new GameView object :param windowWidth: width of screen game ...
94a860db78a3c11cf493f4f6741844ddcadc7302
yuan20170517/SmartWindow
/initialisation.py
1,677
3.796875
4
# initialisation mode is a debugging step to ensure that all sensors, camera and motor is in working conditions # user will do manual check on all the component before letting system to run automatically (will have an option to run this or not) # GPIO PIn allocation is defined in each sub functions # setup humidi...
568d603bd4a9527c74ba3c81b69e309321c29c8c
dntrinh/GitTutorial
/helloworld.py
685
3.90625
4
def helloworld(): def greeting(): print("What is your name?") Name = input() print("Hello World, my name is", Name) greeting() def fibonacci(): num_1 = 0 num_2 = 1 import time time.sleep(1) print(num_1) import time time.sl...
19e8876545c6747fef90f5c0d32345e11f64b34d
gunnarmagholder/Codeeval
/Maze.py
1,424
3.640625
4
maze = [ [1,1,0,1,1], [1,0,0,0,1], [1,0,1,0,1], [1,1,1,0,1] ] def find_entry(mazeToSolve): first_line = mazeToSolve[0] for x in range(len(first_line)): if first_line[x] == 0: return x return -1 def check_field_for_pathway(maze, x, y): if x < 0 or ...
629cfa7a94d9fe43b13b852f022f62b6f7ada3ad
Imafikus/ppj
/vezbanje_kolokvijum/automat.py
652
3.71875
4
import sys def main(): stanje = "A" kranje_stanje = "E" prelaz = { ("A", "a"): "A", ("A", "b"): "B", ("B", "a"): "C", ("B", "b"): "B", ("C", "a"): "D", ("C", "b"): "B", ("D", "a"): "A", ("D", "b"): "E", ("E", "a"): "E", ("...
ece2d6e7033d01d626baab211ab0016b1bd303b6
Bhitt/CS4080_ConceptsOfProgramming
/Python_Set_Intersection_and_Difference.py
98
3.609375
4
s1 = set([1,5,3,6,7,8]) s2 = set([2,5,6,9,7]) print(s1.intersection(s2)) print(s1.difference(s2))
1b43659cd70acabc9654503c315e67abd2c37b5f
alessandrosp/reptile
/reptile/forms/list.py
1,797
3.5
4
import prompt_toolkit.application as ptk_app import prompt_toolkit.layout.containers as ptk_containers import prompt_toolkit.layout.layout as ptk_layout from .multi import MultiForm class ListForm(MultiForm): """Class for forms of type List. ListForms are forms where the user is presented with a series of ...
ee8c9a5142c8de06445bb208926c6712bfadb972
DebarghaG/desiTesla
/Build/AutoDrive/Move.py
2,892
3.703125
4
""" Utility library to create move in any directionself. Call Move.direction(x) from the CarBrain to control the movement of the carself. """ """ import sys import time import RPi.GPIO as GPIO from gpiozero import OutputDevice #mode=GPIO.getmode() Forward=13 Backward=12 Right = 24 Left = 23 forward_motor = OutputD...
a9e0833231d310079bfe191910868f9bbc23481e
hqnjkkl/tensorflowPrimer
/opt/opt4_4.py
736
3.578125
4
#coding:utf-8 #学习率,就是控制梯度下降的步长,一步有多长 #设损失函数 loss=(w+1)^2,令w初值是常数5.反向传播就是求最优w,即求最小loss对应的w值 import tensorflow as tf import numpy as np #定义待优化参数w初值赋5 w = tf.Variable(tf.constant(5,dtype=tf.float32)) #定义损失函数loss loss = tf.square(w+1) #定义反向传播方法 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) #生成会话,训练40轮 ...
a4686a5cd38eb09197da6d4f96a3ad1266bc5cc7
swhite22/two-number-checker
/two_number_checker.py
273
4
4
num1 = input('please input your first number') num2 = input('please input your second number') if num1>num2: print("Number 1 is bigger than Number 2.") elif num2>num1: print("Number 2 is bigger than Number 1.") else: print("Number 1 and Number 2 are equal.")
5faaa6a114e3fd185810e3eaa0fabddab80c4edc
sndsjh2014/Movie-Trailers
/media.py
464
3.609375
4
import webbrowser class Movie(object): ''' This class provides a way to store movie related information ''' def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): # This is the movie title self.title = movie_title # This is the storyline of the movie self.storyline = movie_storyl...
eaa1a014c6de9ef25136681ad08ead632c093f2f
Luoxsh6/superintendent
/src/superintendent/queueing/utils.py
765
3.796875
4
import numpy as np import pandas as pd def _features_to_array(features: list): """Convert a list of features to a 2D array. Parameters ---------- features : list A list of features to be converted to an array or dataframe. Returns ------- features : Any The array of featu...
aa457dd17d93a3a9ef26ad1468ceffc8fe3c8750
benlind/OnScreenKeyboard
/onscreenkeyboard.py
1,758
3.796875
4
#!/usr/bin/env python # This script inputs a file containing lines of strings. It outputs the # path required to type each line on the DVR keyboard. # Written by Ben Lind, 11/23/14 def DVRKeyPath(inputString): "Returns the path required to type the passed string on the DVR keyboard" keyMap = [['A','B','C','D',...
3db887237d52eaf74293f7c2548b73ad234fe0cd
jwitt88/reddit-matplotlib-data-vis
/single_file/main_single.py
3,645
3.78125
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sys import argv #pass the name of the file for analysis script, filename = argv #get the sub/key from the fiename sub = str(filename.split('-')[0]) #read it into a data frame meta_df = pd.read_csv(filename) #count the number of unique list_...
ef53ff411fae444e0594a60680504a102369831d
ews624/Python-Programming1
/Module10/Turtle.py
1,293
4.0625
4
import turtle from turtle import * def tree(branchLen,leonardo): if branchLen > 5: leonardo.forward(branchLen) leonardo.width(leonardo.width()-1) leonardo.right(20) tree(branchLen-15,leonardo) leonardo.left(40) tree(branchLen-15,leonardo) leonardo.right(20) ...
8592f43ab9ac36547e4cb41772e07cfb92cc54fb
tareq89/foodbank
/foodbank/Insert/functions/distanceCalculate.py
932
3.515625
4
from math import sin, cos, sqrt, atan2, radians import decimal import geopy import geopy.distance def DistanceClaculate(lat1,lon1,lat2,lon2): pt1 = geopy.Point(lat1, lon1) pt2 = geopy.Point(lat2, lon2) # distance.distance() is the VincentyDistance by default. dist = geopy.distance.distance(pt1, pt2).km retu...
43eabf28146b66d523d56f6393a8b5d4970b2461
DeeaMG/SmallGamesPy
/hangman/hangman.py
6,584
4.25
4
''' HANGMAN --- GAME ''' from RandomWords import RandomWordGenerator as generator class PlayHangmanGame: # The given word to guess. HANGING_GIVEN_WORD = generator() # The maximum of chances you have. HANGING_CHANCE_MAX_NUM = 6 # Player name. HANGING_PLAYER_NAME = input("Enter your name:...
86add1c3636ae7fba33b7f74f8c9ede18e1bb9e9
cnfsll/MachineLearning
/Mnist/BN/mnist_bn.py
3,799
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sat May 6 15:15:36 2017 @author: minjiang 针对mnist手写体识别例子,比较使用BatchNormalization和不使用BN时深度网络的性能 """ from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import matplotlib.pyplot as plt mnist = input_data.read_data_sets('MNIST_data', one_hot=True) #...
0b17382baaf4e3948c1e93559907009665c630df
cf19rodrigolindo/Python-LindoRodrigo
/Numero_flotant.py
325
3.96875
4
flotant = float(input("Introdueix un numero flotant: ")) flotant2 = float(input("Introdueix un altre numero flotant: ")) if flotant>flotant2: print (flotant,"és més gran que", flotant2) elif flotant<flotant2: print (flotant, "és més petit que", flotant2) else: print (flotant, "és igual que", flotant2)
a909b5d4cce0c5c5ce3dd52f009939d29ac874a3
illusion98/raspberry
/PT2.py
524
3.671875
4
#from gpio import * import gpio from time import * def main(): gpio.pinMode(0,gpio.OUT) #led gpio.pinMode(1,gpio.IN) #tempsesor gpio.pinMode(2,gpio.IN) #switch # pin 상태, output -> HIGH(3.3v)/ LOW(0v) while 1: tempsensor=gpio.digitalRead(2) print('temp:{}'.format(tempsensor)) button=gpio.digitalRead(...
0b5a477d38fcfaaef47984da112c46c75833cc96
Mrliuyuchao/ds
/6月20/练习2.py
956
3.921875
4
class Node: def __init__(self,data): self.data = data self.next = None def __repr__(self): return 'Node(%s)'%(self.data) class LinkList: def __init__(self): self.head = None #头部插入节点 def insert_head(self,data): new_node = Node(data) if self.head: ...
98aa497b75ad8a54a79b40d6b552d683df77c76c
Mrliuyuchao/ds
/面试题整合/两个数之和.py
1,065
3.59375
4
from typing import List # 第一种方法 # def twoSum(nums:list,target:int): # left = 0 # right = len(nums) -1 # while left < right: # curr = nums[left] + nums[right] # if curr == target: # return [left,right] # else: # if curr < target: # left += 1 # ...
ed39c3de6ac1d1296c487fa8206493b46f3c8998
KrishnaRauniyar/python_assignment_II
/f16.py
1,567
4.125
4
# Imagine you are creating a Super Mario game. You need to define a class to represent Mario. What would it look like? If you aren't familiar with SuperMario, use your own favorite video or board game to model a player. from pynput import keyboard def controller(key): is_jump = False if str(key) == 'Key.ri...
4969f9c7fdbf0a5239bbf1e1e4d226b5ed336196
KrishnaRauniyar/python_assignment_II
/f4.py
629
4.25
4
# Create a list. Append the names of your colleagues and friends to it. Has the id of the list changed? # Sort the list. # What is the first item on the list? What is the second item on the list? # no id of list is not changed def checkId(string): arr = [] print("The is before append: ", id(arr)) for i ...
ded061049d468ca34b16685bb993fcd4d23606b9
AP-MI-2021/lab-4-alexandrulupei
/main.py
4,802
3.828125
4
def coutlist(l): return l def citireLista(): ''' Citeste o lista de nr intregi :return: lista citita ''' l = [] givenstring = (input("scrieti elem listei separate prin virgula")) numbers_as_string = givenstring.split(",") for x in numbers_as_string: l.append(int(...
86aa2df21184214b41d06253f511d90ad086b736
LuizFernandoS/PythonCursoIntensivo
/Capitulo07_InputUsuario_While/07_01LocacaoAutomoveis.py
407
3.609375
4
'''7.1 – Locação de automóveis: Escreva um programa que pergunte ao usuário qual tipo de carro ele gostaria de alugar. Mostre uma mensagem sobre esse carro, por exemplo, “Deixe-me ver se consigo um Subaru para você.” livro pg 171 pdf pg 156 ''' carro = input("\nQual marca de carro você gostaria de alugar? ")...
8997c7f99aaf30cc10052590b11156b842204423
LuizFernandoS/PythonCursoIntensivo
/Capitulo06_Dicionarios/06_03Glossary.py
1,363
4.15625
4
#"""6.3 – Glossário: Um dicionário Python pode ser usado para modelar um #dicionário de verdade. No entanto, para evitar confusão, vamos chamá-lo de #glossário. #• Pense em cinco palavras relacionadas à programação que você conheceu #nos capítulos anteriores. Use essas palavras como chaves em seu glossário e #arma...
94cde4051e6db02004ef208d052c79dd0dbd95ff
LuizFernandoS/PythonCursoIntensivo
/Capitulo05_InstrucoesIF/05_07FrutaFavorita.py
1,074
4.03125
4
#5.7 – Fruta favorita: Faça uma lista de suas frutas favoritas e, então, escreva uma série de instruções if independentes que verifiquem se determinadas frutas estão em sua lista. #• Crie uma lista com suas três frutas favoritas e chame-a de favorite_fruits. #• Escreva cinco instruções if. Cada instrução deve verific...
064a70b66d0b9ac03455dedd3c7e857b7bfdb5aa
LuizFernandoS/PythonCursoIntensivo
/Capitulo03_IntroducaoListas/03_02Salute.py
505
4.28125
4
"""3.2 – Saudações: Comece com a lista usada no Exercício 3.1, mas em vez de simplesmente exibir o nome de cada pessoa, apresente uma mensagem a elas. O texto de cada mensagem deve ser o mesmo, porém cada mensagem deve estar personalizada com o nome da pessoa.""" #pg73 names=['Jorge', 'Victor', 'Ângelo'] print(...
7b549e195ea36dba547744025e6e9b03fa487a3a
LuizFernandoS/PythonCursoIntensivo
/Capitulo05_InstrucoesIF/05_11OrdinalNumbers.py
778
4.34375
4
#5.11 – Números ordinais: Números ordinais indicam sua posição em uma lista, #por exemplo, 1st ou 2nd, em inglês. A maioria dos números ordinais nessa #língua termina com th, exceto 1, 2 e 3. #• Armazene os números de 1 a 9 em uma lista. #• Percorra a lista com um laço. #• Use uma cadeia if-elif-else no laço para ...
6e23568c6a10fecd7e15940c24e1bdec2dc40665
LuizFernandoS/PythonCursoIntensivo
/Capitulo03_IntroducaoListas/03_05DinerGuestsChange.py
1,534
3.734375
4
"""3.5 – Alterando a lista de convidados: Você acabou de saber que um de seus convidados não poderá comparecer ao jantar, portanto será necessário enviar um novo conjunto de convites. Você deverá pensar em outra pessoa para convidar. • Comece com seu programa do Exercício 3.4. Acrescente uma instrução print no fin...
b6f55bdf50f4a5e04683937010fbaaf5dc7af696
athulyack/lists
/sort according to noof occurence.py
386
3.6875
4
#program to sort array accoding to their no of occurence ar=[1,1,2,2,2,2,3] new={} for i in ar: k=ar.count(i) new[k]=i n=new.keys() n=list(n) n.sort() n1="" for i in n: n1+=str(i) n1=n1[::-1] n1=list(n1) for i in range(len(n1)): n1[i]=int(n1[i]) final="" for i in n1: f=str(new[i])*i final+=f f...
db5e74dd420fdc7f82c14ac627807651d57a901e
ayeon0804/MULTICAMPAS
/PyCharm/day5_1.py
9,023
3.78125
4
# 함수의 종류 ''' - 사용자 정의 함수 - 빌트인함수 : 외장함수 , 내장함수 ''' # 수학관련 내장 함수 # 절대값 리턴 : abs(숫자) # 최대값 리턴 : max(리스트/튜플/집합...) # 최소값 리턴 : min(리스트/튜플/집합...) x = -800 y = 900 print(f'x의 절대값 = {abs(x)} , y의 절대값 = {abs(y)}') # x의 절대값 = 800 , y의 절대값 = 900 # 리스트의 절대값 반환 numList = [100, 0, -90, 80, -55, -500] temp = [] for i...
4f1a5ab9e6ef1dcb753512eb97afdd936d1a4ae9
ayeon0804/MULTICAMPAS
/PyCharm/day2_퀴즈.py
3,551
3.78125
4
''' 2개의 리스트를 정의하고 다음과 같이 출력한다. myList1 : ['홍길동', '신데렐라', '알라딘', '장화', '홍련', '지니', '엘리스'] myList2 : ['토끼', '거북이', '물개', '펭귄'] 2개의 리스트 합 : (결과값 출력 ) 4개만 출력 : (결과값 출력 ) 짝수번째만 출력 : (결과값 출력 ) 홀수번째만 출력 : (결과값 출력 ) 총 길이 : 11 ''' # 퀴즈 1 myList1 = ['홍길동', '신데렐라', '알라딘', '장화', '홍련', '지니', '엘리스'] myList2 = ['토끼',...
e2d5cb5b67733aea84e5bbbfc4fb8389c55b49f3
anuragbisht12/AlgoExpert-Problems
/90_LongestStringChain.py
1,689
3.65625
4
# O(n*m^2+nlog(n)) time | O(nm) space where n is number of strings and # m is the length of longest string def longestStringChain(strings): stringChains={} for string in strings: stringChains[string]={"nextString":"","maxChainLength":1} sortedStrings=sorted(strings,key=len) for string in sortedStrings: f...
3c0770fe60bbf36efc27adb5810d99d67d8ee407
shashwat1225/Udacity_Data_Structure_Nanodegree_Project_2
/problem_6.py
3,476
3.796875
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" ...
8298f18558bafdb08a2a7d9d1f5eebce478bc225
ArthurNoga/StructureALgoExam
/finalRevV5clean/src/python/andyrecap/LinkedList.py
9,259
3.859375
4
from nodeClass import Node class LinkedList(): def __init__(self): self.first: Node = None self.last: Node = None self.taille: int = 0 def __str__(self): n: Node = self.first affichage: str = "" for i in range(0, self.taille): if n.get_value() is N...
fc5c5383005341bd1d56e119dae84f5a3868b00d
ArthurNoga/StructureALgoExam
/finalRevV5clean/src/python/andyrecap/arrayClass.py
12,617
3.890625
4
import ctypes import math class DynamicArray(object): def __init__(self, capacity: int = 10): self.n: int = 0 # by default self.capacity: int = capacity # by default self.A = self.__make_array(self.capacity) def __str__(self): """ return the array representation ...
91afa48f00f5f32723026e5ba91bc3111498adaa
Data-Analisis/scikit-learn-mooc
/python_scripts/cross_validation_ex_02.py
1,935
4.0625
4
# %% [markdown] # # 📝 Exercise 02 # # This notebook aims at building baselines classifier with which we can compare # our predictive model. Besides, we will check the differences with the # baselines that we saw in regression. # # We will use the adult census dataset but only the numerical features. # %% import panda...
b65ccc14af241a58ba6822cee6ffe2abb5993192
Data-Analisis/scikit-learn-mooc
/python_scripts/ensemble_gradient_boosting.py
9,772
3.65625
4
# %% [markdown] # # Gradient-boosting decision tree (GBDT) # # In this notebook, we present gradient boosting decision tree algorithm and # the difference with AdaBoost. # # Gradient-boosting differs from AdaBoost due to the following reason: instead # of assigning weights to specific samples, GBDT will fit a decision ...
73181b0a6495350ba3b6bfd29da0f000da2ca5f2
Data-Analisis/scikit-learn-mooc
/python_scripts/parameter_tuning_sol_01.py
2,951
4.375
4
# %% [markdown] # # 📃 Solution for introductory example for hyperparameters tuning # # In this exercise, we aim at showing the effect on changing hyperparameter # value of predictive pipeline. As an illustration, we will use a linear model # only on the numerical features of adult census to simplify the pipeline. # # ...
5195135646e6e552d819ae0fabdf0875737a0e8b
Data-Analisis/scikit-learn-mooc
/python_scripts/ensemble_hist_gradient_boosting.py
6,148
3.671875
4
# %% [markdown] # # Speeding-up gradient-boosting # In this notebook, we present a modified version of gradient boosting which # uses a reduce number of split when building the different trees. This # algorithm is called histogram gradient boosting in scikit-learn. # # We previously mentioned that random-forest is an e...
007d41ec4d211e0b21867d7fd5522b27b0f6bca4
Data-Analisis/scikit-learn-mooc
/python_scripts/trees_dataset.py
3,519
3.859375
4
# %% [markdown] # # Presentation of the datasets # # Before we present tree-based models, we will make a quick presentation of the # [Palmer penguins dataset](https://allisonhorst.github.io/palmerpenguins/) # dataset. We will use this dataset for both classification and regression # problems by selecting a subset of th...
a58ef9d8edf95bab62443dd5c214b4ad49b72842
Data-Analisis/scikit-learn-mooc
/python_scripts/trees_hyperparameters.py
5,156
3.890625
4
# %% [markdown] # # Importance of decision tree hyperparameters on generalization # # In this notebook will illustrate the importance of some key hyperparameters # of the decision tree. We will illustrate it on both the classification and # regression probelms that we previously used. # # ## Load the classification and...
086c135b65c622f604c3c2d78eb17457cb54e257
Data-Analisis/scikit-learn-mooc
/python_scripts/linear_models_sol_04.py
3,313
3.6875
4
# %% [markdown] # # 📃 Solution for Exercise 04 # # In the previous notebook, we illustrated how a regularization parameter of # ridge model need to be optimized by hand. However, this way of optimizing # hyperparameters is not effective: only a single split was used while # cross-validation could be used. # # This exe...
444c7a816b14fbba4ae4775c2d2e83990bf3adf8
anthonychu00/Chatroom
/client.py
1,947
3.828125
4
import socket import select import sys import msvcrt # checks if user entered 3 arguments # ideally in this project, the IP address would be localhost (127.0.0.1) as well if len(sys.argv) != 3: print("Please enter args in following order: IP Address, port") exit() if not (sys.argv[2]).isdigit(): print("Por...
e1f9daa708090945d51fafa50606961b91f9e666
not-a-lawyer/insult_classifier
/mark_everything.py
1,542
3.5625
4
#TODO check whether dummy classifier also does this def count_true_positive(two_column_data_set): positive_count = 0 for data in two_column_data_set["class"]: ##Hate Speech is labelled 0 in this project if data == 0: positive_count += 1 return positive_count def compute_preci...
f9e7b9e8622bec6efc8336a52d918eb248ad574c
freefromix/dataScienceTheory
/machineLearningTheory/myNumpy/logistic_regression/logistic_regression_nn.py
10,271
4.125
4
"""Logistic Regression with a Neural Network mindset This is a demo program to see logistic regression in action. """ import numpy as np import matplotlib.pyplot as plt import sys import os sys.path.append(os.path.abspath('..')) import imageNp import load_f5 def sigmoid(z): """Compute the sigmoid of z Args...
459007654ecb635814516383263d1ad0dae035d6
freefromix/dataScienceTheory
/machineLearningTheory/myVisualization/myMatplotlib/1_matplotlib_part1.py
998
3.734375
4
import matplotlib print(matplotlib.get_backend()) import matplotlib.pyplot as plt import numpy as np from pylab import * x = np.linspace(0, 5, 11) y = x ** 2 plt.plot(x, y) plt.xlabel('X label') plt.ylabel('Y label') plt.title('This is my plot title') plt.subplot(1, 2, 1) plt.plot(x, y, 'r') plt.title("This is ...
88b1f98c5ac73feb414dd9176a0bf761006c22d7
ojhermann-ucd/ProjectEuler
/_15_Lattice_paths/_15_Lattice_paths.py
216
3.8125
4
def factorial(n, holder): if n == 2: return 2 * holder else: return factorial(n-1, holder * n) numerator = factorial(40, 1) denominator = factorial(20, 1) * factorial(20, 1) print(int(numerator / denominator))
5ff9a80ad4123fd74cfd1062bf5634bc8d7f1da7
ojhermann-ucd/ProjectEuler
/_17_Number_letter_counts/quick_and_dirty.py
1,567
3.5
4
sub_twenty_dict = { 0:"", 1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen", 18:"eighteen", 19:"nineteen", } tens_dict = { 0:"", 20:"twenty", 30:"...
6e6fbe5717a747884ba539dc802ddae1d26e80c2
ojhermann-ucd/ProjectEuler
/_12_Highly_divisible_triangular_number/factors.py
711
3.84375
4
def factors(n): # starting data divisor = 2 dividend = n # return data divisor_list = [1] dividend_list = [n] # populate lists while divisor < dividend_list[-1]: if dividend % divisor == 0: divisor_list.append(divisor) dividend_list.append(int(dividend / divisor)) divisor += 1 # return dividend_list...
de63f550d582b2a7cc755c8a85de9a72a2aef59a
ojhermann-ucd/ProjectEuler
/_20_Factorial_digit_sum/solution.py
190
3.734375
4
def factorial(n): factorial = 1 multiplier = n while multiplier > 1: factorial *= multiplier multiplier -= 1 return factorial print(sum([int(x) for x in list(str(factorial(100)))]))
82045b8f6cc35314b4a97e964c7306e0d63e4e3c
damlakonur/playground
/user.py
2,990
3.953125
4
class User: def __init__(self, name, surname, email, number): self.name = name self.surname = surname self.email = email self.number = number class Book: def __init__(self): self.users = [] def add_user(self, name, surname, email, number): self.users.append(...