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
d036887e2e21a71bd9058bd8a977699341a65225
chengaojie0011/offer-comein
/py-project/Solution59-1 2.py
1,226
3.65625
4
# -*- coding:utf-8 -*- class Solution: def maxInWindows(self, num, size): # write code here max_in_windows, index= [], [] if len(num)<size or size<1: return max_in_windows for i in range(0,size): while len(index) >0 and num[i] >=num[index[-1]]: ...
7ba006f1696856640ae219bc04259c1bbc482faf
chengaojie0011/offer-comein
/py-project/Solution12 2.py
2,421
3.734375
4
# -*- coding:utf-8 -*- class Solution: def hasPath(self, matrix, rows, cols, path): # write code here for i in range(rows): for j in range(cols): if matrix[i*cols+j] == path[0]: self.b = False print(i, ',', j, ',', path[0]) ...
843c7af47113d5316c157ae94b92ca39336e3100
chengaojie0011/offer-comein
/py-project/Solution31.py
585
3.84375
4
# -*- coding:utf-8 -*- class Solution: def IsPopOrder(self, pushV, popV): # write code here # res = False stack = [] if pushV and popV: for i in pushV: stack.append(i) while stack[-1] == popV[0]: stack.pop() ...
1513eb5d5b56a10e7f27d5ff10c0546ae3afa94a
chengaojie0011/offer-comein
/py-project/Solution62.py
956
3.515625
4
# -*- coding:utf-8 -*- class Solution: def LastRemaining_Solution(self, n, m): # write code here res = 0 if n<1 or m<1: return -1 numbers = list(range(n)) cur = 0 while len(numbers)>1: for i in range(0,m-1): cur +=1 ...
5363af997b944d944cb91eb56102e64b50f20700
chengaojie0011/offer-comein
/py-project/Solution53-3.py
622
3.5625
4
# -*- coding:utf-8 -*- class Solution: def GetNumberSameAsIndex(self, data): length = len(data) if data == None or length<=0: return -1 left = 0 right = length-1 while left<=right: mid = (right+left)//2 if data[mid] == mid: ...
c6d08a44293b4610a1a28118564c258cc7668fc3
chengaojie0011/offer-comein
/py-project/tree/inorder.py
869
3.828125
4
# -*- coding:utf-8 -*- import tree.tree_build as tree_con """递归实现树的中序遍历""" def in_order(root,ret= []): if root is None: return in_order(root.left) ret.append(root.value) print(root.value, end="\t") in_order(root.right) return ret """非递归实现树的中序遍历""" def in_order_stack(root): ret, ...
065f873804060d37aab42a3bd1156c984c3389bd
chengaojie0011/offer-comein
/py-project/Solution58-1.py
1,217
3.59375
4
# -*- coding:utf-8 -*- class Solution1: def ReverseSentence(self, s): # write code here length = len(s) if length <=1: return s l_s = list(s) r_s = self.Reverse(l_s, 0, length-1) i = 0 while i < length: while i < length and r_s[i] ==' '...
7530a56783a8bc09f206fdb7e533148f3936e244
chengaojie0011/offer-comein
/py-project/Solution22 2.py
1,080
3.703125
4
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def FindKthToTail(self, head, k): # write code here if head == None or k <= 0: return None node1 = head for i in range(k-1): if nod...
5a210c20c9ea7125a62245866a785fae5e3f4eee
helixphoenix/python_challenge_linkedin
/sudoku.py
1,676
4.0625
4
#This one is from the course from itertools import product from typing import List def sudoku_solver(puzzle: List[List[int]]) -> List[List[int]]: for (row, column) in product(range(0,9), repeat=2): #repeat 2 because row and column are both in range of 0,9 if puzzle[row][column]==0: for num ...
31f2a5867e1f49f703c48744a4378113b2875bff
wwwser11/first_game
/Player.py
886
3.53125
4
import pygame import random import os # make player sprite class class Player(pygame.sprite.Sprite): def __init__(self, ship_img, color, w, h): self.w = w self.h = h # initializing of internal classes of Sprite pygame.sprite.Sprite.__init__(self) # make img of sprite now it...
c2d4d41656ad09126cc00d059e5a22ea01813276
ProgrammerSahil/linear_equation_solver
/linear_equation_solver.py
1,428
3.640625
4
eq1 = list(input("Enter a, b and c of the equation ax+by+c=0 : ").split()) eq2 = list(input("Enter A, B and C of the equation Ax+By+C=0 : ").split()) #SEPARATE BY SPACE OBVS. #WE WILL USE THE ELIMINATION METHOD TAUGHT IN SCHOOL class equation: def __init__(self, eq1, eq2): self.eq1 = eq1 self.eq2 ...
e0d992eb6e27ae7d0529a0ad59d2968de83d7707
ttungl/laceupleetcoding
/techdevseries/Running median.py
638
3.65625
4
# Running median # Given a stream of numbers, compute the median for each new element. # input = [2,1,4,7,2,0,5] # return output = [2, 1.5, 2, 3.0, 2, 2, 2] class Solution: def __init__(self): self.res = [] def _find_median(self, arr): ans, n = 0, len(arr) arr.sort() if n%2==0: ans = (arr[n//2 - 1] +...
a57989b28e6cb6f6e593e5d99f471bdb1c971f7f
hetu494/Web-Analytics
/senticounter.py
1,200
3.625
4
def loadLexicon(fname): newLex=set() lex_conn=open(fname) #add every word in the file to the set for line in lex_conn: newLex.add(line.strip())# remember to strip to remove the lin-change character lex_conn.close() return newLex def run(path): decisions=[] reviews=[] PL=[]...
e18f2ef267ad69dd122378a9b809b491fb38adb5
SantiagoGonzalezR/ACE-base
/pregunta.py
4,588
3.546875
4
from plant import * from curso import * from random import sample, shuffle class pregunta: #-Pregunta debe ser una clase: Tema, id, respuesta correcta, respuestas incorrectas, enunciado. Funciones: ¿get? #id_pregunta='' #tema='' #enunciado='' #preg='' #respuestaC='' #respuestaI=[] #puntaje=0 #plantil...
6ba34b1bcd307cbac829ad8fbaba27571cd2c807
punkyjoy/LearningPython
/03.py
514
4.125
4
print("I will now count my chickens") print("hens", 25.00+30.00/6.0) print("roosters", 100.0-25.0*3.0%4.0) print("Now I will count the eggs:") print(3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6.0) print("Is is true that 3.0+2.0<5.0-7.0?") print(3.0+2.0<5.0-7.0) print("What is 3+2?", 3.0+2.0) print("What is 5-7?", 5-7) #this i...
4f496a45c22752a7d7ac85c8311dab78e7258a82
niujie/Python_Course_2020
/Numerical_Methods_for_Engineers/ch1/euler_pendulum_generic.py
2,126
3.5625
4
# src-ch1/euler_pendulum_generic.py import numpy as np import matplotlib.pylab as plt from math import pi # define Euler solver def euler(func, y_0, time): """ Generic implementation of the euler scheme for solution of systems of ODEs: y0' = y1 y1' = y2 . ...
57ab5226fdcb7bd2a0a3bf88d58c3f640d6b2c97
Barbandy/cryptographic-algorithms
/com_func.py
1,157
3.671875
4
#! /usr/bin/python #coding: UTF-8 import argparse def writeFile(fname, code): try: with open(fname, 'wb') as f: f.write(''.join(code)) except IOError: exit('No such file or directory ' + fname) def readFile(fname): try: with open(fname, 'rb') as f: text = f.read...
15028b98cebc6c3e435d8deec79bbe6f8626e092
yujit0518/python-challenge
/PyBank/main.py
1,694
3.84375
4
import csv # Load the csv file and write code for output results file_load = "budget_data.csv" file_output = "Bank_Analysis.txt" # tracking the parameters and creating variables from existing data total_months = 0 total_amount = 0 previous = 0 month_change = [] profit_change = [] greatest_increase = 0 g...
a39535427e61a1be04b329c55c091bbdc32f53ed
YasirNacak/Coursework
/cse321_algorithm_design/assignment_3/program.py
6,899
4
4
import math import random # QUESTION 1 def q1(bw_list, should_swap = False): # default should_swap is false because # first element always needs to be black if should_swap: # interchanging boxes bw_list[0], bw_list[len(bw_list) - 1] = bw_list[len(bw_list) - 1], bw_list[0] if len(bw_li...
06b36e6057fc811aed3539df425821a6f01a70c5
ananunes07/Lista6python
/Lista de exercício 3/Exe 01.py
661
3.9375
4
''' Autor: Ana Clara Nunes Data: 04/06/2018 Enunciado Questão 1 ''' n = int(input('Digite o número: ')) if n == 1 or n == 8 or n == 15 or n == 22 or n == 29: print('Domingo') if n == 2 or n == 9 or n == 16 or n == 23 or n == 30: print('Segunda feira') if n == 3 or n == 10 or n == 17 or n == 24 or n == 31: ...
2910eac975795a82a60758b184e78bae9e1132a9
ananunes07/Lista6python
/Lista de exercício 5/Exe 01.py
430
3.9375
4
''' Autor: Ana Clara Nunes Data:30/07/2018 Questão 01 ''' n = int(input('Digite um número entre 0 a 20:')) if n > 20 or n < 0: print('O número digitado deve estar entre 0 a 20') n = int(input('Digite um número entre 0 a 20:')) num = ('zero','um','dois','três','quatro','cinco','seis','sete','oito','nove','de...
cb31a1c5bc294e2df444772719ffa7e6c0c7b5d3
ananunes07/Lista6python
/Lista de exercício 4/Exe 14.py
285
3.734375
4
''' Autor: Ana Clara Nunes Data: 12/07/2018 Questão 14 ''' x = 5 m18 = 0 for x in range(1,x+2): idade = int(input('Digite a idade: ')) if idade < 18: m18 += 1 print(m18,'pessoas são menores de idade') medi = idade + idade / 6 print ('A média de idade é',medi)
9d92d23a4cd275da2cbcefa822c0c5fb0228853f
ananunes07/Lista6python
/Lista de exercício 2/Exe01.py
879
4.34375
4
''' Autor: Ana Clara Nunes Data: 14/05/2018 Enunciado: Faça um programa que peça os três lados de um triângulo. O programa deverá informar se os valores poem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. ''' A = float(input('Digite o lado A: ')) B = f...
751cda71524394c9e960a93f259b05e3e4099942
anandpatel2506/Test
/fibonacci.py
489
4.0625
4
nterms = 100 # uncomment to take input from the user #nterms = int(input("How many terms? ")) # first two terms a = 0 b = 1 cnt = 0 # check if the number of terms is valid if nterm <= 0: print("Please enter a positive integer") elif nterm == 1: print("Fibonacci Sequence upto",nterm,":") print(a) else: p...
1250bef5e2c26658d2daa6219542608005bd6d4e
DropName/infa_2019_primak
/lab3/Task2.py
9,673
4.125
4
from graph import brushColor, penColor, penSize from graph import circle, line, polygon, point, rectangle from graph import canvasSize, windowSize, run from random import randint import math as m def apple(x, y, size, mirror): """ apple function draws the apple of the radius r pxls for size = 1 there...
e7934f8609c70ab719e23eb713cd1e035dd64e15
allegheny-computer-science-310-s2020/class_activities
/a4_face-detection/src/imagesearch/facedetector.py
2,600
4.0625
4
# import the necessary packages import cv2 ''' use the built-in Haar cascade classifiers in OpenCV. These classifiers have already been pre-trained to recognize faces! If we wanted to build our own classifier, we would need a lot of positive and negative images. Positive images would contain images with faces, wherea...
e3d3bdfcd469758146aa7dbdf05413f7d7c55c5d
Umardahil/python
/main.py
597
4.09375
4
# #! 1 Задание: # number1 = int(input('Enter a number: ')) # operator = input('Enter a operator: ') # number2 = int(input('Enter a number: ')) # # if operator == '-': # print(number1 - number2) # elif operator == '/': # print(number1 / number2) # print('I love Java' + 'python') # print('nazar' * 10) # text ...
927503abb71772aab66983a4a625c13ad7d30d4b
Cmart94/holbertonschool-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
206
3.765625
4
#!/usr/bin/python3 def max_integer(my_list=[]): if not my_list: return (None) max_int = my_list[0] for i in my_list: if max_int < i: max_int = i return (max_int)
1ce6ce9993a4a947397c9c42eff0f3fc832e279e
Cmart94/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
258
3.75
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): new_tuple_a = tuple_a + (0, 0) new_tuple_b = tuple_b + (0, 0) at = new_tuple_a[0] + new_tuple_b[0] bt = new_tuple_a[1] + new_tuple_b[1] result = tuple((at, bt)) return(result)
d4bad854227ad91b7ad5a305906060837f0a11fa
Prince9ish/Rubik-Solver
/colors.py
1,592
4.1875
4
'''For representing color of the rubik's cube.''' from pygame.locals import Color from vpython import * class ColorItem(object): '''WHITE,RED,BLUE,etc are all instances of this class.''' def __init__(self,name="red"): self.name=name self.color=color.red self.opposite=None de...
12ba93761123128abf8e4af3224a5b154ffa73b9
simon-ball/opexebo
/opexebo/analysis/autocorrelation.py
1,908
3.546875
4
""" Calculate 2D spatial autocorrelation Calculates 2D autocorrelation (autocorrelogram) of a firing map. """ import numpy as np import opexebo def autocorrelation(firing_map): """Calculate 2D spatial autocorrelation of a firing map. Parameters ---------- firing_map: np.ndarray NxM matrix,...
cd92a41a495d3d7dae140caa5088b81c206291d6
jskelcy/qmk_toolbox
/lib/python/qmk/path.py
1,051
3.796875
4
"""Functions that help us work with files and folders. """ import logging import os from qmk.errors import NoSuchKeyboardError def keymap(keyboard): """Locate the correct directory for storing a keymap. Args: keyboard The name of the keyboard. Example: clueboard/66/rev3 """ for d...
261bad8fd4e63f9b14118686c6c16adb63c3b82a
duecknoah/programming_challenges
/what_day_was_it/with_calendar_module.py
340
3.96875
4
""" Challenge #338 [Easy] What day was it again? https://www.reddit.com/r/dailyprogrammer/comments/79npf9/20171030_challenge_338_easy_what_day_was_it_again/ """ import calendar as cal date = input('Enter YYYY MM DD: ').split() year = int(date[0]) month = int(date[1]) day = int(date[2]) print(cal.day_name[cal.weekday...
55e3c7d14c1d798deff07b0158dc5c5fbc691be2
Maffer16/Proyecto-final-arquitecturas-programables-avanzadas
/database.py
1,361
3.640625
4
import psycopg2 from psycopg2 import Error connection=psycopg2.connect(user="proy", password="proy",host="127.0.0.1",port="5432",database="proy") cursor=connection.cursor() try: createTableQuery='''Create TABLE IF NOT EXISTS SENSORBME280 (ID SERIA...
f7ccc7d3661ee22454f0531cc7b07321feb47d18
frankietran/UdemyCourse
/class-oop/homework.py
530
3.734375
4
class Fruit(object): def __init__(self): print("Created a fruit instance") def nutrition(self): print("Fruit nutrition") def fruit_shape(self): print("Fruit shape") class Apple(Fruit): def __init__(self): Fruit.__init__(self) print("Creating an apple instance"...
d56d51d92ccae4562e0f9c74d96ecf242ba49d77
AllaVved/Python_lessons_basic
/hw05_easy.py
1,849
3.84375
4
# coding: utf-8 __author__ = 'Введенская Алла' # Задача-1: # Напишите скрипт, создающий директории dir_1 - dir_9 в папке, # из которой запущен данный скрипт. # И второй скрипт, удаляющий эти папки. import os # Создаем директории def make_dir(dir_name = "dir_", x = 9): number_dir = 1 while number_dir <= x: pat...
9da5b3f7e14b49c8bec9d870c7e6e9254e7f625b
thecruel/python
/Random Şifre.py
1,948
3.578125
4
import random sayı1 = int(input("Parola minimum kaç karakter olsun?: ")) sayı2 = int(input("Parola minimum kaç karakter olsun?: ")) uzunluk = random.randint(sayı1,sayı2) harfler = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sayilar = "0123456789" karakterler = "\"'!#@.,$" while True: giriş_...
3000ec6bcf9c5393b7257d2b8892c1e6543632da
srikarnikhil/python_practice
/Databases/MusicalTracks.py
2,651
3.609375
4
import xml.etree.ElementTree as ET import sqlite3 conn=sqlite3.connect('musicaltrackdb.sqlite') cur=conn.cursor() cur.executescript(''' DROP TABLE IF EXISTS Artist; DROP TABLE IF EXISTS Album; DROP TABLE IF EXISTS Track; DROP TABLE IF EXISTS Genre; CREATE TABLE Artist ( id INTEGER NOT NULL PRIMARY KEY AUTOINCRE...
f017d6ae7132ac9bb9b82a07de714c673343a256
srikarnikhil/python_practice
/regex/extrctDataUsingRegexListComprehension.py
447
4.0625
4
#The basic outline of this problem is to read the file, look for integers using the re.findall(), # looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and # summing up the integers. import re filename=input('Enter file name:') filehandle=open(filename) total=sum([int(num...
5c16042fe222d5aeceefc78d5124db0c0a0963ff
Bestfeel/pythonPractice
/base/demo2.py
420
3.734375
4
#!/bin/env python # coding=utf-8 from abc import abstractmethod, ABCMeta class AbstractMyClass(object): __metaclass__ = ABCMeta @abstractmethod def show(self): print("show .....") class SomeClass(AbstractMyClass): def show(self): print ("必须实现抽象方法") def funSwitch(args): return...
521654cd787e15308b36e274745edf1cc1a0dae7
joaopauloramos/pythonbirds_I
/calculadora/oo/framework.py
1,460
4.21875
4
# Classes Abstratas class Operacao: """Classe responsável por definir como calculo é feito""" def calcular(self, p1, p2): raise NotImplementedError('Precisa ser implementado') class Calculadora: """Classe responsável por obter inputs e efetuar operação de acordo""" def __init__(self): ...
70b5dfe3c86a6f59f0e656834df5b5dc52e2e151
joaopauloramos/pythonbirds_I
/calculadora/procedural/biblioteca.py
763
4.15625
4
def calcular_iterativamente_forma_infixa(): p1 = input('Digite o primeiro número: ') p1 = float(p1) sinal = input('Digite o sinal da operação (+ ou -): ') p2 = input('Digite o segundo número: ') p2 = float(p2) return _calcular(sinal, p1, p2) def calcular_iterativamente_forma_prefixa(): sin...
1c2439a4add498de80cf3b71955feb2f7866e490
joaopauloramos/pythonbirds_I
/calculadora/oo/testes/testes_unitario.py
937
3.5625
4
#!/usr/in/python3 from unittest.case import TestCase from calculadora.oo.framework import Adicao, Calculadora class CalculadoraParaTeste(Calculadora): def obter_inputs(self): return 'mock',1,2 class OperacaoMock: def calcular(self, p1,p2): return p1,p2 class AdicaoCasosDeTeste(TestCase): ...
8d9e5cafa1ba266c371917f42d7c07a8a54053df
vinhlee95/algorithm-data-structure
/closest-pair-of-points/main.py
3,261
4.21875
4
# A divide and conquer program in Python3 # to find the smallest distance from a # given set of points. import math import copy # A class to represent a Point in 2D plane class Point(): def __init__(self, x, y): self.x = x self.y = y # A utility function to find the # distance between two points def dist(p1, p2):...
2d615e9e4ffbd2d2cfded1afbb5b627aceb478be
jatin7gupta/COMP9321-Practice
/week_4/transform_data.py
1,155
3.5
4
import pandas as pd def transform(df): columns_to_drop = ['Edition Statement', 'Corporate Author', 'Corporate Contributors', 'Former owner', 'Engraver', 'Contributors', 'Issuan...
676acf4d43b0fe82b761cf15ff66b16e12dce24d
faisalkhan91/Expression-Parser
/ExpressionParser.py
11,375
3.890625
4
#!/usr/bin/python3 ############################################################################################# # Program by Mohammed Faisal Khan # # 00598949 # # ...
387985f112fa33529de5dc96c2ef27ac01a8a790
mirokrastev/Python-Algorithms
/sorting/SelectionSort/selection_sort.py
910
3.84375
4
# Selection Sort, Python implementation. @mirokrastev class SelectionSort: def __init__(self, unsorted_ll): self.__sorted_ll = [] self.__unsorted_ll = unsorted_ll self.__iterate_over_ll() def __get_min_element(self): min_num = None for num in self.__un...
f9923b1b4b01f6653a75aa5ff997bb0c3af3d8bc
Maiza584/pythonProject8
/Excle.py
1,899
3.765625
4
# import xlsxwriter module import xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create. workbook = xlsxwriter.Workbook('bye.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Use t...
435f2f05cc84814b53a4edc6f589a1e30ed63ef8
harmanpv64/assign
/regularexp.py
497
3.65625
4
import re #Q1 emails=["zuck26@facebook.com","page23@google.com","jeff42@amazon.com"] ls=[] for i in emails: a=re.findall("[\w]+",i) a=tuple(a) ls.append(a) print(ls) #Q2 text="Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, " \ "To make the bitter butter b...
0846d291d3e5e73d00a55573c7df0eb56b3625dd
harmanpv64/assign
/Assign2.py
279
3.59375
4
#Q1 print("Hello") #Q2 print("acad"+"view") #Q3 x=1 y=2 z=3 print(x,y,z,) #Q4 print("let\'s get started") #Q5 s="acadview" course="python" fees=5000 print("hi,%s your course:%s your fees:%d"%(s,course,fees)) #Q6 name="tony stark" salary=1000000 print(('%s''%d')%(name, salary))
c15f2f96c83613760eacda24d041a896ce8aadf1
claudiordgz/GoodrichTamassiaGoldwasser
/ch01/c121.py
759
3.921875
4
__author__ = 'Claudio' """Write a Python program that repeatedly reads lines from standard input until an EOFError is raised, and then outputs those lines in reverse order (a user can indicate end of input by typing ctrl-D). """ def read_sdin(data): age = 1 if age > 0: try: age = int(input...
ae471d6db283d8d28d6fe43934656f47a5192cec
claudiordgz/GoodrichTamassiaGoldwasser
/ch01/c113.py
357
4.125
4
__author__ = 'Claudio' """Write a pseudo-code description of a function that reverses a list of n integers, so that the numbers are listed in the opposite order than they were before, and compare this method to an equivalent Python function for doing the same thing. """ def custom_reverse(data): return [data[len(...
5aae3515aed32627600c08ebdf14d8e4518fcd4a
claudiordgz/GoodrichTamassiaGoldwasser
/ch01/c122.py
252
3.90625
4
__author__ = 'Claudio' """Write a short Python program that takes two arrays a and b of length n storing int values, and returns the dot product ofa and b. That is, it returns an array c of length n such that c[i] = a[i]·b[i], for i = 0,...,n−1. """
364107a1b807d346b5dc38846598dd402063aa3a
gauthamkrishna1312/python_xp
/fn1.py
233
4.125
4
def check(num): if num == 0: print("Zero") elif num > 0: print("Positive") elif num < 0: print("Negative") else: print("Invalid input") value = input("Enter a number = ") check(value)
47ade36bd4fc754b29fd7a3cd898ddef5b87ca7e
smholloway/miscellaneous
/python/indentation_checker/indentation_checker.py
2,876
4.375
4
def indentation_checker(input): # ensure the first line is left-aligned at 0 if (spaces(input[0]) != 0): return False # emulate a stack with a list indent_level = [] indent_level.append(0) # flag to determine if previous line encountered was a control flow statement previous_line_was_control = False # iter...
46e86cd58a2bf892e9d52748b716d2b4f6de99a1
odkobozeva/automate_python
/cheats.py
5,733
4.3125
4
"""СПИСКИ""" """Вывести минимальное, максимальное, сумму""" def test_min_max_sum(): numbers = [1, 2, 3] print(min(numbers)) print(max(numbers)) print(sum(numbers, 10)) """Вывести все элементы, которые меньше 5""" def test_elem(): # Перебор элементов a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ...
3c2f71fc042ccbcd713bbd2c256ca044803b12f7
Cristobal3/hero-rpg
/herorpg.py
1,783
3.828125
4
import random class Character: def alive(self): if self.health > 0: return True else: return False def attack(self, enemy): if self == hero: num = random(1,5) if num == 5: enemy.health -= 2*self.power else: ...
eafdd212ec14c33bd7f52fba8b53316e128eb8dc
Sachinx0e/reinforcement_learning
/agent.py
6,484
3.546875
4
import random from action import Action from state import StateType class Agent: def __init__(self, state_space, start_state, learning_rate,discount_rate, exploit_prob, living_reward): self._state_space = state_space self._current_state = start_state self._learning_rate = learning_rate ...
d1f00fa6f224748010687c63f08e01a3142d62cf
pawlmurray/CodeExamples
/ProjectEuler/1/MultiplesOf3sAnd5s.py
688
4.3125
4
#get all of the multiples of threes and add them up def sumOfMultiplesOfThrees(max): currentSum = 0 threeCounter = 3 while(threeCounter < max): currentSum+= threeCounter threeCounter += 3 return currentSum #Get all of the multiples of fives and add them up, if they are #evenly divis...
8976d74cd4583c91d1f2870afb7861ee99f32f32
kirillmasanov/skillbox
/lesson_002/08_garden.py
1,560
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # в саду сорвали цветы garden = ('ромашка', 'роза', 'одуванчик', 'ромашка', 'гладиолус', 'подсолнух', 'роза', ) # на лугу сорвали цветы meadow = ('клевер', 'одуванчик', 'ромашка', 'клевер', 'мак', 'одуванчик', 'ромашка', ) # 1 - создайте множество цветов, произрастающих ...
efbac0b803015003e57f3beb49782f0c2f467682
kirillmasanov/skillbox
/lesson_007/probe.py
658
3.671875
4
class Robot: def __init__(self, model): self.model = model def __str__(self): return '{} model {}'.format(self.__class__.__name__, self.model) def operate(self): print('Робот ездит по кругу') class WarRobot(Robot): def operate(self): print('Робот охраняет военный об...
297a8926863329e694677f94f4dacd685c86449b
kirillmasanov/skillbox
/lesson_011/01_shapes.py
1,953
4.0625
4
# -*- coding: utf-8 -*- import simple_draw as sd # На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику, # которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д. # # Функция рисования должна принимать параметры # - точка начала рисования # - угол...
15f0f2d2df7b43605d783b64681d82df8849e8c8
albertogcmr/gui-tkinter-examples
/16-label-keys.py
560
3.875
4
from tkinter import * my_window = Tk() # crea un objeto por defecto # CODE label_1 = Label(my_window, borderwidth=4, relief='solid', font='Times 22 bold', background='red', foreground='white', text='Hola Mundo')...
23a65130451b9e13bcfe796d614881c7093a7144
albertogcmr/gui-tkinter-examples
/02-background.py
504
3.96875
4
""" https://www.w3schools.com/colors/colors_picker.asp """ from tkinter import * my_window = Tk() # crea un objeto por defecto: fondo gris, maximizar, minimizar, etc. # CODE GOES HERE my_window.title("Demo1") # set the background of the window # también se puede usar bg en vez de background # Se puede ...
4469e93b466a27c0f28c8ebdc338df48d2c96a6f
albertogcmr/gui-tkinter-examples
/17-stringvar-textvariable.py
396
3.828125
4
from tkinter import * my_window = Tk() # crea un objeto por defecto # CODE var_1 = StringVar() # crea un string que se puede asociar con un Label label_1 = Label(my_window, relief='solid', font='Times 22 bold', textvariable=var_1) label_1.pack() res = inp...
c5ef0dd18306532299c674cfde252c5d5f599e12
rumdrums/_
/old-staircase-most-golden
2,329
3.71875
4
#!/usr/bin/env python import timeit class BrickStash: def __init__(self, num_bricks): self.num_bricks = num_bricks self.staircases = [] self.get_combos(self.num_bricks) def get_combos(self, lval, depth=1, carried=None, rval=0): #print("brand new iteration: %d" % depth) if carried is None: ...
df0adfa7de6036c164bc12cacf85eb217ccf98c3
Kartikkh/OpenCv-Starter
/Chapter-3/1-Contours.py
1,223
3.71875
4
import numpy as np import cv2 #For better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection. #findContours function modifies the source image. So if you want source image even after finding contours, #already store it to some other variables. #In OpenCV, finding contours ...
d7468de2be523b14bb8cddf5e10bf67e64663fe9
Kartikkh/OpenCv-Starter
/Chapter-2/8-Blurring.py
2,789
4.15625
4
## Blurring is a operation where we average the pixel with that region #In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, #embossing, edge detection, and more. #This is accomplished by doing a convolution between a kernel and an image. # https://www.yo...
32887a264b8a0cb55374c17772ab07872d548cf3
Gareth-Mawer/edX
/MIT 6.001x/Midterm Exam/midterm.py
4,515
4.125
4
""" Midterm Exam Programming Questions from MIT 6.00.1x Course Author: Gareth Mawer """ # Problem 4, previous problems were multiple choice questions def closest_power(base, num): ''' base: base of the exponential, integer > 1 num: number you want to be closest to, integer > 0 Find the intege...
11e2213292c6352fb9f12525797aa43b7b2651e7
petulica/HW_4
/ukol13.py
157
3.734375
4
for radek in range(6): if radek == 0 or radek == 5: for strana in range(6): print ("X", end=' ') print() else: print('X', ' '*7, 'X')
b416567eeb296162f94c88cc47d4096049b1560e
jmtaysom/Python
/CodeEval/stringlist.py
628
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri May 13 12:37:55 2016 @author: jmtaysom """ def recursive_print(n,string,out=''): global final for letter in string: if n>1: recursive_print(n-1,string,out=out+letter) else: final += out+letter+',' with...
514fbfa2e340addc29c2a928a6ace99c042fcb7b
jmtaysom/Python
/Euler/004ep.py
643
4.25
4
from math import sqrt def palindrome(): """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ for x in range(999,100,-1): ...
7a1d1339e877dd16112d267233cc2ca9ba4e54ff
mcclanahoochie/from_google_code
/python/nlp-hist/hist.py
5,850
4.09375
4
#---------- histogram.py ----------# # Create occurrence counts of words or characters # A few utility functions for presenting results # Avoids requirement of recent Python features from string import split, maketrans, translate, punctuation, digits import sys from types import * import types def trigram_histogram(...
e71b20f9dbb5f8d31adc3eceed6d3e2b1cdf6a7b
huiwamwang/text_generator
/text_generator.py
3,256
3.8125
4
"""Last stage of the 'Text Generator' project. ***BLOCK 1*** We are taking text input with the name of the file with training word dataset, open the file and tokenize it with 'WhitespaceTokenizer()' - basically .split() function. ***BLOCK 2*** From the corpus, we create a list of trigrams. ***BLOCK 3*** We create a ...
a2aa78a4894835235fb34904bbcf8d3b586be6be
sydneypickle/JSON_Project_Repository
/1-13Fires.py
1,446
3.75
4
""" Use the files below to compare the fires that have been burning in California between Sept 1-13 and Sept 14 - 20. This file contains information about the latitude and longitude, and the brightness of each fire. Using what you have learnt in processing a JSON files and mapping, make a map that shows the fires. Yo...
79d0c5882e5031ac0dea21e8a34467d02ff45d33
Perlou/python-practice
/python3-demo/commonlib/use_datetime.py
531
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from datetime import datetime # 获取当前时间 now = datetime.now() print('now =', now) print('type(now)=', type(now)) # 用指定日期时间创建datetiem dt = datetime(2017, 6, 1, 12, 20) print('dt =', dt) # 把 datetime 转换成 timestamp print('datetime -> timestamp:', dt.timestamp()) # 把 timest...
f5d9707e28f3caa730c939e3ac5e164250643e22
Perlou/python-practice
/python2-demo/oop/o7.py
334
3.6875
4
class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score s = Student('Perlou', 'Male', 123) print s.name, s.gen...
2a5221102ca0550c31cfd5fffdb55b8a4447055c
GITlibin1025/pyLearn
/fbnq.py
896
3.921875
4
#斐波那契数列 #使用迭代 ''' #多行注释 def fab(n): n1 = 1 n2 = 1 n3 = 1 #默认初始值为1 if n < 1: print("输入有误") return -1 while (n-2) > 0: n3 = n1 + n2 n1 = n2 n2 = n3 n -= 1 return n3 x = int(input("请输入项数")) fanhuizhi = fab(x) if fanhuizhi != -1: print('该项的系数为%d' % fanhuizhi) ''' def fab(x): x1 =...
64d726aadc6c6ae0a2c6ac018baf8707ca693831
mbazych/cdv
/Strukturalne/obliczenia.py
248
3.75
4
try: a = float(input("Podaj a: ")) b = float(input("Podaj b: ")) if a + b == 0: print("Nie dzieli się przez 0") else: c = (a*a+b)/(a+b)**2 print(f'Wynik: {c}') except ValueError: print("Błędne dane!")
1f3e03e3b71faec688b8b03b74af02fb5eba53b7
mbazych/cdv
/Strukturalne/slowniki.py
1,077
3.546875
4
slownik = {'klucz1':'wartosc1', 'klucz2':'wartosc2'} ''' Utwórz słownik o nazwie pracownik zawierający klucze: imie, nazwisko, miasto, wiek, imionaDzieci, imionaRodzicow ''' pracownik = { 'imie': 'Michał', 'nazwisko': 'Bazych', 'miasto': 'Trzebiatów', 'wiek': 20, 'imionaDzieci': ['Jan', '...
de63e6e1ff87ac0be5de4bec6bad1a807052a5b8
Ibukun-Badmus/Datascience_Exercises_With_Python
/Squares.py
291
3.828125
4
squares = ["One", "Two", "Three", "Four", "Five"] values = [1, 2, 3, 4, 5] print(dict(zip(squares, values))) def make_squares(squares_, values_): make_new_squares = {} for x, y in zip(squares_, values_): make_new_squares[x] = y ** 2 return make_new_squares
cb1a40c27a7582cd67ebd31eed43e58a2a5a76c6
AxelInd/Machine-Learning-Testbed
/Algorithms From Scratch/feedForwardNeuralNetwork.py
1,515
3.75
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 7 12:44:44 2021 @author: axelt """ import numpy as np #the most common ANN activation function def activationFunction_sigmoid (value): return 1.0/(1+np.e**(-1*value)) #inputs x = np.array([[1,2,3,4,5],[6,7,8,9,10]]) #.reshape(-1,x) infers the size of the original 1...
3140727c46021881de2cca69254f367ff3b6422c
Agent1000/pythoner-ML2AI
/loop in loop.py
138
3.765625
4
i = 1 while i <=8: j = 1 while j<=8: print("ครั้งที่ ",i," รอบที่ " , j) j+=1 i+=1
25785c99718e4f26dbb5b63a583b522d46697ebd
Agent1000/pythoner-ML2AI
/หาเลข มากสุด น้อยสุด.py
682
4.25
4
x=int(input("กรอกเลขครั้งที่ 1 > ")) y=int(input("กรอกเลขครั้งที่ 2 > ")) z=int(input("กรอกเลขครั้งที่ 3 > ")) if z>y and z>x :print(z,"มากที่สุด") elif x>y and x>z:print(x,"มากที่สุด") elif y>x and y>z :print(y,"มากที่สุด") if z<y and z<x : print(z,"น้อยที่สุด") #if เช็คใหม่ หาเลขน้อยสุด elif x<y and x<z:print(x,"...
7c50d1cf0c89424f64ccea7e729157f520695136
Agent1000/pythoner-ML2AI
/ซ้อน loop.py
159
3.921875
4
# loopซ้้อน loop i=1 while i<=3: j=1 while j<=8: print("รอบที่ ", i,"ครั้งที่ ", j) j+=1 i+=1
95dd635ca9e4423673761585bfbe36486a169c84
Agent1000/pythoner-ML2AI
/for return.py
345
4
4
def count_vowel(str): vowel = 0 for c in str: if c in ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'): vowel = vowel + 1 print(f"สระในภาษอังกฤษในประโยคที่พิมมา มี {vowel} ตัว " ) n = str(input("กรอกคำ>>")) count_vowel(n)
63d411c5d7889b53c52cf9d1f74ec23f8e2b391f
malumelo7/exercicios-python
/exe04.py
207
4.0625
4
numero = int(input('Digite um valor:')) j=0 print('Current as previous number sum in a range(',numero,')') for i in range(numero): print('Current number:',i,'Previous number',j,'Sum:',i+j) j=i
383f21357ea4d282d4bca136a67518d704abc5e3
malumelo7/exercicios-python
/exe24.py
656
3.890625
4
def Encontra(lista, proc,min, max): mid = (min + max)//2 if proc == lista[mid]: print(f"Proc={proc}, lista[mid]= {lista[mid]} ") return mid elif proc < lista[mid]: print(f"Proc={proc}, lista[mid]= {lista[mid]} ") return Encontra(lista, proc, min, mid-1) elif proc > li...
d189e9268baa4a80d24dbe0cea62528c1965c1f5
malumelo7/exercicios-python
/exe03.py
259
3.921875
4
primeiro = int(input('Digite o primeiro número:')) segundo = int(input('Digite o segundo número:')) soma = primeiro+segundo multiplicar = primeiro*segundo if multiplicar>1000: print('Deu maior que 1000, sua soma é:',soma) else: print('Deu menor.')
ef4521cc8aa1020b134331df34e833d4a77bd3dd
omisunuwar/Python
/test.py
342
3.765625
4
fname = input('Enter file name: ') if (len(fname) < 1): fname = 'mbox.txt' fh = open(fname) for line in fh: if not line.startswith('From: '): continue pieces = line.split() email = pieces[1] #print(email) lst=list() #for e in email: parts=email.split('@') domain=parts[1] #lst.append(doma...
8eba40a2e369c4d3cf5db974f126a2aecdf55225
omisunuwar/Python
/Ex8-5 -worked.py
722
4.03125
4
#file is mbox-short2.txt fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short2.txt" #press enter defaults to mbox-short2.txt fhand = open(fname) count = 0 for line in fhand: line=line.rstrip() words=line.split() #if len(words)<3: continue #Guardian pattern to see if the word is shor...
fdc9a6f882f1f4be935a0dfed1d44d72f56f1a80
Yudhajith/cmpe255-spring19-Lab2
/friend.py
284
3.546875
4
import numpy as np def mean_num_friends(x): return np.mean(x) def median_num_friends(x): return np.median(x) num_friends=[100, 49, 41, 40, 25, 10, 5, 4, 7, 20, 60] print("Mean = ", mean_num_friends(num_friends)) print("Median = ", median_num_friends(num_friends))
12dad31fc6576ac2ade7215f3bd7fcb67311e796
Vibertexs/Python
/4inarow.py
561
3.703125
4
grid1 = [0,0,0,0,0,0,0] #This is the top row grid2 = [0,0,0,0,0,0,0] grid3 = [0,0,0,0,0,0,0] grid4 = [0,0,0,0,0,0,0] grid5 = [0,0,0,0,0,0,0] grid6 = [0,0,0,0,0,0,0] # This is the bottom row print("Player one is represented as 'x' while player two is represented as 'o'") def printGrid(): print("", grid1, "\n", ...
4626b5b5da64d718d75eb5cf0e45d0ff27032255
huginngri/Skilaverkefni
/Skilaverkefni 2/characterCounts.py
571
3.875
4
sentence = input('Enter a sentence: ') upper = 0 lower = 0 digit = 0 punct = 0 for k, j in enumerate(sentence): if sentence[k].isdigit() == True: digit += 1 elif sentence[k].islower() == True: lower +=1 elif sentence[k].isupper() == True: upper +=1 elif sentence[k] == ' ': ...
2df586adab5cca8eef6f3101b000b71133b582a5
huginngri/Skilaverkefni
/Skilaverkefni7/TicTacToe.py
2,812
4
4
def size_of_board(): while True: the_size = int(input("Input dimension of the board: ")) if the_size >= 3: break return the_size def get_list_board(the_size): i = 1 j = 0 big_list = [] while i <= the_size: one_list = [] for k in range((j*the_size),(i*...
f740967c23e72c96ed4e54c4bad40ace3a2f3610
COREENE/python
/pylog2.py
18,128
3.9375
4
#python 学习笔记2之模块,面向对象编程,面向对象高级编程,错误调试和测试 #难点:metaclass元类 #模块 #目录组织模块——包Package #__init__.py本身就是一个模块,而它的模块名就是包名mycompany #!/usr/bin/env python3 # -*- coding: utf-8 -*- ' a test module '#模块的文档注释 __author__ = 'Michael Liao' #作者 import sys #导入sys模块 def test(): args = sys.argv if len(args)==1: prin...
5904acd697e84a4063452b706ab129537e53ab5b
Aryamanz29/DSA-CP
/gfg/Recursion/binary_search.py
627
4.15625
4
#binary search using recursion def binary_search(arr, target): arr = sorted(arr) #if array is not sorted return binary_search_func(arr, 0, len(arr)-1, target) def binary_search_func(arr, start_index, end_index, target): if start_index > end_index: return -1 # element not found mid = (start_index+end_index) //2...
f85760ebd360952a68bff5475fabae43a2c91c64
Aryamanz29/DSA-CP
/gfg/Recursion/subsequence.py
695
4.0625
4
# Print subsequences of given string using recursion.eg. if string is "abc" then output should be- " " "a" "b" "c" "ab" "bc" "ca" "abc", # Note:Combinations of subsequence 2^N( here N is number of char in a given string) def sub(s, curr='', index=0): if index == len(s): print(curr, end=" ") return sub(s,curr, in...
564287a67c3733c80cddc4a95d5c8fcbdffe91bd
Aryamanz29/DSA-CP
/gfg/trees/duplicate_subtree_in_bt.py
825
3.9375
4
from base import Node, buildTree # https://practice.geeksforgeeks.org/problems/duplicate-subtree-in-binary-tree/1 def preorder(root, subtree={}): s = "" if root is None: s += "$" return s s += str(root.data) s += preorder(root.left, subtree) s += preorder(root.right, subtree) ...
64a1c5ef7f7b9817c5a24022f743f41e5eb3c27d
Aryamanz29/DSA-CP
/gfg/trees/height_of_tree.py
384
3.875
4
from base import Node, buildTree def height(root): if root is None: return 0 left_height = height(root.left) right_height = height(root.right) return max(left_height, right_height)+1 if __name__ == "__main__": t = int(input()) for _ in range(t): s = input() root = bui...