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
784190e6364fc07ee04537756d816571b4060bc4
IkerSedanoSanchez/TIC-II-20_21
/adivino_IkerSedano.py
347
3.78125
4
def adivino(): numero=input("Dime un numero del 1 al 10") intento=input("intentalo: ") while intento!=numero: if intento>numero: print "Demasiado grande" if intento<numero: print "Demasiado pequeno" intento=input("intentalo de nuevo") print "Ahora...
5d5505f9a93cb5bf30054304a2d6e86fda9017d7
IkerSedanoSanchez/TIC-II-20_21
/7_letra_funcion2_IkerSedano.py
1,176
4.03125
4
def letra_funcion(): print """ ***MENU*** S de suma R de resta M de multiplicacion D de division""" interruptora=1 while(interruptora==1): numero=input ("Introcuzca el primer numero: ") numero2=input ("Introduzca el segundo numero: ") funcion=raw_in...
09fd2d4e77c3bb2ce2401f583a567c6351aaf2d7
veryobinna/assessment
/D2_assessment/SOLID/good example/liskov_substitution.py
1,345
4.125
4
''' Objects in a program should be replaceable with instances of their base types without altering the correctness of that program. I.e, subclass should be replaceable with its parent class As we can see in the bad example, where a violation of LSP may lead to an unexpected behaviour of sub-types. In our example, "i...
8a019f465421cf836b9596fc994db78e24d28760
veryobinna/assessment
/SOLID/bad example/liskov_substitution.py
1,585
3.78125
4
''' Objects in a program should be replaceable with instances of their base types without altering the correctness of that program. I.e, subclass should be replaceable with its parent class The violation of LSP here is that a `Prisoner` is not a suitable substitution of `Person` since they "behave" differently. Remem...
47d1664da65f239ae39ff3a740cf8f6c40798285
ak2906/Clique-Isp-program
/isp.py
1,679
3.546875
4
import sys import random def failure(): print("No independent set present") sys.exit() def success(s1,s2): print("Independent set present") print(s1) print(s2) def isp(m,vertex1,t1,n): s1=[] s2=[] for i in range(t1): while(len(s1)<t1): x=random.choic...
8032170c30b1f128ac9a73cd40097d4a2020ed07
190965/I2P-2017-S1-Quizv3
/Chocolate Machine.py
328
3.921875
4
ChocoBar=(16.90) print("Chocolate bar is",ChocoBar) Cash=float(input("How much money are you going to pay with?:")) Changedue=(Cash-ChocoBar) print("Change =",Changedue) onedollar=1 twodollars=2 fivedollars=5 tendollars=10 while Changedue>10: Changegiven=(Changedue-10) while Changedue>5: Changegiven=(Changedu...
e1733000ddfdf22519225f0583c8998636d469cc
190965/I2P-2017-S1-Quizv3
/Name and Age.py
309
4.0625
4
name=(input("What is your name:")) print(name) age=(int(input("How old are you?:"))) print(age) print("Hi", name, "you are", age, "years old") days=age*365 hours=days*24 minutes=hours*60 seconds=minutes*60 print(name,"You have been alive for",days,"days,",hours,"hours,",minutes,"minutes,",seconds,"seconds")
ea2e9c0f638b63ba7436d8aa293dd727d1daeb40
abr-98/image-reader-python
/image_operations.py
711
3.59375
4
import image_rotation import image_crop import image_resize def rotate(str): img_rotate(str) def crop(str): img_crop(str) def resize(str): img_resize(str) def img_opt(): str=raw_input("Enter the image ") ch_int=1 while ch_int != 4: print("-----------------------OPTIONS--------------...
69e3015a61b3bb4d252c148655a21f35d8445707
gpapalambrou/course_Python
/codes/p43.py
226
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 15 06:34:36 2019 @author: gpapalambrou """ def a(x, y): """Adds two variables x and y, of any type.Returns single value.""" return x + y help(a)
cd61f72f308e3b735fab29e2e4473d3e1c588637
gpapalambrou/course_Python
/codes/atom.py
348
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 09:30:29 2019 @author: gpapalambrou """ class AtomClass: def __init__(self, Velocity, Element = 'C', Mass = 12.0): self.Velocity = Velocity self.Element = Element self.Mass = Mass def Momentum(self): retu...
eeb4417e9f419a311fb639aeada768728c113f28
tekichan/teach_kids_python
/lesson5/circle_pattern.py
897
4.34375
4
from turtle import * bgcolor("green") # Define Background Color pencolor("red") # Define the color of Pen, i.e our pattern's color pensize(10) # Define the size of Pen, i.e. the width of our pattern's line radius = 100 # Define the radius of each circle turning_angle = 36 # Define how much the ...
c0ca0bd29975db7f07427345b3d2fe6f1296e676
develooper1994/PrimeNumberGenerator
/source-ders1/asal kodlarım/main1.py
2,597
3.671875
4
''' Created on 8 Eyl 2016 @author: robotik ''' from test.test_binop import isnum print('python') print() print('robotik '*5,end='-*-*-*-*-*-*-*-*-*') # end varsayılan olarak '\n'satır başıdır. siz end yerine ne koyarsanız print onu yapar. print('3.1 '+'2.2 '*3) print(float('3.1')+float('2.2')) #print(int('3...
7310422db38a47c865475379e69c7fe487ea590f
hj2809/assignment1
/assignment.py
1,366
3.640625
4
import string_calculator import pytest def test_empty_string(): """it should return 0 if the string is empty""" assert string_calculator.add('') == 0 def test_add_two_CSVs(): """it should add 2 numbers in a comma separated string""" assert string_calculator.add('1, 2') == 3 def test_add_multiple_CSVs(): """it s...
4cfdfdf135413dc4814e3d37bd0292dcfe9537eb
ttran2/random-stuff
/primes/primes.py
453
3.953125
4
#!/usr/bin/python import sys for a in sys.argv[1:]: try: n=int(a) except: continue if n<2: print a+" is NOT a prime" continue #for i in range(2,int(n**0.5)+1): #all numbers between 2 and n^0.5+1 for i in range(2,int(n**0.5)): #for i in range(2,n/2): if n%...
03b57f9f0e1aae33faa9739f20c4489e2b34ac51
tylere/pykml
/src/examples/misc/hello_world/hello_world_5_globe_scale.py
1,144
3.625
4
#!/usr/bin/python # a Python script that uses pyKML to create a Hello World example from lxml import etree from pykml.factory import KML_ElementMaker as KML text = 'Hello World!' # create a document element with a single label style kmlobj = KML.kml( KML.Document( KML.Style( KML.LabelStyle( ...
4bcddbde0bcaf75f8bf54b0124be4f402144fc21
tylere/pykml
/src/pykml/test/__init__.py
473
3.734375
4
from xmldiff import main, formatting def compare_xml(tree1, tree2): """Compare two XML trees.""" tree_diff = main.diff_trees(left=tree1, right=tree2, formatter = formatting.DiffFormatter(pretty_print=True)) if len(tree_diff) == 0: retu...
040c56cf90dc5e02874c16273ac2a83b8dad9cc2
abhilashaop/Computer-Vision
/hough.py
892
3.765625
4
import numpy as np import cv2 as cv # hough transform is a popular technique to detect any shape if you can represent that shape in a mathematical form. # It can detect the shape even if thr image is broken or distorted . #steps of hough transform are: # a. edge detection using canny mehtod # b. mapping of edge point...
33c30ab1d4ae19c1e7e1bfe5b4bb4a0a07f3d046
DaniloSilva14/AlgoritmosDeOrdenacao
/selectionSort.py
348
3.625
4
def selectionSort(arr, n): for i in range(n): min_idx = i for j in range(i+1, n): if arr[min_idx] > arr[j]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] arr = [50, 40, 30, 20, 10] n = len(arr) print ("Vetor Desordenado:") print (arr) selectionSort(arr,n) print ("\n\nVet...
4df3921f3df9edf313f2bc3985cf0ba9956ab7c9
kenifranz/pylab
/best_cars.py
216
4.0625
4
best_cars = ['Mercedes', 'Toyota', 'BMW', 'Nissan'] best_cars[-1] = 'Land Rover' best_cars[1] = 'Audi' print (best_cars) best_cars.append('Jaguar') #append will add a new item at the end of the list print(best_cars)
15e49688c27e8237138889efa46963ffa4775c91
kenifranz/pylab
/popped.py
309
4.28125
4
# Imagine that the motorcycles in the list are stored in chronological order according to when we owned them. # Write a pythonic program to simulate such a situation. motorcycles = ['honda', 'yamaha','suzuki'] last_owned = motorcycles.pop() print("The last motorcycle I last owned was "+ last_owned.title())
3408fff8ea5b1171beea3c7d618ce8e3b9369f72
JaredColon-Rivera/The-Self-Taught-Programmer
/.Chapter-3/Challenge_7.py
227
4.03125
4
age = 17 if age >= 21: print("You can legally drink!") elif age < 21 and age >= 18: print("You can't drink, but you can buy cigars!") elif age < 18: print("You really can't do anything except see 'It' without your parents")
fb9903c28aaf1aec877b8db2e59066bf5ee6cef0
JaredColon-Rivera/The-Self-Taught-Programmer
/.Chapter-7/Challenge_4.py
397
4.03125
4
list_num = [1, 2, 3, 4, 5, 6, 7, 8, 9] guess_q = "What number is in the list?: " while True: print("Input q to quit") guess = input(guess_q) if guess == "q": print("Goodbye") break try: guess = int(guess) except ValueError: print("please type a number or q to quit") if guess in list_num: print("You got ...
6c7e27e3fc262767b72f94eb360276fcdf933d9b
JaredColon-Rivera/The-Self-Taught-Programmer
/.Chapter-4/Challenge_1.py
91
4
4
x = int(input("Type in a number: ")) print(x*x) """ Takes in a number and squares it """
17f39a18c96ac3f6a3bb1646da4d01875b1889e6
JaredColon-Rivera/The-Self-Taught-Programmer
/.Chapter-3/Challenge_4.py
233
4.375
4
x = 10 if x <= 10: print("The number is less than or equal to 10!") elif x > 10 and x <= 25: print("The number is greater than equal to 10 but it is less than or equal to 25!") elif x > 25: print("The number is greater than 25!")
b60be2850fc472d968cb90bb0a896c7761545ed9
banxia1994/python-learn
/prepare/AlgorithmsByPython-master/MapReduce_and_filter.py
2,379
3.5
4
# -*- coding:UTF-8 -*- import functools # Python3.x和Python2.x对于map、reduce、filter的处理变得不同 # Python3.x中map和filter的输出是一个map型和filter型, 需要从里面取出需要的值 # Python2.x中map和filter输出的直接是一个list # Python3.x中使用reduce需要引入functools # map是用同样方法把所有数据都改成别的..字面意思是映射..比如把列表的每个数都换成其平方.. # reduce是用某种方法依次把所有数据丢进去最后得到一个结果..字面意思是化简..比如计算一个列表所有数的和的过...
ab6bf361eae978cf5b0f701f7f63ac6df10a12b1
sureshbvn/leetcode
/trees/dfs_left_side_view.py
691
3.6875
4
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = None self.right = None def leftSideView(root): if root is None: return [] leftSide = [] def helper(node, level): if level==len(leftSide): leftSide...
7aa38fdee29def47ffa177874aec3e6c5e4e342d
sureshbvn/leetcode
/trees/156_dfs_binary_tree_upside_down.py
1,214
3.796875
4
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def upsideDownBinaryTree(root): if root is None: return None globalroot = [None] def dfs(node, parentNode, rightNode): oldleft = n...
c32434949033bd85a29003c4edab0adedd1cc361
sureshbvn/leetcode
/recursion/reverse_string.py
246
3.953125
4
def reverseString(s): def helper(s, start, end): if start == end: return s[start] return helper(s, start+1, end) + s[start] return helper(s, 0, len(s)-1) print(reverseString("suresh"))
d6bd643d0da7cfb11fd22a0d0b346171fba82b24
sureshbvn/leetcode
/recursion/subset_sum.py
952
4.25
4
# Count number of subsets the will sum up to given target sum. def subsets(subset, targetSum): # The helper recursive function. Instead of passing a slate(subset), we are # passing the remaining sum that we are interested in. This will reduce the # overall complexity of problem from (2^n)*n to (2^n). ...
8a787fb2c5bee3282b723d4bd45d6ba78bfbc5d5
pravinv1998/python_codeWithH
/name.py
180
4.09375
4
# print simple name name="pravin" print("Pravin Wargad",name) # handle string print(name[0:]) print(name[:-1]) # to count length of string length=len(name) print("lenth is ",length)
5d0d3522cee1193cb0765c366e7d5d73a583aab2
pravinv1998/python_codeWithH
/newpac/read write file.py
339
4.15625
4
def read_file(filename): ''' 'This function use only for read content from file and display on command line' ''' file_content = open(filename) read_data = file_content.read() file_content.close() return read_data n=read_file("name.txt") print(n) print(read_file.__doc__) # read the ...
0d3445778886b9a5b4454e4d437dead6398c4c39
pravinv1998/python_codeWithH
/newpac/Health_system.py
2,784
3.828125
4
''' this program is use to log perticular persons food data ''' def getdate(): import datetime return datetime.datetime.now() # print(getdate()) try: def write_log(name,food_item): ''' this function use for only write file at append mode :param name: name and food_item :...
af03c2d029e68ad8fe818ba61b776f1afb8b1222
dmeckley/Course
/course.py
817
4.09375
4
class Course(object): # Initializer Constructor Method: def __init__(self, courseName): """Initializes self.__courseName variable and self.__students list.""" self.__courseName = courseName self.__students = [] # Accessor Methods: def getStudents(self): """Returns self.__students list.""" return(se...
3acc3989c6b539caa092896f3c7d3c5e466f6c2c
AtomIOI/PythonTutorial
/Tests/test_Inheritance.py
443
3.796875
4
import unittest from Tutorial.Inheritance import Person, Student class MyTestCase(unittest.TestCase): def test_inheritance(self): person = Person("John", "Smith") self.assertEqual("John Smith", person.printname()) student = Student("Adam", "Kovic", 2019) self.assertEqual("Adam Kov...
bc4906e63fbb7278109151edfd73f7d06cc38630
abalulu9/Sorting-Algorithms
/SelectionSort.py
701
4.125
4
# Implementation of the selection sorting algorithm # Selection sort takes the smallest element of the vector, removes it and adds it to the end of the sorted vector # Takes in a list of numbers and return a sorted list def selectionSort(vector, ascending = True): sortedVector = [] # While there are still elements...
f32f8b9e269ecd353396b052d2ec4e7167f55f8f
achyudh/hackerrank-solutions
/python/noPrefixSet.py
1,082
3.78125
4
#!/bin/python3 import os import sys class TrieNode: def __init__(self): self.isLastChar = False self.childNodes = dict() class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): hasNewChar = False currentNode = self.root for char in...
2f28f3c4f6c93913345c688e688662eb228879ed
stanislav-shulha/Python-Automate-the-Boring-Stuff
/Chapter 6/printTable.py
997
4.46875
4
#! python3 # printTable.py - Displays the contents of a list of lists of strings in a table format right justified #List containing list of strings #rows are downward #columns are upward tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goo...
96a3ec7334436703a69c3d4bd396eb3f99ca5bf2
stanislav-shulha/Python-Automate-the-Boring-Stuff
/Chapter 4/CommaList.py
733
4.59375
5
#Sample program to display a list of values in comma separated format #Function to print a given list in a comma separated format #Takes a list to be printed in a comma separated format def comma_List(passedList): #Message to be printed to the console message = '' if len(passedList) == 0: print('Empty List') ...
2b7df14561403960fe975298193f7863d79d2987
charlesumesi/ComplexNumbers
/ComplexNumbers_Multiply.py
1,049
4.3125
4
# -*- coding: utf-8 -*- """ Created on 16 Feb 2020 Name: ComplexNumbers_Multiply.py Purpose: Can multiply an infinite number of complex numbers @author: Charles Umesi (charlesumesi) """ import cmath def multiply_complex(): # Compile one list of all numbers and complex numbers to be multiplied ...
d52cba35244df859534780c2015525667194398d
PurpleMyst/aoc2017
/05/second.py
528
3.875
4
#!/usr/bin/env python3 def steps_to_leave(maze): pc = 0 steps = 0 while True: assert pc >= 0 try: value = maze[pc] except IndexError: return steps if value >= 3: maze[pc] -= 1 else: maze[pc] += 1 pc += valu...
1971488ba05250620c94218f23f23819243149be
PurpleMyst/aoc2017
/09/second.py
353
3.671875
4
#!/usr/bin/env python3 import re ESCAPED_CHARS_REGEXP = re.compile(r"!.") GARBAGE_REGEXP = re.compile(r"<(.*?(?<!!))>") def main(): with open("input.txt") as input_file: data = input_file.read() data = ESCAPED_CHARS_REGEXP.sub("", data) print(sum(map(len, GARBAGE_REGEXP.findall(data)))) if __...
3d354cd1c4e773dee69e1b41201c83e943a11ed7
PurpleMyst/aoc2017
/03/first.py
878
4.1875
4
#!/usr/bin/env python3 UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) NEXT_DIRECTION = { RIGHT: UP, UP: LEFT, LEFT: DOWN, DOWN: RIGHT } def spiral_position(target): assert target >= 1 x, y = 0, 0 value = 1 magnitude = 1 direction = RIGHT while True: for _...
32e27a1fa28ab89fd90d27879cddb02a653714bb
cleberq/Python
/Python-Avancado01.py
1,074
3.515625
4
''' CLASSE TIME() #primeiro deve-se importar a classe time #Essa clase é um vetor, que em sua lista traz: semana,mes,dia,hora,min,seg,ano import time #em seguida construir o codigo #comando time.asctime() traz a data e hora exemplo: Fri Jun 21 08:26:57 2019 t = time.localtime() #para ver a estrutura print (time.loc...
7986bdf165225ad99e6f58144120180a86b07ef5
cleberq/Python
/Py-Matplotlib.py
364
3.921875
4
import matplotlib.pyplot as plt from pandas import DataFrame ##### plt.plot([1, 3, 5], [2, 5, 7]) plt.show() ########### data = {'Estado': ['Santa Catarina', 'Paraná', 'Goiás', 'Bahia', 'Minas Gerais'], 'População': [1.5, 1.7, 3.6, 2.4, 2.9]} frame = DataFrame(data) print(frame) ############ plt.plot(frame['Es...
07c153b5c614a74207d2f33e098ee2135990a80d
sd2020spring/toolbox-ai-and-algorithms-liloheinrich
/astar.py
12,147
3.84375
4
import pygame # http://www.raywenderlich.com/4946/introduction-to-a-pathfinding class GridWorld(): """Grid world that contains Pauls (and other things) living in cells.""" def __init__(self, width=10, height=10, cell_size=50): pygame.init() screen_size = (height * cell_size, width * cell_size...
7acd91998c767b727f83ae3cc0b8ce051e01ad8c
ranlix/RenameM3U8
/renameM3U8.py
858
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys dir_path = sys.argv[1] # dir_path = r"E:\m3u8s" # m3u8_list = [] def rename(filepath): """ 重命名: abcd%5Fefg-1.m3u8 --> abcd_efg-1.m3u8 abcd%5Fefg-2.m3u8 --> abcd_efg-2.m3u8 """ files = os.listdir(filepath) for i in files: ...
b697dd05a1f6be16c38a05c7c046b0a9e94f2f60
vijaylingam/Cryptography
/RSA/keygeneration.py
3,717
4.125
4
__author__ = 'vijaychandra' import random import math lambdavalue = input('Input the value of lambda: '); x = int(int(lambdavalue) / 2); print("The value of x (size of prime) is: %d" % x); def rabinMiller(num): # Returns True if num is a prime number. s = num - 1 t = 0 while s % 2 == 0: # k...
b464df6db818ec9e25b7b2e26edf812a690b7278
erchiggins/pairing-rc-w2-2020
/make_change_with_cache.py
2,962
3.5625
4
import unittest def make_change_no_cache(amount, denominations): # print(f'entering make_change with {amount}, {denominations}') combos = [] if all([amount < denom for denom in denominations]): return [] for denom in denominations: # print(f'evaluating denom {denom}') if denom == amount: com...
1222666257d78bb5b96318c0871c674ccbb4a60b
ACour008/nlp-text-adv
/item.py
3,751
3.65625
4
from preconditions import check_preconditions class Item: """Items are any objects that a player can get, or otherwise examine.""" def __init__(self, name, description, examine_text="", take_text="", start_at=None, gettable=True, take_fail = "", use_data = None, use_fai...
b80fe77cf2662326c372c92cf8c34f1317dc2ca7
neilmb/adhoc-problems
/slcsp/slcsp.py
4,061
3.78125
4
"""Find second-lowest-cost silver plans by zip code. This reads an input file of zipcodes in CSV format, computes the SLCSP for each zip code using the data in `plans.csv` and `zips.csv` in the current directory, and outputs the results in CSV format on standard out. """ import csv import sys from collections import...
da8a388917a4b85834ad1972b9f3000f098c7cfc
v1ct0r2911/semana8
/ejercicio5.py
403
3.96875
4
#5. Elabore un algoritmo que imprima la tabla de multiplicar de un número ingresado por teclado. # Este número deberá ser positivo, en caso que ingrese un número negativo deberá emitir un mensaje # de error: NUMERO INCORRECTO cont=1 i=int(input("ingrese numero:")) if i>0: while cont <=12: tabla=cont*i ...
d299761952fcd762c0b8e8b9a7100fd1f582ff30
Uzair-Jamal/python-bootcamp
/Day 13.py
1,038
3.609375
4
#Q1: import re def check_string(string): charRE = re.compile(r'[^a-zA-Z0-9.]') string = charRE.search(string) return not bool(string) print(check_string("%$%%^&*(#$#%$%")) print(check_string("dsffcdsafcccsdvsd4545454")) #Q2: def match_word(s): word = '\w\d' if re.search (word,s): ...
1066736bf951dc84d3b1e64988fd7d61f5e41ccf
arakaneyuta/python
/sort_algorithm/babble_sort.py
239
3.640625
4
def babble(array): for j in range(0,len(array)-1): for i in range(0,len(array)-1): if array[i] > array[i+1]: tmp = array[i] array[i]=array[i+1] array[i+1]=tmp print array array = [21,4,5,61,2,7,300,44,56] babble(array)
333602d8d3000f102a3b32f3281ca6596e4572bb
data-plum/courses_prometheus
/find_fraction.py
766
3.8125
4
def find_fraction(summ): def nod(numerator, denominator): a = numerator b = denominator if (a % 2 == 0 and b % 2 == 0) or\ (a % 3 == 0 and b % 3 == 0) or\ (a % 5 == 0 and b % 5 == 0) or\ (a % 7 == 0 and b % 7 == 0): return True if summ <= 2: return False else: if summ % 2 == 0: nume...
26cd2c872a98b01bcad51e6f158640ca5b7b99d9
AngeloG-2/Candy-Recommendation-Using-Nearest-Neighbors
/candy recommendation.py
1,350
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 13:24:08 2019 @author: Angelo Gaerlan """ import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestNeighbors #All possible features for a Candy chocolate = 1 fruity = 0 caramel ...
022ed45ff906e0443a4e37070f4e024cd88f84e9
anli5005/covid-19-research
/safegraph/filter-places.py
614
3.53125
4
import pandas as pd print("key,type") places = pd.read_csv("places.csv", index_col=0, names=["","bb","code","key"]) for index, row in places.iterrows(): code = str(row["code"]) if code.startswith("721"): print("%s,0" % row["key"]) elif code.startswith("722"): print("%s,1" % row["key"]) ...
0328dec6bff3a1139961cff5513852a602b2bf45
AZ9tumas/Math-Parser
/lexer.py
2,045
3.53125
4
from tokens import * import string DIGITS = '0123456789' LETTERS = string.ascii_letters class Lexer: def __init__(self, expression): self.expression = expression self.idx = -1 self.current_char = None self.advance() def advance(self): self.idx += 1 ...
f6773157af8fefb8582193cde46986b45978b277
yairdaon/LasMap
/tests/make_data.py
1,149
3.5625
4
import numpy as np import pandas as pd import os def make_simple_data(): '''Data with known distances between data points ''' x = np.ones(3) obs = np.array([1.,2.,3.,4.]) data = np.empty( (4,3) ) ## So first line is distance 1 from x v = np.array( [2,-1,3] ) v = v / np.linalg.norm(v...
007f176e9d38b1d07543cda8113ae468d31daa28
andresjjn/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
779
4.375
4
#!/usr/bin/python3 """ Module Print square This document have one module that prints a square with the character #. Example: >>> print_square(4) #### #### #### #### """ def print_square(size): """Add module. Args: size (int): The size length of the square. Reises: TypeE...
0366faf5b1eed979333805bcfed5fbb6abbc67a9
andresjjn/holbertonschool-higher_level_programming
/0x06-python-classes/6-square.py
3,756
4.28125
4
#!/usr/bin/python3 """Empy class square that define a square""" class Square: """Empy class""" def __init__(self, size=0, position=(0, 0)): """Declaration private instance attribute size Args: size (int): size of square. position (Tuple): Tupla of position Raise...
dc00c1e6a88479ef51939af915a10c4b7dbebee4
andresjjn/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
577
4
4
#!/usr/bin/python3 """ Module add This document have one module that add two numbers Example: >>> add_integer(8, 1) 9 """ def add_integer(a, b=98): """Add module Args: Integers or float a and b Reises: TypeError: If a or b aren´t not int or float Return: Integer result ...
f30ac55e2db6264456d258fb4248b516546cb98f
andresjjn/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
6,466
4.125
4
#!/usr/bin/python3 """This file contain a class named Rectangle inherits from Base""" from models.base import Base class Rectangle(Base): """Class Rectangle inherits from Base""" def __init__(self, width, height, x=0, y=0, id=None): """Class constructor Args: width (int): Width of...
5bd8a885dc78f1d4cd3f50bcaa51b4d470e970d2
andresjjn/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/12-roman_to_int.py
560
3.53125
4
#!/usr/bin/python3 def roman_to_int(roman_string): if not roman_string or type(roman_string) != str: return 0 M = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} add = 0 count = 0 while count < len(roman_string): if count + 1 != len(roman_string) and M[roman_string[...
e23a809a3a920c566aa857d70f684fc787381bbb
GbemiAyejuni/BubbleSort
/bubble sort.py
828
4.28125
4
sort_list = [] # empty list to store numbers to be sorted list_size = int(input("Enter the size of list: ")) # variable to store size of list indicated by the user for i in range(0, list_size): number = int(input("Enter digit: ")) sort_list.append(number) # adds each number the user gives to sort_list ...
5bccfef12a41201e2aa93264f4831392274fff75
club-de-algoritmia-cuvalles/Concursos
/11vaFeriaAcademicayCultural/Intermedio/Problema2/problema2.py
1,609
3.65625
4
"""Problema 2 Validate an input password Propuesta de solucion autor: Luis Arturo De La Garza Navel Python 2.7""" """el uso del modulo sys para entrada/salida de datos es altamente recomendado en programacion competitiva (ojo: no todas las competencias permiten su uso), pero puede usar los metodos propios defin...
1e649947198885e95119e402565537b056ec2149
club-de-algoritmia-cuvalles/Concursos
/CUValles2019B/Basico/Problema3/Problema3.py
1,893
3.984375
4
""" Problema 3: Separar frase Autor de la solucion: Luis Arturo DLG. Python 3.x Descripcion del problema:Recibiremos una frase, la cual puede contener cualquier tipo de caracter, y debemos de separar los numeros de los demas caracteres, y los numeros deben ser sumados Entrada: Ae78YuPo5?8&40 Salida: Cadena...
03b2544e8a5cf895ef31c936184b2cf6c091d672
club-de-algoritmia-cuvalles/Concursos
/11vaFeriaAcademicayCultural/Basico/Problema4/problema4.py
993
4.03125
4
"""Problema 4 Palabra Piramide Girada Propuesta de solucion autor: Luis Arturo De La Garza Navel Python 2.7""" """el uso del modulo sys para entrada/salida de datos es altamente recomendado en programacion competitiva (ojo: no todas las competencias permiten su uso), pero puede usar los metodos propios definido...
23bfee2063d48828feeab2958d8a46b427b62618
club-de-algoritmia-cuvalles/Concursos
/CUValles2019B/Basico/Problema5/Problema5.py
1,592
3.921875
4
""" Problema 5: My office Autor de la solucion: Luis Arturo DLG. Python 3.x Descripcion del problema:Recibiremos una frase el cual sera el titulo a centrar, y un numero entero el cual nos indicara las unidades a centar el titulo Entrada: My Office 15 Salida: ###################################### ...
85e836d64aa430b587e6d73afa8ded86764bdc0a
club-de-algoritmia-cuvalles/Concursos
/11vaFeriaAcademicayCultural/Intermedio/Problema5/problema5.py
1,202
3.9375
4
"""Problema 5 Baker Palindromes Propuesta de solucion autor: Luis Arturo De La Garza Navel Python 2.7""" from collections import deque from sys import stdin def es_palindromo(palabra): """Funcion para verificar si una palabra es palindromo""" palabra = list(palabra) return palabra == palabra[::-1...
bba7a6b1f479e572f02d49c019ad5e3acffe17ad
mbollon01/caesar
/caesar.py
1,968
4.15625
4
def main(): print ("Welcome to Caesar shift\n") print ("=======================\n") print ("1.Encrypt\n2.Decrypt") option = int(input("please input an option: ")) message = input('Enter Message: ') shift = int(input("input the shift: ")) if option ==1: encrypt(message, shift) elif option ==2: decrypt(m...
9afbf86cbb2a75107e9647032d942eb884505488
woniukaibuick/DA-ML
/src/com/valar/basic/others.py
1,579
3.953125
4
# print("hi python"); # var1 = 1; # del var1; # print(abs(-100)); # # lis = ["one","two"]; # lis.clear(); # print(lis) # a, b = 0, 1 # while b < 10: # print(b) # a, b = b, a+b # import sys # # def fibonacci(n): # 生成器函数 - 斐波那契 # a, b, counter = 0, 1, 0 # while True: # if (counter > n): # ...
bbf6a602c149c78e232a9cc2e26b73305171e291
wnukmat/271B_Project
/helper_library.py
945
3.5625
4
import cv2 def sliding_window(image, window, classifier) ''' takes image, slides over by param window size, extracts features and classifies using param classifier param input: image: type np.array window: type int classifier: trained classifier object param output: pos_example: l...
eef4c1a2d81c858197e26f85ff15baa746db6f9d
syntaxmonkey/Thesis
/PycharmProjects/geodesic/driverTurtle.py
1,214
3.5625
4
import numpy as np import matplotlib matplotlib.use('tkagg') # Fix for turtle and Tk: https://github.com/matplotlib/matplotlib/issues/10239/ import matplotlib.pyplot as plt # For displaying array as image from PIL import Image, ImageDraw #Program to draw concentric circles in Python Turtle import turtle # Draw with Tu...
54b2ff41c3c8945b87b4369d91bee8be240de517
syntaxmonkey/Thesis
/PycharmProjects/geodesic/circularLines.py
2,968
3.5
4
import math import matplotlib.pyplot as plt # For displaying array as image import numpy as np def generateCircularPoints(angle, dimension, spacing, segments, axis, radius): angle = angle % 360 # Generate all the points around the boundary. # Find x values along the y = 0 axis. print ('starting angle: ', angle) ...
1cf0efd3a0e71b72eba3a065a3a01f72cbcabf79
RoutinoDesigns/LPTHW
/ex11.py
214
3.953125
4
age = input("How old are you?") print("How tall are you",end = ' ') height = input() print("how much do you weigh",end = '') weight = input() print(f" so,you are {age} years old,{height} tall and {weight} heavy")
d9a69fbda9ed1346f9475dd255278948ae5038de
arifams/py_coursera_basic_
/for_test2.py
352
4.40625
4
print("before, this is the total number") numbers = 3,41,15,73,9,12,7,81,2,16 for number in numbers: print(number) print("now python try to find the largest number") largest_so_far = 0 for number in numbers: if number > largest_so_far: largest_so_far = number print(largest_so_far, number) print("Now the curre...
2895e054d5c2b4610cb1bd40474389f5e6556f33
arifams/py_coursera_basic_
/string_location1.py
476
3.71875
4
fruit = 'mango' letter = fruit[1] print(letter) password = '1234567890' number = password[7] print(number) x = int(number) - 1 print(x) find_g = fruit[x - 4] print(find_g) print('print loop mango') for loop in fruit: print(loop) another_fruit = 'banana' print('find how many a in banana') count = 0 for huruf_a...
d12fe1bbeabb15dac38d14db1c9fdee60ab90b8f
arifams/py_coursera_basic_
/read_file1.py
406
3.640625
4
file_text = open('hatta.txt', 'r') counter = 0 for text in file_text : counter = counter + 1 text = text.replace('\n', '') print(text) print('Line text:', counter) print('----- another try with function rstrip ----') file_text = open('hatta.txt', 'r') counter = 0 for text in file_text : counter = coun...
1ce98af69c4079d51dd917e6078aeb3c87b99ce9
Kim-Seul-Gi/python_practice
/day2/99.py
499
3.578125
4
#99단 출력 # n*m=k 라는 식으로 출력될 수 있도록 for문을 만들어보자 # a=range(2,10) # b=range(2,10) # for i in a: # for j in b: # c=i*j # print(i,"x",j,"=",c,"입니다.") # with open("gugudan.txt","w") as file: # for i in range(2,10): # for j in range(2,10): # line = f"{...
d7be1ccf4141c4ab91c5c70e09b78c0eaab72ea8
gm-p/practice_demo
/机器学习百科/pycode/多态.py
1,249
4
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 22 16:31:11 2019 @author: asus """ ''' 方法重写:子类继承弗雷,会继承父类所有的方法,当父类的方法无法满足要求时,可在子类中定义一个同名的方法覆盖父类的方法,这叫做方法重写 当子类的实例调用该方法时,优先调用子类自身的方法,因为它被重写了 ''' class People: def speak(self): print("people is speaking") class Student(People): def speak(self): # ...
9e06005ba42b309d851b0c070c134bb5a632611f
gm-p/practice_demo
/python练习/tk32.py
327
3.65625
4
from tkinter import * root = Tk() w = Canvas(root, width=200, height=100) w.pack() w.create_line(0,0,200,100,fill="green", width=3) w.create_line(200,0,0,100,fill="green", width=3) w.create_rectangle(40,20,160,80,fill="green") w.create_rectangle(65,35,135,65,fill="yellow") w.create_text(100, 50, text="FishC") main...
347decf9c6ed110da06cd3677c22a160172ff139
gm-p/practice_demo
/机器学习百科/杂项code/kaggle kernel常用方法和语句总结.py
7,937
3.703125
4
# https://blog.csdn.net/maomaona/article/details/90143587 import pandas as pd # 读取数据 # 读数据,看行数、列数、前几行 df = pd.read_csv('../input/application_train.csv') print('Training data shapa:',df.shape) df.head() # EDA # 查看目标变量分布 # 目标变量为分类变量 df['TARGET'].value_count() df['TARGET'].plot.hist() 查看缺失值 目标dataframe缺失数据的分布 输入:目标dataf...
36717713967683a0d1eaad1959a05c0a8eb7e642
TRACYMUSIKER/coffeeRun
/PYGAME/whackadot.py
3,066
3.515625
4
import pygame import math import time from random import randint #Class creation with only 2 parameters - x + y, and 1 method - drawing) class Dot(object): def __init__(self, x_coor, y_coor): self.x_coor = x_coor self.y_coor = y_coor self.appear = False def draw_self(self, screen): ...
66e8640f0e71954aef9a20ca509cb3fb5172872d
gaodelade/guess-number
/guessnumbergame.py
705
4.03125
4
#This is our first number guessing game import random #defining variables n = random.randint(1,99) guess = int(input("Enter an integer from 1 to 99 :")) i = 0 while n!=guess: #print("Wrong number guessed .\n Please try again") if guess < n: print("Your guessed number is lower than the ori...
7b9e12083faf0278926f41cc4c60562e24332697
lasupernova/book_inventory
/kg_to_PoundsOrOunces.py
1,806
4.125
4
from tkinter import * #create window-object window = Tk() #create and add 1st-row widgets #create label Label(window, text="Kg").grid(row=0, column=0, columnspan=2) #create function to pass to button as command def kg_calculator(): # get kg value from e1 kg = e1_value.get() # convert kg into desired un...
92f181d880bb54b77ee185689c6a849a1c369985
Ridhima12345/codewayy_python_series
/Python_Task1/String_Prog.py
656
3.84375
4
#function for calculating total marks and percentage def cal(maths,english,social,hindi,science): total_Marks = english+social+maths+hindi+science percentage = float((total_Marks/500)*100) #percentage in float print("The total marks are: ",total_Marks) print("The percentage is: ",percentage)...
ff532aec119457aeb322cc22ac3ac7f6f8b58a5e
NaderDroid/codingBat
/warmup-02/front_times.py
176
3.5625
4
def front_times(str, n): return str[0:3]*n print(front_times('Chocolate', 2)) print(front_times('Chocolate', 3)) print(front_times('Abc', 3)) print(front_times("na", 3))
2daaa43678e697ef5bf7b9ea511892d31aee87b6
stynon/Make1.2.3
/list.py
771
3.625
4
#!/usr/bin/env python """ Maak een functie die data (bv. van een sensor) in een lijst stopt. Er worden steeds 20 items in de lijst gestoken, het gemiddelde print je af. Zorg dat je de loop kan onderbreken met een door jou gekozen symbool/letter/nummer/... """ # Import import random __author__ = "Stijn Janssen" __emai...
84f9b055285e1dc32eba6b0b8f64174e5c5463e2
vladhondru25/scikit
/linear_regression.py
631
3.59375
4
from sklearn import datasets, linear_model from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # Get Boston dataset boston = datasets.load_boston() X = boston.data y = boston.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Visualise first feature ...
038222bfd3d7ce7b6ff6edb72ee973f56a94751e
congma/takeevery
/takeevery.py
4,006
4.375
4
"""every(iterable, n) yields lists of size at most n from iterable, until the iterable is exhausted. Example: taking every N elements from nothing -- nothing is taken. >>> import six >>> for t in every([], 11): ... print(t) Example: taking every N elements from an unending generator -- can always take more. >>> d...
15d0ab0823bf520629e1777e7086982dd33c2618
erikaejlli/GWC---SIP---2019
/Week 3/twitter.py
5,058
4.09375
4
# ''' # In this program, we print out all the text data from our twitter JSON file. # Please explain the comments to students as you code. # ''' # We start by importing the JSON library to use for this project. # Twitter data is stored in this format - this is the same format # students learned for their Survey Projec...
ed71f10ee02ba85aa14b378d2a36667b8da9eb8b
Kgrochowsk/Python-projects
/Coffe machine/coffee_machine.py
3,225
4.15625
4
class CoffeeMachine: def __init__(self, water, milk, coffee, cups, money): self.water = water self.milk = milk self.coffee = coffee self.cups = cups self.money = money def state_of_machine(self): print("The coffee machine has:") print(str(self...
57a4ff9ae3edd0739ac3f256e36ca57c6a24f9e5
rubik/mando
/examples/docs/types.py
342
3.78125
4
from mando import command, main @command def pow(a, b, mod=None): '''Mimic Python's pow() function. :param a <float>: The base. :param b <float>: The exponent. :param -m, --mod <int>: Modulus.''' if mod is not None: print((a ** b) % mod) else: print(a ** b) if __name__ == '...
b4efe7e763a1deb5a5e299f3cf68730aa475b4ec
anderson-felix/PTG-fazentech
/database.py
433
3.53125
4
import sqlite3 conn = sqlite3.connect("./fazenda.db") # confira se o seu diretório está correto cursor = conn.cursor() createTable = """ CREATE TABLE Vaca ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ordenhada TEXT CHECK (ordenhada IN ('S','N')) NOT NULL DEFAULT 'M', ult_ordenha TEXT default NULL, ...
6e8d17c385229344a5ba7cfddfdc9679de7e09eb
jelaiadriell16/PythonProjects
/pset2-1.py
736
4.1875
4
print("Paying the Minimum\n") balance = int(raw_input("Balance: ")) annualInterestRate = float(raw_input("Annual Interest Rate: ")) monthlyPaymentRate = float(raw_input("Monthly Payment Rate: ")) monIntRate = annualInterestRate/12.0 month = 1 totalPaid = 0 while month <= 12: minPayment = monthlyPaymentRate ...
7a7f1db7573dad288d803c608f2b6aa94967b8aa
AnnanShu/LeetCode
/401-500_py/490-maze.py
866
3.5625
4
from typing import List class Solution: def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: if not maze: return False R, C = len(maze), len(maze[0]) visited = [[False] * C for _ in range(R)] directions = [(1, 0), (-1, 0), (0, -1), (0, 1)...
615c5a575f66914d01d11da34d8d4f80bd19e778
AnnanShu/LeetCode
/800+_py/1300-findBestValue.py
533
3.5
4
from typing import List class Solution: def findBestValue(self, arr: List[int], target: int) -> int: arr = sorted(arr) n = len(arr) for i, num in enumerate(arr): if target / (n - i) <= num: return target // (n - i) if abs(target - (n-i)*(target // (n - i) +...
3a6b0641ede852d73b215c9879cf3108863a244e
AnnanShu/LeetCode
/UniFindSet/uniFindSet.py
806
3.515625
4
class UnionFindSet: def __init__(self, n:int): self.rank_ = [0] * (n + 1) self.parents_ = [0] * (n + 1) for i in range(n + 1): self.parents_[i] = i def Find(self, u): if u != self.parents_[u]: self.parents_[u] = self.Find(self.parents_[u]) ...
023e0b34a70927bcd9fb29668e742325498f03f7
AnnanShu/LeetCode
/181-230_py/215-KthLargestInArray.py
231
3.515625
4
import heapq class Solution: def findKthLargest(self, nums: list, k: int) -> int: inner_list = nums[k] inner_list = sorted(inner_list)[::-1] if k == lem(nums) heapq.nlargest(2, [2,3,4,5,8,3])
77f692de70a2a886fe6d3deccb30981b486fa7fe
AnnanShu/LeetCode
/Special_py/16_11_Dividing_boardLCCI.py
842
4.09375
4
""" You are building a diving board by placing a bunch of planks of wood end-to-end. There are two types of planks, one of length shorter and one of length longer. You must use exactly K planks of wood. Write a method to generate all possible lengths for the diving board. return all lengths in non-decreasing ...