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
ee43a116e8951757f34048101d50a6e43c4eea49
wentao75/pytutorial
/05.data/sets.py
653
4.15625
4
# 堆(Sets)是一个有不重复项组成的无序集合 # 这个数据结构的主要作用用于验证是否包含有指定的成员和消除重复条目 # 堆对象还支持如:并,交,差,对称差等操作 # 可以使用大括号或set()方法来产生堆对象,不要使用{}来产生空的堆对象 # {}会产生一个空的字典而不是堆对象 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) 'orange' in basket 'crabgrass' in basket a = set('abracadabra') b = set('alacazam') a b a - b b ...
25ca539e5e7e3b489d10ec35eb0e3e5eb49a78d0
rcm2000/learn_algorithm
/code07-02.py
1,776
3.96875
4
##함수 def isQueueFull(): global SIZE, front, rear if (rear != SIZE - 1) and (front == -1): return False else: for i in range(front+1,SIZE): queue[i-1] = queue[i] queue[i] = None front -= 1 rear -= 1 return False def enQueue(data): global SIZ...
911ff63d9a725b1c278ce6e4499f1963d01e1e16
rcm2000/learn_algorithm
/code13-03.py
589
3.734375
4
## 함수 def binarySearch(ary,fData): pos = -1 start = 0 end = len(ary)-1 while (start <= end) : mid = ((start + end) //2) if ary[mid] == fData : return mid elif fData > ary[mid]: start = mid + 1 else: end = mid - 1 return pos ## ...
6cbfc9e2bd18f1181041287a56317200b1b789a8
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week7/Practice ActivityRecursionSolution5.py
925
4.46875
4
""" Example of a recursive function that inserts the character 'x' between all adjacent pairs of characters in a string """ def insert_x(my_string): """ Takes a string my_string and add the character 'x' between all pairs of adjacent characters in my_string Returns a string """ if le...
87f5557c82320e63816047943679b70effe5aecf
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week6/Inheritance2.py
437
4.25
4
""" Simple example of using inheritance. """ class Base: """ Simple base class. """ def __init__(self, num): self._number = num def __str__(self): """ Return human readable string. """ return str(self._number) class Sub(Base): ...
efaf6d26c8b60e755140beebcc1a7134c68dc6e5
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad10/text.py
431
3.625
4
from tkinter import * def iniciarVentana(): root = Tk() root.title("Text") root.iconbitmap('icono.ico') root.resizable(0, 0) text_area = Text(root) text_area.config(width=30, height=10, font=("Verdana", 45), padx=10, pady=10, selectbackground="yellow") text_area.pack(...
7b04a899e538e742f6957fe6078a22107b1c23bb
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad2/listas.py
440
3.796875
4
matriz = [ [1, 1, 1, 3], #0 [2, 2, 2, 7], #1 [3, 3, 3, 9], #2 [4, 4, 4, 13] #3 ] #print(type(matriz)) #print(len(matriz)) #print(matriz) a = sum([8,3,4]) print(a) """matriz[1][-1] = sum(matriz[1][:3]) matriz[3][-1] = sum(matriz[3][:-1])""" print (matriz[0][0]) matriz[0][0] = sum(matriz[0][-3:]) m...
8cbc6a384f66035c62485e1f80b9fb33143f3b5d
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad4/ejercicios-unidad4.py
5,068
4.21875
4
import math def obtener_lista_numeros(cadena): """Valida la entrada de usuario y devuelve una lista de numeros ingresados por teclado. Controla espacios en blanco Args: cadena (str): Entrada de usuario que representa los numeros. Returns: list: Lista de numeros que fueron extraidos ...
6df83a3cfec4db1e245f94b8588886399c145f14
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad9/biblioteca.py
1,464
3.921875
4
class Biblioteca(): lectores = [] # Atributo de clase def __init__(self, direccion, recepcion, nombre): print("Init") self.direccion = direccion self.recepcion = recepcion self.nombre = nombre def __str__(self): print("str") return (f" Direccion...
8f43e84679abf5fcd2a82816b011d9cca2fcde5c
mikefraanje/Programming-Blok1
/les3/pe3_3.py
253
3.953125
4
leeftijd = int(input('geef je leeftijd: ')) paspoort = input('Ben je nederlander? ') if leeftijd > 17 and paspoort== 'ja': print ('gefeliciteerd, je mag stemmen!') else: print('je mag niet stemmen, want je moet nederlander en 18 jaar oud zijn')
0babb63d5faccfb7e0abfa713d6538dc0b629834
mikefraanje/Programming-Blok1
/les6/pe6_2.py
510
3.578125
4
# Schrijf een nieuw programma waarin een list met minimaal 10 strings wordt ingelezen. Het programma # plaatst alle vier-letter strings uit de ingelezen list in een nieuwe list en drukt deze af. Inlezen van een # lijst kan met eval(input("Geef lijst met minimaal 10 strings: ")). lijst = ["boter", "kaas", "bier", "pizz...
37260be3734e89bfff5437f1104e809b392bc14d
mikefraanje/Programming-Blok1
/les3/pe3_2.py
147
3.6875
4
leeftijd = input('Geef je leeftijd') paspoort = input('Nederlands paspoort') if leeftijd > 18 and paspoort == 'ja' : print 'Je mag stemmen!'
bbb886305283fb3075719376a9f315fd8f8ada66
OlegPonomaryov/mymllib
/mymllib/_test_data/classification.py
800
3.625
4
"""Test data for classification models.""" # Classes: # 0 (A) - both x1 and x2 are high # 1 (B) - both x1 and x2 are low # 2 (C) - x1 is high, x2 is low X = [[24, 32], [3, 0], [19, 1], [17, 28], [0, 5], [27, 5], [20, 30], [2, 3], [22, 3]] y = [0, 1, 2, 0, 1, 2, 0, 1, ...
996ec39d2549387fc942be88971b907ea28e1b2b
OlegPonomaryov/mymllib
/mymllib/neural_networks/output_activations.py
2,482
3.6875
4
"""Different activation functions for neural networks.""" from abc import ABC, abstractmethod from mymllib.math.functions import sigmoid, log_loss, softmax, softmax_loss class BaseOutputActivation(ABC): """Base class for activation functions for output layer.""" @staticmethod @abstractmethod def acti...
1089357cd0a34c9a7dd53f59c75ac9d6e154f206
busquedas/ejercicios-tecnicas
/ejercicio_7.py
996
4.09375
4
#Crear una calculadora. El usuario deberá ingresar un valor, luego una operación #(1 para sumar, 2 para restar, 3 para dividir, 4 para multiplicar) #y un segundo valor para completar el calculo. El sistema deberá mostrar el resultado. valor = input ("ingrese un valor: " + str ()) valor = float (valor) opcion = input (...
8560b816547fb7fa0dd5ef0f1f12b527ab543a67
busquedas/ejercicios-tecnicas
/ejercicio_13.py
472
3.859375
4
#Almacenar 5 números por teclado y mostrar el promedio de ellos. #tengo que empezar print ("ingrese 5 números por teclado: ") almacenar = [] numero1 = input ("1ero: " + str ("")) numero2 = input ("2do: " + str ("")) numero3 = input ("3ro: " + str ("")) numero4 = input ("4to: " + str ("")) numero5 = input ("5to: " + str...
a4ae13c4e1865d32d4fb7729db2f53060ff2c323
bblodget/RaspberryPi
/minecraft/digit_wall.py
7,417
4.09375
4
""" File: digit_wall.py This module defines a class DigitWall which creates a wall that can display a 7-segment digit in a Minecraft world. It provides a method to update the digit that is displayed. Author: Brandon Blodget URL: https://github.com/bblodget/RaspberryPi Copyright (c) 2013, Brandon Blodget All righ...
9a0d08c170b5495ec44ab846a7593a3671b74f9f
kmgumienny/Python-Practice-Udemy
/String Challenge.py
646
4.03125
4
# Create a program that takes an IP address entered at the keyboard # and prints out the number of segments it contains, and the length of each segment. ipAddress = input("Please enter an IP address ") printText = '' numNumbers = 0 numSegment = 1 for i in range(0, len(ipAddress)): if ipAddress[i] in '0123456789'...
cbdff5a801c81d3e94cd908387a5fdbddf4ba561
edenpan/dissertation
/strategies/componentTradingRules/BollingerBandsStrategy.py
3,130
3.609375
4
# coding: utf-8 # autor:Eden # date:2018-08-03 # bb.py : Bollinger Bands is a volatility indicator that considers the fluctuations of stock price. # middle band: BBs calculates an n day moving average of past close price Avgt,n. # upper band: k times above the standard deviation of the middle band. # lower band:...
70b3346ddb78d5d8e5f136bae52c8ebd0d25238c
vefakucukler/Imdb-Analysis
/ImdbAnalizi/pandas_imdb_analizi.py
1,578
3.71875
4
import pandas as pd df = pd.read_csv('imdb.csv') result = df result = df.columns #Dataset Hakkında Bilgi verir result = df.info #1- İlk 5 kaydı gösterir result = df.head() #2- İlk 10 kaydı gösterir result = df.head(10) #3- Son 5 kaydı gösterir result = df.tail() #4- Son 10 kaydı gösterir result = df.tail(10) ...
061cc8e04cdaba494f531e6f7efa6a5f9b882e8e
besenthil/Algorithms
/algoexpert/move_element_to_end.py
764
3.59375
4
# O(n) Time # O(1) Space def moveElementToEnd(array, toMove): #pythonic way current_index = 0 while current_index < len(array): if array[current_index] != toMove: array.insert(0, array.pop(current_index)) current_index += 1 return array # O(n) Time # O(1) Space def moveElem...
2cb01f710d593d6e3be2cf77a8024817bb032ccb
besenthil/Algorithms
/algoexpert/sortedSquaredArray.py
100
3.5
4
# O(nlogn) Time # O(n) Space def sortedSquaredArray(array): return sorted(x ** 2 for x in array)
4fcf5d6c12648b420d72c50ccac1e39393347910
besenthil/Algorithms
/quicksort.py
839
3.734375
4
import random,datetime def partition(arr,low,high): pivot = arr[low] i = low j = high while i < j: while ((i <= high) and (arr[i] <= pivot)): i += 1 while arr[j] > pivot: j -= 1 if i < j: arr[i],arr[j] = arr[j],arr[i] else: ...
9cf4c0dd69fd5464b6de5877926e842f5d47fe13
besenthil/Algorithms
/symmetric_point.py
333
4.0625
4
def compute_symmetric_point(): coordinates = [] for _ in range(int(input())): coordinates.append(list(map(int,input().split()))) for coordinate in coordinates: print("{0} {1}".format(2*coordinate[2]-coordinate[0],2*coordinate[3]-coordinate[1])) if __name__ == "__main__": compute_symmet...
703e36dd7548ded429c5e24e5fab313f21b800ef
besenthil/Algorithms
/algoexpert/nodeDepths.py
346
3.90625
4
def nodeDepths(root, level=0): if root is None: return 0 else: return level + nodeDepths(root.right, level + 1) + nodeDepths(root.left, level + 1) # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None ...
e34f2b59fe4b713e979a1d35c4660e1c26fe6764
Harshitanetam/std_deviation
/std_deviation.py
1,084
3.9375
4
import math #list of elements to calculate mean import csv with open('data.csv', newline='') as f: reader = csv.reader(f) file_data = list(reader) data = file_data[0] #getting the mean # data = [20,69,56,90,40,99,86,100,70,69,80,65,57,82,90,70,79,39,90,80,86,53,97,95,88,47,100,56...
c3d263e251fd73a1bb7c4c511ecd26225679fe3c
Thuhaa/PythonClass
/16-Aug/list_slicing.py
377
3.921875
4
kenya_uni = ["TUK", "UON", "Egerton", "Moi", "JKUAT", "KU"] # print the values in the list between index 2 and 4 print(kenya_uni[2:5]) # Expected Output: ["Egerton", "Moi", "JKUAT"] # Reversing a list print(kenya_uni[::-1]) # Expected Output: ["KU", "JKUAT", "Moi", "Egerton", "UON", "TUK"] # printing speci...
9f045af90875eea13a4954d2a22a8089fd07724a
Thuhaa/PythonClass
/28-July/if_else_b.py
713
4.21875
4
marks = int(input("Enter the marks: ")) # Enter the marks # Between 0 and 30 == F # Between 31 and 40 == D # Between 41 and 50 == C # Between 51 and 60 == B # Above 61 == A # True and True == True # True and False == False # False and False == False # True or True == True # True or False == True # False an...
d88cc40adb2c1fcb288b6af4f01c590c12b6788f
Gaurav-Pande/openshift-python
/GenderClassifier.py
4,356
3.5
4
# Lucien Rae 2017 # A classifier that predicts whether a name is male or female # Uses a DecisionTree Classifier # Data from a list of 258000 names, 50/50 ratio between male and female # Features are the digits that correspond with the letters in the name # Labels are the gender import csv from sklearn import tree from...
ac9c8b4b870b5a72e4cc38267bc0e8238e699222
artikri/stp
/NextDate.py
1,300
3.734375
4
def isLeapYear(year): if year % 4 == 0: if year % 100==0: if year % 400==0: return 1 else: return 1 else: return 0 day = int(input("Enter day:")) mon = int(input("Enter mon:")) year = int(input("Enter Year:")) thirty = [4, 6, 9, 11] thirtyOne = ...
ddccc907b7cc2cdea22874e8f41c9ec04eacc220
ritwiktiwari/algorithm-visualizer
/app.py
2,924
3.640625
4
from tkinter import * from tkinter import ttk import random from bubble_sort import bubble_sort # Main Window root = Tk() root.title("Sorting Algorithm Visualizer") root.maxsize(900,600) root.config(bg='black') # Variables selected_algorithm = StringVar() data = [] def draw_data(data, color_array)...
4e6708d3b8109a6fb5082eb4efb5d0590309f71a
yestodorrow/dataAnalysis
/firstCourse/hello.py
1,252
4.125
4
print("Hello Python") # 交互界面窗口 输入输出交互式 # 编写和调试程序 # 语法词汇高亮显示 # 创建、编辑程序文件 print("hello world") a=3 # 定时器 import time time.sleep(3) a=4 print(a) print(a) # 标量对象 # init 整数 # float 实数 16.0 # bool 布尔 True False # NoneType 空类型 x="this is liu Gang" y="he is a handsome boy" print(x+","+y) #变量 #赋值语句 x,y="liugang","very ha...
e39be11bf340de1ffc975a2568c41538ad434495
hafenschiffer/UdemyPythonForPentesters
/nmapscanner.py
531
3.625
4
#!/usr/bin/env python3 #pip3 install python-nmap import sys import nmap def scanport(scanner, target, port): print('\nScanning %s for port %s' %(target, port)) result = scanner.scan(target, port) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: %s <ip>" % sys.argv[0]) sys....
198c27c7d2e676d844c3ff0958f7174b5ad95d89
marczakkordian/python_code_me_training
/02_flow_homework/02_while/02.py
485
3.640625
4
# Napisz prostą grę, w której użytkownik musi zgadnąć liczbę od 0 - 20 ukrytą w programie (np. secret_num = 5). # Pytaj użytkownika o podanie liczby tak długo, aż nie zgadnie. # defining secret number secret_num = 12 # defining user number variable user_num = int(input('Enter your number (1-20): ')) # loop with guess...
4190a27fb1a36236b8279533eb51a6152fc84ad7
marczakkordian/python_code_me_training
/02_flow_homework/02_summary/05.py
1,293
3.96875
4
# Stwórz grę ciepło zimno. # Komputer losuje liczbę z zakresu od 1 do 100. # Użytkownik podaje swój traf. # Komputer odpowiada ciepło zimno, ale nie więcej niż 6 razy. # Jeśli użytkownik zgadnie wygrywa gracz. # Jeśli po 6 próbach użytkownik nie zgadnie - wygrywa komputer. import random ran_num = random.randrange(1, 1...
6528bce9faea44b6dc6326a8fdae56e584fb31ab
marczakkordian/python_code_me_training
/01_types_homework/04.py
1,199
4.09375
4
# Utwórz skrypt, który zapyta użytkownika o tytuł książki, nazwisko autora, liczbę stron, a następnie: # Sprawdź czy tytuł i nazwisko składają się tylko z liter, natomiast liczba stron jest wartością liczbową. # Użytkownicy bywają leniwi. Nie zawsze zapisują tytuły i nazwisko z dużej litery – popraw ich # Połącz dane w...
137638cb6c3ee7cd32d6d183e2bc898e1a2c8bd1
marczakkordian/python_code_me_training
/04_functions_homework/10.py
1,605
4.125
4
# Stwórz grę wisielec “bez wisielca”. # Komputer losuje wyraz z dostępnej w programie listy wyrazów. # Wyświetla zamaskowany wyraz z widoczną liczbą znaków (np. ‘- - - - - - -‘) # Użytkownik podaje literę. # Sprawdź, czy litera istnieje w wyrazie. Jeśli tak, wyświetl mu komunikat: # “Trafione!” oraz napis ze znanymi li...
9132918faa63a4d2c62f1fb2a50b0c421797c217
marczakkordian/python_code_me_training
/01_types_homework/06.py
1,794
3.90625
4
# Przekopiuj zawartość import this do zmiennej. # >>> import this # Policz liczbę wystąpień słowa better. # Usuń z tekstu symbol gwiazdki # Zamień jedno wystąpienie explain na understand # Usuń spacje i połącz wszystkie słowa myślnikiem # Podziel tekst na osobne zdania za pomocą kropki s = "The Zen of Python, by Tim P...
03f803d4d6528c47286a810901e4481e5185fd3e
marczakkordian/python_code_me_training
/10_OOP_concepts/05.py
1,097
3.75
4
# Stwórz abstrakcyjną klasę Pojazdy. Utwórz potomne klasy pojazdy np. Samochód, Rower, Autobus, Ciężarówki. # Dodaj opisy zgodne z tym jak te pojazdy są klasyfikowane. # Jaki rodzaj dokumentu jest potrzebny, by kierować poszczególnym pojazdem. from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmetho...
66c416b409954077d2abed35fec39fe267cb176c
marczakkordian/python_code_me_training
/01_types/string.py
503
3.890625
4
# 1 result = str.isnumeric("1232a323") print(result) # 2 result2 = str.center("Python", 15, "*") print(result2) # 3 result3 = "Remove_this_string".strip("ing") print(result3) # 4 # 5 # 1.1 quote = 'Honesty is the first chapter in the book of wisdom.' print(len(quote)) print(quote[-7:-1]) middle = len(quote) //...
1610aa340e7429d1ba3116f31461f592b3a3cf78
marczakkordian/python_code_me_training
/05_files_homework/02.py
375
3.53125
4
import os filename = 'example.txt' def create_or_overwrite_file(file): with open(filename, 'w+') as fopen: usr_range = int(input('Type the number of lines: ')) for i in range(usr_range): fopen.write("This is line %d\r\n" % (i + 1)) return os.stat(filename).st_size print('Size of...
3ae6677865a6e401ad34555877857f480b6454cb
marczakkordian/python_code_me_training
/02_flow_homework/02_summary/02.py
602
3.9375
4
# Pobierz od użytkownika dowolny tekst i wyświetl tylko te znaki, które są na pozycjach parzystych. # Wykonaj na dwa sposoby - za pomocą pętli oraz przez sting slicing ( ‘abrakadabra’ -> ‘baaar’). import re usr_input = input('Type your string: ') cleaned_input = re.sub('[^A-Za-z]', '', usr_input.strip()) print('Strin...
70507218fe55d8d425f4e88b82ab10ca08852538
marczakkordian/python_code_me_training
/03_collections_homework/03_dictionary/09.py
799
3.953125
4
# 5 użytkowników poproś o podanie 4 przedmiotów szkolnych, sprawdź czy przedmioty powtarzają się na listach. # Wyświetl najpopularniejszy przedmiot. (Uwzględnij fakt, że użytkownicy mogą zapisać przedmioty małymi, # drukowanymi lub zaczynając od dużej litery) import re import sys usr_num = 1 item_table = [] res_table ...
4ebabef297dd4146c39908d9bcad7b5b2dddea81
tanay46/Code-eval
/src/SumDigits.py
289
3.75
4
''' Created on Jul 12, 2011 Given a positive integer, find the sum of its constituent digits. @author: tanay ''' from sys import argv f = open(argv[1]) text = f.readlines() for line in text: n = int(line) total = 0 while n>0: total+=n%10 n=n/10 print total
48c4f525c65c75bf3108786b0cc450a640c8090d
tanay46/Code-eval
/src/reverseSentence.py
367
3.625
4
''' Created on Jul 12, 2011 @author: tanay ''' from sys import argv f = open(argv[1]) text = f.readlines() for line in text: line= line.strip() if line != '': sentence = '' words = line.split(' ') words.reverse() for word in words: sentence+=' '+ word senten...
6795c4e6e07de121d7dce93da430830b71f0cb3e
akoschnitzki/Module-4
/branching-Lab 4.py
884
4.375
4
# A time traveler has suddenly appeared in your classroom! # Create a variable representing the traveler's # year of origin (e.g., year = 2000) # and greet our strange visitor with a different message # if he is from the distant past (before 1900), # the present era (1900-2020) or from the far future (beyond 2020). y...
d8fae23b0d84264e3e62eb9b4051f60fe598ddf2
Ginju2019/Data_Science_Casestudy_Project2_S8_15_18
/piggy_bank.py
3,760
4.28125
4
import math class PiggyBank: #Pigg Bank def __init__(self): # initialize Piggy Bank current balance to zero self.balance_amt = 0 def addMoney(self, deposit_amount): """ Add the user deposited amount with current balance Parameters: ...
f0d8bcdd6544d7ac2f672244e1b6dec60486ebbe
andredoumad/DataStructuresAndAlgorithms
/MaxHeap.py
3,510
3.5625
4
# Andre Doumad import unittest, random # MaxHeap class MaxHeap(object): # heap def __init__(self): self.heap = [] # get parent index def getParent(self, i): return int((i-1)/2) # get left index def getLeft(self, i): return 2*i+1 # get right index def getRight(se...
196b3dd4caed879919bab15e240794b92b5e1a3d
harrypotter0/Python-web-development
/assignments/akash.py
758
3.609375
4
# To run this, you can install BeautifulSoup # https://pypi.python.org/pypi/beautifulsoup4 # Or download the file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate e...
7fdd1016be8cc57629a8b1a2ce577d608fd8702b
wilfredgithuka/learn-python-the-hard-way
/ex13.py
412
3.609375
4
#Wilfred Githuka #Githuka.com #31 December 2016 #Exercise 13 from sys import argv #script, first, second, third = argv #fname, idno, age, weight = argv #name = raw_input ("Name") #idno = raw_input ("ID-No?") #age = raw_input ("age?") #weight = raw_input ("weight?") name, idno, age, weight = argv print "Your name i...
5a954acd1407b5c802cc4064cde5883515f972d3
atupal/codeforces
/contests/286_DIV2/ts.py
361
3.640625
4
# -*- coding: utf-8 -*- import sys reload(sys) #sys.setdefaultencoding("utf-8") s = input().strip() # columm是w位的字符串 for i in range(len(s)+1): for j in range(26): l = [ _ for _ in s ] l.insert(i, chr( ord('a') + j)) if ''.join( l[:len(l)/2] ) == ''.join( l[::-1][:len(l)/2] ): print (''.join(l))...
fd4a6cca1323eb6439f3d3aa8548bb206f521d8d
jreis22/card_games
/src/core/cards/card.py
914
3.609375
4
from card_game_logic.cards.card_enums import Suit, Rank class PlayingCard(object): def __init__(self, suit: Suit, rank: Rank): self.suit = suit self.rank = rank def same_suit(self, other_card): if isinstance(other_card, PlayingCard): return other_card.suit == self.s...
951e9e2022aa94ef5708f128238ed9b7835aee52
Tanya-Kr/python_simle_tasks
/task10/test.py
1,822
3.703125
4
import unittest from unittest import TestCase, main, TestSuite from package.task10 import calculation class AddTest(TestCase): def test_all_args_more_zero(self): num1 = 3 num2 = 5 expected = 8 actual = calculation.add(num1, num2) self.assertEqual(expected, actual) d...
53303f7123bbd2c1b2f8c07d9002bae85f3cb81a
TrevAnd1/Sudoku-Puzzle-Solver
/Sudoku/Sudoku Puzzle Solver.py
1,725
4.15625
4
import pygame import random from pygame.locals import ( K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_RIGHT, K_LEFT, K_UP, K_DOWN, K_KP_ENTER, K_ESCAPE, KEYDOWN, QUIT, ) WHITE = (0,0,0) SCREEN_WIDTH = 1000 SCREEN_HEIGHT = ...
89f9b01bac89aff46326b94b18d0837935166b24
dyb-py/pk
/com/baizhi/杜亚博作业/asda.py
3,555
3.59375
4
# def f1(): # a=[1,2] # return a # a=[1,2] # a.append(f1()[1]+f1()[0]) # print(a) # def f1(s,t,m,n): # if n==1: # print('%s-->%s'%(s,t)) # else: # #n-1 a-->c # f1(s,m,t,n-1) # #a-->b # print('%s-->%s'%(s,t)) # #n-1 c-->b # f1(m,t,s,n-1) # f1('a','b...
55ab453d18e2b12b64378fd70fc3843ec169eb29
Deepak10995/node_react_ds_and_algo
/assignments/week03/day1-2.py
901
4.4375
4
''' Assignments 1)Write a Python program to sort (ascending and descending) a dictionary by value. [use sorted()] 2)Write a Python program to combine two dictionary adding values for common keys. d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} Sample output: Counter({'a': 400, 'b': 400, 'd': 400,...
24f3091c067759e7cde9222bfb761a777da668df
Deepak10995/node_react_ds_and_algo
/coding-challenges/week06/day-1.py
2,263
4.28125
4
''' CC: 1)Implement Queue Using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.last = None def enqueue(self, data): if self.last is None: self.he...
9281945408c7377a7849bcc0bfffeb9e912df0bd
Deepak10995/node_react_ds_and_algo
/assignments/week03/day3-4.py
836
3.625
4
''' Assignment: c) https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem d) https://www.hackerrank.com/challenges/list-comprehensions/problem ''' # Ques (c) # find second maximum number def runner_up(n,arr): if n == 0 : return false else: sorted_arr = sorted(arr,rev...
94012a1a44d78faf11cfd7230fd10d694cf846ef
Deepak10995/node_react_ds_and_algo
/assignments/week04/day1-2.py
883
3.796875
4
''' Assignments 1) https://www.hackerrank.com/challenges/countingsort4/problem ''' #counting sort #!/bin/python3 import math import os import random import re import sys # Complete the countSort function below. def countSort(arr,n): count = 0 count_sort = 0 sorted_arr = list() string = '' for ite...
dc20ed1e85f83f4b9e1af3bcb1eeb40f7848f43f
ccappelle/TreebotFrontiers
/3by3/object.py
913
3.53125
4
SPHERE=0 CUBE = 1 BIG=0 SMALL = 1 def CreateSphere(posVec,radius,sizeType): #Create sphere object in one of three positions obj = CreateObject(posVec,SPHERE,radius,sizeType) return obj def CreateCube(posVec,length): obj = CreateObject(posVec,CUBE, length) return obj def CreateObject(posVec, myType, length,size...
99ffabbbe487fb2b30fff35ef5b84ec832545227
ryanhofmann/ASTR5550
/hw3/hw3.py
3,517
3.53125
4
#!/usr/bin/env python3 import numpy as np from scipy import integrate from scipy import interpolate import matplotlib.pyplot as plt def f(x, p=2): """ Distribution function """ return x**(-p) def x(a, p=2): """ Inverse transform function """ return ((-p + 1)*a + 1)**(1/(-p + 1)) def P(k, lam=10)...
de19e44159a2ee8e49ed30eeaf405faa82f2e881
RiEnRiu/rer_learning_code
/interview/huffman_encode.py
3,139
3.984375
4
# a node is a dict with keys={'depth', 'weight', 'sub_trees'} # it is a leaf node if node['sub_trees'] is a weight value but not a list # 'depth' means the depth of this tree # 'weight' means the sum of all leaves in this tree # 'sub_trees' means all its children def _find_new_node_index(other_nodes,new_node): if...
a729758b2b951b8c38983b7dd5336c8f36f933da
DajkaCsaba/PythonBasic
/4.py
293
4.53125
5
#4. Write a Python program which accepts the radius of a circle from the user and compute the area. Go to the editor #Sample Output : #r = 1.1 #Area = 3.8013271108436504 from math import pi r = float(input("Input the radius of the circle: ")) print("r = "+str(r)) print("Area = "+str(pi*r**2))
198ac0807066f80ab712f7b4d33d0f9376ccfda2
cordunandreea/Probleme-Olimpiada-Clasa-9
/problema1.py
127
3.578125
4
x=int(input('nr total de pasari de la ferma:')) g=x//2 r=g//4 gs=x-g-r print(g,'gaini') print(r,'rate') print(gs,'gaste')
a5c57237975d714e0fad9f8dcbae46f429c978c5
NatalyaMotuzenko/BD_Lab
/BD_lab1/Routes.py
4,830
3.625
4
class Routes(object): # инициализация def __init__(self): self.routes = [] # добавление записи def add(self, route): self.routes.append(route) # вывод всех записей на экран def __str__(self): fullInfo = "" for ind, route in enumerate(self.routes): fu...
8b0f85f98616cbcb53b4071df7c04122e1f9edfb
gtvanderkin/CSC-227-Final-Project-Water
/waterReader.py
902
3.875
4
def calcharge(gal, br): # This function defines the cost calculation, and returns it # There are different rates for 'R'esidential or 'B'usiness rates if br == 'R': if gal <= 6000: return gal * 0.005 else: return (6000 * 0.005) + 0.007 * (gal - 6000) else: ...
f00fa5c5febcd13d2399ec516fff6cd786151af8
mustard-seed/graph_algo
/test_undirectedGraph.py
415
3.5625
4
import undirected_graph.graph as graph if __name__ == '__main__': num_vertices = 13 edges = [ [0, 5], [4, 3], [0, 1], [9, 12], [6, 4], [5, 4], [0, 2], [11, 12], [9, 10], [0, 6], [7, 8], [9, 11], [5, 3] ]...
812a7add94f621c196f8c68bdcb467d09f77d823
and117117/infa_2019_and117117
/lab3/event_bind.py
998
3.765625
4
from tkinter import * from random import randrange as rnd, choice import time root = Tk() root.geometry('800x600') canv = Canvas(root, bg='white') canv.pack(fill=BOTH, expand=1) colors = ['red', 'orange', 'yellow', 'green', 'blue'] score = 0 def new_ball(): """ Draw new ball with random coordinates (x, y), ran...
3de713f7ca2f61358268815be48dbe7a217db2ee
wojtbauer/Python_challenges
/Problem_2.py
865
4.125
4
#Question 2 # Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320 # Factorial = int(input("Wpisz liczbę: ")) # wynik = 1 #...
00a1a499a91fd85e4f67bb908624dee7ae148227
ejh243/MunroeJargonProfiler
/jargonprofiler/munroe.py
3,712
4.09375
4
''' Calculate a 'Munroe' score - what proportion of the text comes from the 1000 most common words in English. ''' from . import util import re def get_common(): ''' Opens the text file containing the list of 1000 most common words found at http://www.ef.co.uk/english-resources/english-vocabulary/top-100...
6fd67b08209d819f2d502bb65b0a8bbb0413f7c5
Kexin6/zergProject
/Demo1/package3/class2.py
961
3.921875
4
class Student(object): sum = 0 #和类相关的变量 # name = 'Someone' # age = 0 #Constructor def __init__(self, name, age): self.name = name self.age = age self.score = 0 # self.__class__.sum += 1 # print("当前学生总数: " + str(self.__class__.sum)) def doHomework(self)...
decf9fca45f23a75d59f49cbe0c3d9cc1a73ecb9
JNieswand/tetris
/main.py
7,819
3.609375
4
#main import numpy as np import copy import matplotlib.pyplot as plt global SIZE_X, SIZE_Y SIZE_X = 10 SIZE_Y = 20 def turn_coordinate(coordinate): turn_matrix = np.array([[0, 1],[-1, 0]]) new_coord = np.matmul(np.array([coordinate.x, coordinate.y]), turn_matrix) return Coordinate(new_coord[0], new_coord[1...
3343ed5fc69d1492b3c43d7efe74f5fd37e118c8
VeselinMetodiev/Chess-Game
/Main.py
2,430
3.515625
4
import pygame from os import sys from Constants import WIDTH, HEIGHT, SQUARE_SIZE, WHITE, BLACK from Game import Game from Algorithm import get_random_move FPS = 60 #window display WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Chess') #get the square clicked from mouse def get_row_col_fr...
5d3dfbaf1c4e88e47273834ae7118582e9070951
VeselinMetodiev/Chess-Game
/Rook.py
2,134
3.828125
4
from Constants import WHITE_ROOK, BLACK_ROOK, WHITE from Piece import Piece class Rook(Piece): def __init__(self, col, row, color): Piece.__init__(self, col, row, color) self.moved = False if color == WHITE: self.image = WHITE_ROOK else: self.image = BLACK_ROO...
5d663b2b02ab3f51d646e0e1d53f6d5b352b6b35
Marcnuth/LM-ML
/split-captcha-py/src/xnp.py
3,869
3.53125
4
import numpy as np from operator import itemgetter ''' Return the indexes of max connected array in given array ''' def max_connected_array(arr, diagonal=True): nonzero_arr = np.nonzero(arr) nonzero_all = set(map(lambda x, y: (x, y), nonzero_arr[0], nonzero_arr[1])) nonzero_walked = set() scores = lis...
521b998e165983de4be3342e7e5d354b03d096ac
eddgar10/codigosdebarrapersonalizado
/tecladogenera.py
2,827
3.84375
4
#!/usr/bin/python # -*- coding: utf-8 -*- #EDGAR ESPINOSA OCTUBRE 2021 #github.com/eddgar10/codigosdebarrapersonalizado #fuentes: #https://www.geeksforgeeks.org/how-to-generate-barcode-in-python/ #https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/ #https://barcode-labels.com/getting-started/barcodes/typ...
6952569826d810c9a9eae1dc5a3cca1365bd028a
ElenaVasylenko/PyReview
/basics/inheritance/Employee.py
1,758
3.890625
4
from abc import ABC, abstractmethod from datetime import date class Employee(ABC): def __init__(self, doc_id: str, name: str, birthday: str): self.__doc_id = doc_id self.name = name self.birthday = birthday print('employee created') @abstractmethod def get_duties(self): ...
c8f4db8845bf675f10b8cbb24773648475d06172
ElenaVasylenko/PyReview
/basics_test.py
726
3.75
4
# import re # import functools # l = [[1,2,3]] # # m = l.copy() # print(m) # l[0][1] = 'X' # print(l) # z = {1:'bill', 2:'age', 3:'22'} # v = list(z.values()) # print(v) # matrix = [[0, 2, 4, 5], [3, 1, 1, 8]] def main_diagonal(matrix :list): column_id = 0 diagonal = [] for row in matrix: ...
b1d9e5aa28778528f9305577f6e7a3a0604198c9
jackiehluo/projects
/numbers/change-return-program.py
951
3.796875
4
from math import floor def change(c, m): d = m - c dollars = int(floor(d)) coins = int((d - floor(d)) * 100) twenties = 0 tens = 0 fives = 0 ones = 0 quarters = 0 dimes = 0 nickels = 0 pennies = 0 if dollars > 0: twenties = dollars / 20 tens = (dollars % ...
bf126961d6fef79b8a12837acd4f6baf93f4fb6e
jackiehluo/projects
/numbers/tax-calculator.py
440
3.90625
4
def calculate(cost, rate): tax = round(cost * (rate / 100), 2) total = round(cost * (1 + rate / 100), 2) return tax, total cost = float(raw_input("Enter the cost: $")) rate = float(raw_input("Tax Percentage: ")) try: tax, total = calculate(cost, rate) print "Tax: $" + str(tax) print "Total: $" + str(total) excep...
8473a7a874e1bf2435049301d45064ecefe4f45d
jackiehluo/projects
/numbers/fibonacci-sequence.py
209
4.1875
4
from math import sqrt def fibonacci(n): return ((1 + sqrt(5)) ** n - (1 - sqrt(5)) ** n) / (2 ** n * sqrt(5)) n = int(raw_input("Enter a digit n for the nth Fibonacci number: ")) print int(fibonacci(n))
f9d9fd5fc21240bba11af8a5a30b2d0fb32b31cb
farnaztizro/computer-vision
/backpropagation/neuralnetwork.py
4,780
3.828125
4
import numpy as np class NeuralNetwork: # alpha value is applied during the weight update phase def __init__(self, layers, alpha=0.1): # initializes our list of weights for each layer self.W = [] # store layers and alpha self.layers = layers self.alpha = alpha ...
49e00035aa0f8b45dcca3c99f500d4300c066f81
MrHughesAvanti/GCSESummer
/selection.py
429
4.0625
4
import random number = random.randint(1, 10) guess = int(input("have a guess please: ")) for i in range(2): if guess > number: print("Sorry that's too high try a lower number") elif guess < number: print("Sorry that's too low try a higher number") else: print("Well d...
fc560701f87c73692b9710ce0a8593f28788a6c8
Drake-Firestorm/Think-Python
/code/reverse_pair.py
1,143
3.984375
4
# Method 1: using in_reverse() def is_reverse(word1, word2): if len(word1) != len(word2): return False i = 0 j = len(word2) - 1 while j >= 0: if word1[i] != word2[j]: return False i = i + 1 j = j - 1 return True def reverse_pair1(t): for i in rang...
411b26434e82a196319418b1fb65b2d4b7d4fa18
Drake-Firestorm/Think-Python
/code/anagram_db.py
754
3.859375
4
import anagram_sets_Allen_Downey import shelve def store_anagrams(d, filename): try: shelf = shelve.open(filename) for key, values in d.items(): if len(values) > 1: shelf[key] = values shelf.close() except: print("Error storing anagram") rai...
2266a4997eb486d1f00ce38df91d39f9b01e6502
Drake-Firestorm/Think-Python
/code/PokerHand.py
6,075
3.984375
4
"""This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ from __future__ import print_function, division from Card_Allen import Hand, Deck from Card_Allen import Card c...
cda9fd96188b3e9e86fe9345225796e5b1e00044
Drake-Firestorm/Think-Python
/code/reducible.py
2,490
4.09375
4
def make_word_dict(): """ Reads a word list and returns a word dictionary. :return: dictionary with words as keys """ fin = open("words.txt") d = dict() for line in fin: word = line.strip().lower() d[word] = d.get(word, 0) for letter in ["a", "i", ""]: d[letter] ...
b53251dd84c5f2f83b0b5af7fcba3a263a5defea
sowjanyadevdas7/python
/mathop.py
999
3.96875
4
a = int(input("enter a value:")) b = int(input("enter b value:")) def add(a , b): return(a + b) def sub(a , b): return(a - b) def mult(a , b): return(a * b) def division(a , b): return(a // b) def modulus(a , b): return(a % b) print("select operation:") print("1.add of a and b is:") print("2.sub of ...
344de2bd22b3a00639d6b89e35c17b7e0bec6da5
bosefalk/small_meal_planner
/meals_wrapper.py
685
3.53125
4
import meals import sys # Select four random meals and print them meal_list = meals.random() print('\n') print('\n') print('\n') print('Four chosen meals:') print(meal_list) print('\n') allowed_numbers = [1,2,3,4] selecting = True while selecting == True: user_input = input("select " + str(allowed_numbers) +", Al...
9dba4ddee189dd1094f32328b6e5638eaaec16c9
sylviachan127/Python-Intro
/HW10.py
2,241
3.734375
4
#Yuen Han(Sylvia) Chan #Section: B01 #GTID: #902983019 #Email: ychan35@gatech.edu #I work on the entire HW by myself from Myro import* import time import math init() #This homework contains 2 functions, one is to calculates the G Force, #another one is to control robot with color. def gravitationalForce(): #This func...
8cf092c3be2f448f4fc062ad93975f413aa607b9
grypyAndy/andelaTests
/stringlab.py
477
3.75
4
i='yes' j="Maybe" print (i*5) print(j*3+i*5) #the interview section applicant=input("Enter the applicant's name: ") interviewer=input("Enter the interviwer's name: ") time=input("Enter the appointment time: ") print(interviewer, "will interview", applicant, "at ", time) #entering numbers and getting a sum xstring...
bad796cdceeeb2c1a3641944b82e1e51ab1e51ac
1071183139/biji
/5_python基础/1_字符串.py
2,201
3.859375
4
# 字符串的格式化输出 # username=input('请输入名字') # print('你的名字为%s'%username) #字符串的切片 name = 'abcdef' # print(name[0]) name = 'abcdef' # print(name[2:]) # 取 下标为2开始到最后的字符 name = 'abcdef' # print(name[1:-1]) # 取 下标为1开始 到 最后第2个 之间的字符 # print(name[::-1]) # fedcba 逆序 步长为1 # print(name[::-2]) # fdb 逆序 步长为2 # format函数 #...
5f849288cc936f586ecbf6daf928afdbac9b4948
1071183139/biji
/4_面试题/2_网上找的/1_大黄蜂面试题/5_高阶函数.py
711
4.09375
4
# map(f,list)是 Python 内置的高阶函数,它接收一个函数 f 和一个 list, # # 并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的可迭代对象并返回。 # li=[1,2,3,4,5] # def func(x): # return x * x # li1=map(func,li) # # li2=map(lambda x:x*x,li) # # # print(list(li1)) # print([i for i in li2]) # filter方法求出列表所有奇数并构造新列表a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]? # a = [1,...
e4c76d2fc432ebb3f228aa6e88021e1fdeae6930
1071183139/biji
/7_py实用编程技巧/2_对象迭代和反迭代/2_3反向迭代.py
640
3.8125
4
class FloatRange: def __init__(self, start, end, step=0.1): self.start = start self.end = end self.step = step # 正向迭代器 def __iter__(self): t = self.start while t <= self.end: yield t t += self.step # 反向迭代器 def __reversed__(self): ...
b24e2b4d66157574392a9861bb2c68b86248607d
1071183139/biji
/3_简历/3_python操作excel/1_获取excel/5_遍历行和列中单元格的值 .py
586
3.65625
4
import openpyxl # 打开excel文件,获取工作簿对象 wb = openpyxl.load_workbook('example.xlsx') ws = wb.active # 当前活跃的表单 col_range = ws['B:C'] row_range = ws[2:6] # for col in col_range: # 打印BC两列单元格中的值内容 # for cell in col: # print(cell.value) # for row in row_range: # 打印 2-5行中所有单元格中的值 # for cell in...
8a9d3d3ed9ec795f9f3bc61d66df424ad06118b8
aysebilgegunduz/Memcached_Load_Balancer
/webserver.py
2,801
3.515625
4
from flask import Flask from flask import make_response from flask import request from lib.cache import Cache import names import configparser config = configparser.ConfigParser() config.read("config.ini") MAX_USER = config.getint('Defaults', 'max_number_of_client') CACHE_1 = Cache(config.get('Defaults', 'memcache_ad...
c4eb3c25ca77674db9f7f11884a94a5ddb60af2e
penicillin0/atcoder
/ABC/029/c.py
196
3.734375
4
def dfs(n, string): if n == N: print(string) else: dfs(n + 1, string + 'a') dfs(n + 1, string + 'b') dfs(n + 1, string + 'c') N = int(input()) dfs(0, '')
371da8bf4eb27baab5753fd7f86bb4d878f95ce2
penicillin0/atcoder
/ABC/142/a.py
84
3.5
4
n = int(input()) if n % 2 == 0: a = n // 2 else: a = n // 2 + 1 print(a/n)
c80f70c511c515dc0fbe42199aad5b42a936d54e
penicillin0/atcoder
/ABC/002/b.py
104
3.546875
4
W = input() ans = '' for w in W: if w not in ['a', 'i', 'u', 'e', 'o']: ans += w print(ans)
b8abe9896b291ba6ae31a9611f686d2c3e7c629b
penicillin0/atcoder
/ABC/144/d.py
277
3.6875
4
from math import atan from math import pi a, b, x = map(int, input().split()) if a * a * b / 2 <= x: ans = atan((2 * b) / a - 2 * x / (a ** 3)) ans = ans * 180 / pi else: ans = atan(2 * x / (a * (b ** (2)))) ans = ans * 180 / pi ans = 90 - ans print(ans)