blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
69905e825f7034ef8afd488fa900db50098408ea
gapc87/EjerciciosPython
/fundamentos/operadores_aritmeticos.py
263
3.9375
4
a = 3 b = 2 suma = a + b print('suma', suma) resta = a - b print('resta', resta) multi = a * b print('multiplicacion', multi) division = a/b print('division', division) modulo = a % b print('residuo', modulo) exponente = a ** b print('exponente', exponente)
0d843c4ef440e3a9a3b816c41e8eea7788492421
Redhead80/files.sorted
/main.py
697
3.59375
4
def sorted_union_files(files: list, result_path: str) -> None: temp_dict = {sum(1 for _ in open(one_file, encoding="UTF-8")): one_file for one_file in files} with open(result_path, "w") as file_write: file_write.write("") with open(result_path, "a") as file_write: for key in sorted(temp_dict...
5cb61169d5312ae1d2db4e8b9424950df5e6a44f
soonler/Python000-class01
/Week_02/G20200389010209/week02_0209_ex.py
2,061
4.125
4
#父类:1、变量初始化;2、打印支付信息的方法 class Customer(object): def __init__(self, name,total_goods, total_money): self.name = name self.total_money = total_money self.total_goods = total_goods def print_tips(self,name,total_money): print(f"亲爱的顾客{self.name},您需要支付{self.total_money:.2f}元") #子类普通...
b6b893d3dc6a4364eb38b1a24e68759d672331e4
chapsan2001/ITMO.Labs
/PythonLabs/Lab3/lab_03_05.py
729
3.921875
4
''' Операции cо словарями ''' d2 = {'a':1, 'b':2, 'c':3, 'bag':4} d5 = d2.copy() # создание копии словаря print("Dict d5 copying d2 = ", d5) # получение значения по ключу print("Get dict value by key d5['bag']: ", d5["bag"]) print("Get dict value by key d5.get('bag'): ",d5.get('bag')) print("Get dict keys d5....
e3a94c1d185811bc82b8397acec050aae3cb8190
pyxin/python_test001
/part_one/py001.py
1,834
3.78125
4
# 一摞有序的纸牌 __getitem__ 和 __len___ # import sys # sys.path.extend(['/Users/pan/Codes-01/PY/python_test001']) import collections import doctest Card = collections.namedtuple('Card', ['rank', 'suit']) """ >>> beer_card = Card(7,'ssss') >>> beer_card Card(rank=7, suit='ssss') """ class FrenchDeck: """ 定义一个纸牌类 ...
90dbb8b39f5875d3fd2d9f7340bb0071337280d9
cmhuang0328/hackerrank-python
/basic-data-types/4-find-the-second-largest-number.py
537
4.0625
4
#! /usr/bin/env python3 ''' You are given n numbers. Store them in a list and find the second largest number. Input Format The first line contains n. The second line contains an array A[] of n integers each separated by a space. Constraints 2 <= n <= 10 -100 <= A[i] <= 100 Output Format Print the value of the secon...
aa51818ff92b4b1a75986c08c647ffc5b2cfb1ad
chris-sooseok/food_prediction_machine
/2_IDA.PY
7,926
3.875
4
import pandas as pd import csv import numpy as np import string import math import re # count max number of items to fill headers def count_max(filename): f = open(filename, 'r') lines = csv.reader(f) max = 0 for line in lines: if (max < len(line)): max = len(line) return max #...
e17ed949e1ddb2d9097495b233191d839981dd9c
curiousTauseef/Algorithms_and_solutions
/Codility/6_NumberOfDistinctIntersections.py
4,161
3.625
4
''' We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J]. We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at...
f61c59ad1db01a892a9f5317a8c28ca66e55b09c
strawwj/pythontest
/pythoncase/udpserver_test.py
336
3.578125
4
#udp没有客户端服务端之分 import socket MYHOST = '127.0.0.1' OTHERHOST = '127.0.0.1' PORT = 60008 with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as s: s.bind((MYHOST,PORT)) s.sendto(b'hello i am wj',(OTHERHOST,60008)) data,addr = s.recvfrom(1024) print('data:',data) print('addr:',addr) s.close()
ca5ba9239b148fd7c5cee98d963d0490fe8db8ff
saurav1066/python-assignment
/8.py
343
4.21875
4
""" Write a Python program to remove the nth index character from a nonempty string. """ inp = input("Enter a string:") remove_index = int(input("Enter the index you want to remove:")) if len(inp) < remove_index: print("Sorry the string is shorter than you think.. ") else: inp = inp[0:remove_index]+inp[remov...
8d92533a7f31c1c88a1b3b0f7b9690503f2a6d9a
anna-s-dotcom/python01-python08
/Tag04/dozent_queue.py
691
3.859375
4
import queue print('start fifo') fifoq = queue.Queue() fifoq.put(5) fifoq.put('A') fifoq.put(True) fifoq.put([1, 5]) while not fifoq.empty(): print(fifoq.get()) print() print('end fifo') print() print('start lifo') lifoq = queue.LifoQueue() lifoq.put(5) lifoq.put('A') lifoq.put(True)...
687699ceb423770daf2d49f0522fa3bd836d4ede
Rvh88/category-production-computational-modelling-1
/framework/evaluation/tabulation.py
1,627
3.8125
4
""" =========================== Tabulation and working with pandas.DataFrames. =========================== Dr. Cai Wingfield --------------------------- Embodied Cognition Lab Department of Psychology University of Lancaster c.wingfield@lancaster.ac.uk caiwingfield.net --------------------------- 2019 ----------------...
5dc289b609bba64c11f23ee23e2afda4e8f92196
ccojocea/PythonVSC
/CollectionsModule/namedtuple.py
236
3.734375
4
from collections import namedtuple Dog = namedtuple('Dog', 'age breed name') sam = Dog(age=2, breed='Lab', name='Sammy') print(sam) Cat = namedtuple('Cat', 'fur claws name') c = Cat(fur='Fuzzy', claws=False, name='Kitty') print(c[1])
d4850ae7c9bd3ac512a5fbfffc6bed3b428fbd01
spartanick666/practice_python
/exercise11.py
345
4.09375
4
def get_number(): return int(input("Please enter a number: ")) #combine functions def not_prime(): if number % i == 0: print("This is not prime number") def is_prime(): if number % i != 0: print("This is a prime number") number = get_number() for i in range(2, number + 1): not_prime(...
3cfac8470683e13a2e149feb58afd36ec8b7f423
eduardofmarcos/Python
/11 - aluguel_de_carros.py
210
3.71875
4
km = float(input('Digite a kmmetragem rodada: ')) dias = int(input('Digite a quantidade de dias: ')) total = (km * 0.15) + (dias * 60) print('O total a pagar pelo aluguel será de R$: {:.2f}'.format(total))
ce8909fd77eef131d4fcd8ace05fe1c8eeeb2c6b
tramvn1996/datastructure
/strings/mnemonics_phone.py
849
3.953125
4
#generate a corresponding characters sequence #based on a string of digits MAPPING = ('0','1','ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ') def mnemonics_phone(phone_number): def phone_mnemonics_helper(digit): if digit == len(phone_number): mnemonics.append(''.join(partial_mnemonic)) ...
8c6fa26db94b73d1d58d6efd52fd9014278d7ae6
devjayantmalik/PythonTutorials
/src/tutorial_5.py
7,084
4.59375
5
# ================================================== # ================================================== # Functions # ================================================== # ================================================== # =============================================== # Write a function to add two ...
11541508eda910012ca16ac3e2f6fcf1c0c16074
sitnet1102/project2_bank_system
/dataType.py
9,782
3.71875
4
''' 데이터 타입과 관련된 메소드들은 기획서를 기반으로 합니다. ''' class dataTypeBase : ''' 데이터 타입 추상 클래스입니다. ''' @classmethod def dataConfirm(cls, data) : #데이터 문법 확인 매소드 pass @classmethod def dataToBasicType(cls, data) : #기본형 변환 메소드 #if self.dataConfirm(data) : return data.strip...
73966187535e1aa60fbd701724e652053d15d2a8
ZhangYet/vanguard
/myrtle/date0313/peek_index_in_a_mountain_array.py
760
3.703125
4
# https://leetcode.com/problems/peak-index-in-a-mountain-array/ from typing import List def same_direction(nums: List[int], up: bool) -> bool: if len(nums) == 1: return True if up: return all([nums[i] < nums[i+1] for i in range(len(nums) - 1)]) return all([nums[i] > nums[i+1] for i in ra...
3d98d33b8f2a1a637b2e02385d478f2540f2433f
luotong1995/ML_python
/Perceptron/Perceptron.py
2,622
3.578125
4
import numpy as np from matplotlib import pyplot as plt class Perceptron(object): def __init__(self, input_num, activator): ''' :param input_num: 感知器数据的输入维度 :param activator: 激活函数 ''' self.input_num = input_num self.activator = activator # 权重初始化 sel...
a29adc30c35a4103613e00b057ae862d370fbc52
theshdb/Brute-Force-Linear-Regression
/main.py
1,944
3.765625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt class Linear_Regression: def __init__(self, file_path): self.train_data = pd.read_csv(file_path) self.train_x = self.train_data.pop("house age") self.train_y = self.train_data.pop("house price of un...
40375ea1239b01730a42c908636248db4c48ace9
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/Fun_Projects/Interpreter/draw_animation.py
685
4.0625
4
import turtle screen = turtle.Screen() # create a new screen screen.setup(500,500) # 500 x 500 window don = turtle.Turtle() # create a new [ninja] turtle don.speed(0) # make it move faster def draw_square() : # a function that draws one square for side in range(4) : ...
242eb9402addb6e8bd7aa887dd497757e1c76e1a
midah18/Pyramid
/draw.py
4,335
4.25
4
def get_shape(): """ certain names of shapes are valid if user input is the right shape break from this function if user input is the wrong shape, keep asking till the correct one is given """ valid = ['square', 'triangle', 'pyramid', 'proper square', 'rectangle', "paralellogram"] while True...
2b2cde4e5e7c5d20b45d98c5710b69bd9064c9dd
jcfischer/suncontrol
/python/objects.py
7,947
3.59375
4
"""Classes to define world objects""" import random import math_utils import color_utils class Object: pos = (0, 0, 0) vec = (0, 0, 0) color = (0, 0, 0) size = 0.0 max_size = 0.1 alive = True def __init__(self, pos=(0, 0, 0), vec=(0, 0, 0), color=(0, 0, 0), size=0.1, ttl=10): sel...
2129040f84883d0879b8a9eebe595faf67cf6fdd
oman36/self-learning
/tutorial/4.More-Control-Flow-Tools/4.7.More-on-Defining-Functions/4.7.0.Function-properies.py
779
3.640625
4
def parent_func(): variable = 'Value' other_var = 'Val2' if other_var == 'Val1': variable = 'Other value' def nested_func(a, b, third_val=2): return variable == a or third_val == b return nested_func func = parent_func() print(repr(func.__name__)) # 'nested_func' print(repr(fun...
004b87e4355a65e91d266c983198d238ca5de714
UltraPythonCoder/PythonStuff
/FibbonacciSequence.py
205
3.875
4
i = int(input("How Many Numbers? ")) a = 1 b = 1 counter = 2 print("1") print("1") while counter < i: if counter != 2: a = c c = a + b print(c) b = a counter += 1
21a4cbab427b832ddef6ab324a9bdcd624c4da3e
Suhailhassanbhat/algorithm
/linear_regression.py
1,471
3.921875
4
import pandas as pd import numpy as no import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import statsmodels.api as sm ca_api_data = pd.read_csv('apib12tx.csv') print(ca_api_data.columns) #make a histogram grade12 = plt.figure(1) ca_api_data['API12B'].hist() # histogram of meals, whic...
74dac41e1a4a00b697cd38bdde409b56cdc220c7
kaijie0102/H2-computing
/Assignments/Assignment 6.py
2,417
4.09375
4
#Qn 1 ''' class Pet: def __init__(self,name,animal_type,age): self.__name = name self.__animal_type = animal_type self.__age = age def set_name(self,name): self.__name = name def set_animal_type(self,animal_type): self.__animal_type = animal_type def set_age(se...
2e3c50f04fbe1fb7d3c8cab47d73e1d38db44dad
caw024/Myline
/draw.py
1,213
4.0625
4
from display import * #eq of line is Ax+By+C=0 def draw_line( x0, y0, x1, y1, screen, color): A = y1 - y0 #change in y B = x0 - x1 #negative change in x x = x0 y = y0 if B==0: while y <= y1: plot(screen,color,x,y) y+=1 else: m = -1.0*A/B #slope #octant 1 if ((1 > ...
ff53374b1d460fbc87e07b2ca7134073c61c6592
helllo-ai/Project
/class1.py
595
3.65625
4
import csv with open("project.csv",newline="")as f: reader=csv.reader(f) file_data=list(reader) file_data.pop(0) total_marks=0 total_entries=len(file_data) for marks in file_data: total_marks+=float(marks[1]) mean=total_marks/total_entries print("Mean (Average) is -> "+str(mean)) import pandas as pd impo...
57943939f85a6a5537a75fb898afe1a75deb781f
decross1/hackerrank_30_days_of_code
/Day 13 of 30 Days.py
734
4.15625
4
## Hackerrank: Day 13 of 30 Days of Code from abc import ABCMeta, abstractmethod class Book: __metaclass__ = ABCMeta def __init__(self, title, author): self.title = title self.author = author @abstractmethod def display(): pass # Write MyBook class ...
06a2f274279e4245a663f434d4b75209bb7743c1
Darshini-V-M/python-programming
/beginner level 1/print in words.py
314
3.828125
4
x=int(raw_input()) if(x==1): print('One') elif(x==2): print('Two') elif(x==3): print('Three') elif(x==4): print('Four') elif(x==5): print('Five') elif(x==6): print('Six') elif(x==7): print('Seven') elif(x==8): print('Eight') elif(x==9): print('Nine') elif(x==10): print('Ten') else: print('invalid')
31c502d3bca2cd57d2bd0bb56c6ed3dd26ee3470
Anirudh-Muthukumar/Python-Code
/Print all Root to Leaf paths of a Binary Tree.py
1,055
3.78125
4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def rootToLeafPath(root): res = [] q = [(root, [root.val])] while q: node, path = q.pop(0) if not node.left and not node.right: # leaf node res += path, ...
e56d6b12b654bb05a417e63b5cb4db8e66346b93
Empirio991/testing
/step3.py
2,528
3.828125
4
"""Fizz Buzz game with a twist to it.""" import argparse import json class FizzBuzzGame: """FizzBuzz game class.""" def __init__(self, rules): """init method for the class.""" self.rulesDivisible = rules["divisible"] self.rulesEndsWith = rules["ends"] def buzzer(self, n: int) -> ...
cc308c8ceb9f299814d4fd0d1ef8d97007bba75f
DebashishSarkarDurjoy/SDES
/sdes.py
8,517
3.859375
4
# S-DES functions in the form of list IP = [2, 6, 3, 1, 4, 8, 5 , 7] IPinverse = [4, 1, 3, 5, 7, 2, 8, 6] P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] P8 = [6, 3, 7, 4, 8, 5, 10, 9] E_P = [4, 1, 2, 3, 2, 3, 4, 1] P4 = [2, 4, 3, 1] # the S0 table as 2d list S0 = [ [1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3,...
a1f1e528df2218b1551941e39254d5d0af99e24c
Dimple16/Winsound
/sound.py
1,748
3.625
4
# -*- coding: utf-8 -*- """ Created on Thu May 10 06:31:27 2018 @author: DEV """ import winsound #The winsound module provides access to the basic sound-playing machinery provided by Windows platforms. It includes functions and several constants print("Binary Representation of sound") print("Enter the...
5152133f8e590f6552471a7f5796d7bdc697d8cf
ukarthikvarma/DataAnalysisProjects
/sea-level-predictor/sea_level_predictor.py
1,591
3.515625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import linregress def draw_plot(): # Read data from file df = pd.read_csv('epa-sea-level.csv') new_year = [] for i in range(2014,2050): new_year.append(i) i = i+1 empty_array = np.empty((36,4)) e...
c91d7a0cb0631bd0fb7da78c41adf651719739d9
chlomcneill/advent-of-code-2018
/Python/Day 2/Day2Part1.py
852
3.78125
4
import string def letter_repeats_exactly_2_times(n): alphabet = list(string.ascii_lowercase) repeats = [] for letter in alphabet: if n.count(letter) == 2: repeats.append(letter) return repeats def letter_repeats_exactly_3_times(n): alphabet = list(string.ascii_lowercase...
abee39af450089a4901a1237b1ba9fb0b746bb9e
joshuap233/algorithms
/tree/binary_search_tree.py
3,138
4.1875
4
from typing import Optional """ 最麻烦的删除操作: 需要删除的节点为 A 1. A 为树叶,直接删除 2. A 只有一个儿子, 儿子代替父节点即可 3. A 有两个儿子, 找到 A 右子树中最小的节点删除, 然后代替 A 测试(偷懒用 leetcode 测试): 查找: leetcode T700 插入: leetcode T701 删除: leetcode T450 验证: leetocde T98 """ class Node: # 可以添加一个 key 字段, 这里仅使用 val 来查找 def __in...
22a003978a9e99bf292e67b0835e901aeea02578
GeraJuarez/code-analysis-python
/lab2/test_myPowerList.py
2,527
4.09375
4
import unittest from MyPowerList import MyPowerList as MPL class TestingMyPowerList(unittest.TestCase): """MyPowerList unit tests. """ def test_add_item_count(self): """Test number of additions corresponds to the list size. """ mpl = MPL() mpl.add_item(1) expecte...
c24446d278e7fbe80357a66660a188ae2a5af11a
daniel-bray/skillshare-py-chattybot
/Problems/The first digit of a two-digit number/task.py
70
3.609375
4
# put your python code here num = int(input("")) print(int(num / 10))
8f1f1b6c59c52e2b38478dad546a6f2393d10548
greenfox-velox/danielliptak
/week4/day3/9.py
603
4.21875
4
# create a 300x300 canvas. # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. from tkinter import * root = Tk() width = 300 height = 300 canvas = Canvas(root, width=width, height=height) canvas...
bf1f22643f12cfeeb3e389f7c96a104b5d5aff89
nunes-moyses/Projetos-Python
/Projetos Python/pythonexercicios/des010.py
166
3.640625
4
p = float(input('Qual o preço do produto?')) pd = p - (p * 0.05) print('O produto que custava {}, na promoção com desconto de 5% vai custar {:.2f}'.format(p, pd))
e17f56117b544d5bba1e98c326f5587b2a283905
Jasmine-2002/Python
/xxx.py
348
3.71875
4
import re def is_palindrome_1(tmp_str): for i in range(len(tmp_str)): if tmp_str[i] != tmp_str[-(i+1)]: return False return True x=input().lower() r='[’!"#$%&\'()*+,-./:;<=>?@[ \\]^_`{|}~\n。!,]+' a=re.sub(r,'',x) b=list(a.replace(" ",'')) n=is_palindrome_1(b) if n==True: print('yes') e...
d16a53c256191673da688a32f34bc12cf7c2be40
Muhodari/python-complete-crash-Course
/E.word_Replacement_exercise/wordReplacement.py
236
4.21875
4
sentence = input('Enter the sentence:') wordToReplace = input('Enter word to replace: ') replaceWordWith = input("Enter the word to replace with: ") finalSentence = sentence.replace(wordToReplace, replaceWordWith) print(finalSentence)
1c0df7b32b402e67a7df801a9279c05f9a67daea
vineel2014/Pythonfiles
/python_exercises/20project_ideas/emailsender.py
1,055
3.859375
4
import smtplib from tkinter import * import tkinter.messagebox as mbox def sent(): to =e1.get() gmail_user = 'Enter your gmail username' gmail_pwd = 'Enter your gmail password' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(g...
e567fb8130105586704047a59821f5366110b3dc
xeladock/Python_wb
/Black Box(Smoke)/scratches/3.1.1.py
211
3.84375
4
def f(x): if x<=-2: print(1-((x+2)**2)) return '' elif -2<x<=2: print(-x/2) return '' elif 2<x: print(1+((x-2)**2)) return'' x=int(input()) print(f(x))
eb4a8eb6f061a5bab38d0ece4aa000ae1ce08b36
sheelabhadra/LeetCode-Python
/324_Wiggle_Sort_II.py
755
4.09375
4
#Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... #Example: #(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. #(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. ## SOLUTION: Sort the array in descending order. Di...
553fdf08c6102c6c016e8464f6ebce3e26a2b96a
robj137/advent_of_code
/2016/day01.py
1,448
3.796875
4
import datetime as dt from collections import defaultdict class Traveler: def __init__(self): self.position = 0 + 0j self.direction = 0 + 1j self.visited = {} self.visited_twice = [] def get_position(self): return self.position def get_distance(self, val): return abs(int(val.real)) + abs...
72dc14e0441e6888d728eb9822c5d94becd03f03
Austin-Long/CS5
/hw1pr2.py
1,692
3.828125
4
# CS5 Gold, Lab1 part 2 # Filename: hw1pr2.py # Name: # Problem description: First few functions! def dbl(x): """Result: dbl returns twice its argument Argument x: a number (int or float) Spam is great, and dbl("spam") is better! """ return 2*x def tpl(x): """Return value: tpl returns ...
e55a9dac4da160dc2456cd097eb6923aded8e9a8
jjasonkal/Codewars
/kata/kata_solved/calculator/CalculatorTests.py
1,557
3.640625
4
import unittest from kata_solved.calculator.Calculator import Calculator class MyTestCase(unittest.TestCase): def test_add(self): test_data = [ ('1.1 + 2.2 + 3.3', 6.6), ('2 + 3', 5), ('2 + 2 + 2 + 2', 8)] for test_input, test_output in test_data: se...
2b87c24be4f7384458af7bab356fcc4f34112dfa
Daniyal963/LAB-05
/Program 1.py
273
3.59375
4
print("Daniyal Ali - 18B-096-CS(A)") print("Program 1") count = 0 f = eval(input("Please enter your final loop where u want to end the loop")) while (count<7): print("The value of Count",count) count = count+1 print("I am using while loop", count, "time")
b2aa907950c2fe53e676d6f6b71d9099f9656fe0
BradenRowlands/CP1404Practicals
/Prac04/Lottery.py
269
3.734375
4
import random thelist = [] amountOfPicks = input("Please enter the amount of picks you would like") for i in range (int(amountOfPicks)): for number in range(6): number = random.randint(1,45) thelist.append(number) print(thelist) thelist = []
e2402b603f4e217ad83e6a3ecb82af98e8679f86
rao003/StartProgramming
/PYTHON/einstieg_in_python/Beispiele/spiel_oop.py
1,524
3.671875
4
import random # Klasse "Spiel" class Spiel: def __init__(self): # Start des Spiels random.seed() self.richtig = 0 # Anzahl bestimmen self.anzahl = -1 while self.anzahl<0 or self.anzahl>10: try: print("Wieviele Aufgaben (1 bis 10):") ...
c4c46ee7d884cf30ddbcd1d71e4d6342c58fcf6b
Reebs296/Okanagan-Engineering-Competition-2021-Team-EngiCoders
/main.py
8,772
3.859375
4
import random #import gui library import tkinter as tk #create tile class that is either a stone or a bomb class Tile: #initialize the tile def __init__(self, x, y, bomb): self.x = x self.y = y self.bomb = bomb self.bombnum = 0 self.revealed = False self.flagged...
2e60e1dd6c2b93324c5d0fc7da2d6d4c0e76af1c
steffenschumacher/TimeString
/TimeString/__init__.py
3,494
3.703125
4
import re import datetime class TimeString(object): string_time_re = re.compile(r'(((?P<years>\d+)y)|((?P<weeks>\d+)w)|((?P<days>\d+)d)|((?P<hours>\d+)h)){1,2}') @staticmethod def convert(value): """ Converts either timestring (1y2w etc) to timedelta, or timedelta(or hours as int) to times...
05bd09f9b249289d16a6ae401638d791ae851498
mohan277/backend_repo
/clean_code/clean_code_submissions/clean_code_assignment_001/truck.py
1,600
3.6875
4
from car import Car class Truck(Car): HORN_SOUND = 'Honk Honk' def __init__( self, color=None, max_speed=None, acceleration=None, tyre_friction=None, max_cargo_weight=None): super().__init__(color, max_speed, acceleration, tyre_friction) self._max_cargo_weight = max_cargo_...
518e9e256174b4e6ec2f3637364c3977562b2b20
anas-yousef/Connect-Four
/game.py
7,767
4.21875
4
class Game: PLAYER_ONE = 0 PLAYER_TWO = 1 DRAW = 2 ROWS = 6 COLUMNS = 7 CHECK_FACTOR = 3 ''' I assigned it to be equal to 3 because in the functions where I check if there is a winner, I use the number 3 constantly ''' def __init__(self): ''' Initializes the ...
256a6aa582c669a79b39ccdcb8369eeb6ce7c03e
sonichuang/My-py-file
/保存属性值文件.py
1,384
3.6875
4
import time #通过小甲鱼的代码使用time.ctime()方法显示时间更方便 import pickle #储存二进制文件 import os #使用remove方法删除文件 class Mydes: def __init__(self, value = None, name = None): self.value = value self.name = name self.path = 'C:\\Users\\vulcanten\\desktop\\%s.txt' % self.name #不同的属性保存在不同的文件里面 def __get__(self,...
de3310357d59a9c4fcfaf0604424a02f1fb60530
rlipscomb99/LIS4930
/unittest.py
781
3.78125
4
import itertools import unittest def iteration(name): count = 0 lista = [] for i in itertools.cycle(name): if count > 10: break else: lista.append(i) count += 1 return lista class testIteration(unittest.TestCase): def testIterationsuccess(self): actual = iteration(name = "Pot...
e20242a5341b231666de17d5e13979fa415dee65
ComiteMexicanoDeInformatica/OMI-Archive
/2019/OMIPS-2019-pistas/tests/test-validator.py
1,741
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import collections import libkarel from kareltest import * class Test(KarelTest): def test(self): world = self.world #Karel inicia en la casilla (1,1) viendo al norte. self.assertEqual(1, world.y) self.assertEqual(1,...
c08a47b1f3684bfcdb09fbc1eb02131605a137b0
flaviogf/courses
/geral/livro_data_science_do_zero/chapter5/example01.py
869
3.625
4
from collections import Counter import matplotlib.pyplot as plt num_friends = [100, 49, 41, 40, 25, 100, 49] friends_count = Counter(num_friends) xs = range(101) ys = [friends_count[x] for x in xs] plt.bar(xs, ys) plt.axis([0, 101, 0, 25]) plt.title('Histograma de Contagem de Familiares') plt.xlabel('# de fami...
1335af13201a15c3a8c3f9ac35140abf6b8eb46a
garibaldiviolin/knapsack-solutions
/naive_recursion.py
838
4
4
""" A naive recursive implementation of 0-1 Knapsack Problem Returns the maximum value that can be put in a knapsack of capacity W Reference: https://www.geeksforgeeks.org/python-program-for-dynamic-programming-set-10-0-1-knapsack-problem/ """ def naive_recursion_knapsack(W, wt, val, n): # Base Case if n =...
834c27e43d5ec459dd2735eabf2773e497d91223
rafaelgustavofurlan/basicprogramming
/Programas em Python/04 - Vetores/Script5.py
600
3.828125
4
# Faça um programa que carregue um vetor com dez numeros inteiros. # Calcule e mostre os numeros superiores a 50 e suas respectivas # posicoes. Mostrar mensagem se não existir nenhum numero nesta # condição. vetor = [] tem_maior_50 = False #entradas for n in range(0, 10): num = int(input("Informe {0} valor para...
6f4e4e07aee1258e2a8b1c2cbfba4c5a51951896
miaopei/MachineLearning
/LeetCode/github_leetcode/Python/reverse-nodes-in-k-group.py
1,888
4
4
# Time: O(n) # Space: O(1) # # Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. # # If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. # # You may not alter the values in the nodes, only nodes itself may be changed. # ...
5d5c2db91704e472ba501bd13cb65338e848c4f1
PuffyShoggoth/Competitive
/CCC/CCC '09 J2 - Old Fishin' Hole.py
412
3.640625
4
trout=int(input()) pike=int(input()) pickerel=int(input()) lake=int(input()) combos=0 for a in range(0, lake+1): for b in range(0, lake+1): for c in range(0, lake+1): if a+b+c==0: continue if a*trout+b*pike+c*pickerel<=lake: print(a,'Brown Trout,', b, 'Northern Pike,', c, 'Ye...
f7141e5e76d2cfc5ff5d406bf03134155c1937a2
tomboy-64/pje
/py/prob0196.py
1,974
3.53125
4
import math import gmpy2 LINE_NO = [ 8, 9, 10000, 5678027, 7208785] primes = [ 2 ] def isPrime(x): if x > primes[ len(primes)-1 ]: nextPrimes(x) if x in primes: return True else: return False def nextPrimes(x): global primes outerDone = False # sys.stdout.write(".") # sys.stdout.flush() whil...
8e5685361270f69df82e32753ca7a53c8561b3cd
yenchihliao/ankiSupport
/OperationDecorator.py
558
3.5625
4
from Operation import Operation class Loop2X(Operation): def __init__(self, op): self.operation = op self.helpMsg = "Looping, X to exit, and ? to get help\n" + self.operation.helpMsg self.prefix = "decorator" def do(self): while(True): arg = input(self.operation.pref...
50587ced395a200f03f33407da4ac5c218df10ec
hudefeng719/uband-python-s1
/homeworks/A13191/checkin10/day16-homework2.py
393
3.59375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import time import calendar print time.localtime() print time.time() localtime = time.localtime(time.time()) print "本地时间为:", localtime localtime = time.asctime( time.localtime(time.time()) ) print "本地时间为:", localtime print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(...
ecc9bd5abded97db30d2b69b35acf272d3695be4
mabatko/python-chess
/chessboard.py
9,359
3.578125
4
class Chessboard: board = [[] * 8 for i in range(8)] pieces = [] turns = 0 lastMove = {"pieceName": '', "type": '', "color": '', "origX": -1, "origY": -1, "futureX": -1, "futureY": -1} x_axis = [' 0 ',' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 '] def __init__(sel...
196fd2cb6ddd86992c51a92fd2fc945d15e3df07
naveen673/pythonprogramming
/cit_CyberSecurity/assessments/assessment_3/task_2.py
731
4.40625
4
''' Task 2 # Write a python program to find the factors of a given number. # The factors of a number are those, which are divisible by the number itself and 1. # For example, the factors of 15 are 1, 3, 5. # Please follow the below steps to complete this task: # Define a function which will take the number as parameter...
4bb2ebe022c3a89549f5b856b0b508e40f754dc3
409085596/TallerHC
/Clases/Programas/Tarea07/Ejercicio01S.py
569
3.65625
4
# -*- coding: utf-8 -*- from Ejercicio01 import determinaIgualdad interruptor = True while interruptor == True: a, b= raw_input("\nDame dos listas para determinar si son iguales.\nTienen que estar separadas por un espacio, pero sin dejar espacios entre sus elementos:\n").split() a=a.replace("[",""); a=a.replac...
be8d555f37b45cea50577e8614689e3fa71173d5
Ritesh007/tutorial
/python/class_syntax.py
296
3.90625
4
#!/usr/bin/python ######################### # python script 17 ######################## #defining a class class Class_name(): def function1(self): name = lambda a: a+5 print(name(10)) #creating a object class_object = Class_name() #calling a def in class class_object.function1()
e2ff29bda99bf4d72e43268dc3b3019a94faf962
Marcfeitosa/listadeexercicios
/ex034.py
565
3.9375
4
print("""Desafio 34 Faça um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$ 1.200,00 calcule um aumento de 10%. Para salários inferiores ou iguais, o aumento é de 15%""") sal = float(input('Qual é o seu salário? ')) if sal > 1200.00: print('Par...
ba69c6856d2bdbcec5d4189fe8c363f025a9e3dd
micaswyers/Advent
/Advent2015/15/day15.py
3,708
3.53125
4
# Part 1 from collections import defaultdict def parse_input(file_name): """Returns a dict mapping properties to ingredients & stats ex) { 'capacity': {'sprinkles': 5, 'peanutbutter': -1, 'frosting': 0, 'sugar': -1}, } """ with open(file_name) as f: properties = defaultdic...
0dc8aef8626037514ae6b195a1f9b89fbd1105b7
dean-joshua/CSE-210-02pp
/Hilo/game/dealer.py
1,643
3.984375
4
import random class Dealer: def __init__(self): '''A constructor method for the Dealer class.''' self.current_card = 0 self.next_card = 0 self.h_or_l = "" def draw_card(self): '''A draw card method that pulls a new card''' list_of_cards = [1,2,3,4,5,6,7,8,9,10,...
4b26bdc9c7cb8cc35f6656dcc421ddd51fae6930
KingOfRaccoon/2
/12.py
205
4.125
4
string = '3' * 95 while '333' in string or '999' in string: if '999' in string: string = string.replace('999', '3', 1) else: string = string.replace('333', '9', 1) print(string)
779908de67851ba3e9a52f80acd0053a335a6f8c
xuedong/hacker-rank
/Interview Preparation Kits/Interview Preparation Kit/Dynamic Programming/Max Array Sum/max_array_sum.py
774
3.53125
4
#!/bin/python3 import math import os import random import re import sys # Complete the maxSubsetSum function below. def maxSubsetSum(arr): n = len(arr) if n == 1: return arr[0] elif n == 2: return max(arr[0], arr[1]) else: max_sum1 = max(arr[0], arr[1]) max_sum2 = arr[0...
87c3cb7cbdb7042826cb5e75712f27b31710bb24
QAlexBall/Python_Module
/cookbook/meta_programing/exercise_1.py
1,141
3.5625
4
""" exercise 1 """ import time import logging from functools import wraps def timethis(func): """ Decorator that reports the execution time. """ @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(fun...
e2d99b7f412e5ce63d6cfe8c78ca110100358cad
brianchiang-tw/leetcode
/No_0653_Two Sum IV - Input is a BST/by_preorder_and_set.py
2,145
3.828125
4
''' Description: Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True Example 2: Input: 5 / \ 3 6 / \ \ 2 4 7...
a0714e8bda11809c931d81867ef9e8f1f172d58b
Mahantesh1729/python
/Activity_11.py
359
3.875
4
def main(): print("Enter the first number") a = input_number() print("Enter the second number") b = input_number() summation = add(a, b) display(a, b, summation) def input_number(): return int(input()) def add(a, b): return a + b def display(a, b, summation): print(...
ee179a8a2c6b18a01ed1c7b68517ddb16725e3be
zhaochuanshen/leetcode
/Remove_Duplicates_from_Sorted_List.py
629
3.75
4
''' Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ...
e7c9ff96bfd41f28f35486d8635a44bbcdb47126
benilak/Everything
/CS241_Miscellaneous/scratch_2.py
2,743
4.28125
4
'''class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self._hours = hours self._minutes = minutes self._seconds = seconds def get_hours(self): return self._hours def set_hours(self, hours): if hours < 0: self._hours = 0 elif hou...
82b224451dba360530b8859a82896acba87cffde
RSanchez98/python
/UMDC/01/05.py
257
3.8125
4
#Escribir un programa que imprima todos los números pares entre dos números que #se le pidan al usuario primero = int(input("Primer nuermo ")) ultimo = int(input("Ultimo numero ")) primero += primero % 2 for i in range(primero, ultimo+1, 2): print(i)
1aaf8dc33fe75a183f1c0c6956c2705c2ea55342
luckyanand235/Coursera_Algorithmic_Toolbox
/week2/stress_test/fib_last_digit_st.py
672
4.0625
4
# Uses python3 import numpy as np import math def fibonacci(n): phi1 = (1 + math.sqrt(5)) / 2 #phi2 = (1 - math.sqrt(5)) / 2 return round(pow(phi1, n) / math.sqrt(5)) % 10 def get_fibonacci_last_digit_optimized(n): if n <= 1: return n previous = 0 current = 1 temp = 0 for _ in range(1, n): temp = cu...
44e8477cc08cefc16db0f67823974cb13da82c6a
deepgupta11101/vsa2018
/proj02_02.py
1,086
4.5625
5
# Name: # Date: # proj02_02: Fibonaci Sequence """ Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13....
62658823a27f622e7af6b254fdcd37fa09cb7f3a
manuck/myAlgo
/baekjoon/1717_집합의 표현.py
511
3.53125
4
import sys sys.stdin = open('1717_input.txt') input = sys.stdin.readline def find(num): if p[num] != num: p[num] = find(p[num]) return p[num] def union(a, b): A = find(a) B = find(b) if A != B: p[B] = A n, m = map(int, input().split()) p = [i for i in range(n + 1)] for _ in ran...
9c73b002b1f9da826887bedcfe2e0e838b4c6c14
sudoheader/TAOD
/quadratic_equation_solver_app.py
1,230
4.34375
4
#!/usr/bin/env python3 import cmath print("Welcome to the Quadratic Equation Solver App.\n") print("A quadratic equation is of the form ax^2 + bx + c = 0") print("Your solutions can be real or complex numbers.") print("A complex number has two parts: a + bj") print("Where a is the real portion and bj is the imaginar...
a1a96efd4c12a837f3c12ade32434ed5e3af077c
mr-zhouzhouzhou/LeetCodePython
/剑指 offer/数组/二维数组中的查找.py
880
3.5625
4
""" 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数, 判断数组中是否含有该整数。 """ """ 思路: 从左下角开始遍历,往上走是变小,往右走是变大 """ class Solution: # array 二维列表 def Find(self, target, array): # write code here row = len(array) col = len(array[0]) m = row - 1 ...
f5999b13fd8ba2e6f943763b5df71ca7d67a618a
zhanghong7096/CCC-Solutions
/2011/Senior/S1.py
540
3.59375
4
# CCC 2011 Senior 1: English or French # written by C. Robart # March 2011 # straight forward file handling with # simple character counting in strings file = open("s1.5.in", 'r') lines = file.readlines(100000) countS = 0 countT =0 for line in lines: for i in range(0, len(line)): if line[i] =...
57b370549e16d998e36020293c055d1c8667184f
yinkz1990/100daysofcode
/classifier.py
575
4.125
4
age = int(input('Enter your age =')) categories =['Child','Adolescence','Adult',' Senior Adult'] adult = ['Early','Middle','Late'] if age >= 0 and age <= 12: print('You are a',categories[0]) elif age >= 13 and age <=18: print('You are an' ,categories[1]) elif age >=19 and age <=59: print('You are an' ,cat...
34cad6a8b172637c2d2bcf43708fb78472843bd3
Sibyl233/LeetCode
/src/LC/480.py
1,218
3.71875
4
from typing import List import bisect """解法1:暴力法 - 时间复杂度:O(nklogk) - 空间复杂度:O(k) """ class Solution: def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: n = len(nums) res = [] for i in range(n-k+1): tmp = nums[i:i+k] tmp.sort() res.appen...
323d705f64528385fad9fd7a232c852efec01deb
Aprilya/bioinformatics
/RNA.py
435
3.75
4
# rosaling.info RNA task from bioinformatics stronghold # transcribing coding DNA into RNA from sequence given in a sequence.txt sequence = open('sequence.txt').read() sequence_length = len(sequence) RNA = "" for i in range(sequence_length): if sequence[i] == "T": RNA += "U" else: RNA += seque...
b241cb750b7ef59dd7fb2b4edcc5def54a03c1f9
MannazX/mannaz
/Python/Exercise 6 - 4.7.py
752
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 24 10:45:27 2018 @author: magge """ print("Add to inputs") i1 = eval(input("input 1: ")) i2 = eval(input("input 2: ")) t = i1 + i2 print("Sum = {0}, type {1}".format(t, type(t))) #With integers: #input 1: 23 #input 2: 34 #Sum = 57, type <class 'int'> #Now with list: #i...
672a2156b394907b55f43dd6acfdb89a67b0cc07
eosband/QuantRL
/envs.py
4,154
3.765625
4
from functions import * class TradingEnv(): """ Represents the trading environment used in our model. Handles low-level data scraping, retrieval, and calculation Adjustable parameters: get_reward(params): the reward function of a certain action get_state(params): the state that the mode...
26e1b8c7891e74fdc5abd386d619d5fe1f3033e2
Devinwon/master
/craw/RE-matchMAXMIN.py
195
3.796875
4
import re # 贪婪匹配(默认) 非贪婪匹配 # 增加?获得最小匹配 rel=re.match(r'PY.*N','PYANBNCNDN') rel2=re.match(r'PY.*?N','PYANBNCNDN') print(rel.group(0)) print(rel2.group(0))
25d47223b5c4eede49d710105b9c5e577638d977
dymfangxing/leetcodelintcode
/leetcode_py/jiuzhang_py_Ladders/9chapter_10_Dynamic_Programming/116_Jump_Game.py
1,183
3.59375
4
#coding=utf-8 #1)array中每个元素表示在这一步最大能跳多少步,而非一定要这么多步 #2)可以超过最后那个数 #3) reach means it reachs the last index """ reach是为了记录每个点最远能到达的位置,取当前值与i+A[i]的较大值, 这样,即使reach不再变大,但i+A[i]依然能帮助走完整个array """ class Solution: """ @param A: A list of integers @return: A boolean """ def canJump(self, A): # write...
9d7a98618a962ec84ab577573e518a74a10db3c3
arkanmgerges/cafm.identity
/src/domain_model/country/CityRepository.py
1,094
3.765625
4
""" @author: Mohammad S. moso<moso@develoop.run> """ from abc import ABC, abstractmethod from typing import List from src.domain_model.country.City import City class CityRepository(ABC): @abstractmethod def cities( self, resultFrom: int = 0, resultSize: int = 100, order: List[dict] = None ) -> di...
bc2229d2578f385b18d65df6ff2a8d58fd9a1277
Alejandro-Paredes/EECS337---NLP-Project-2
/conversions.py
3,722
3.5625
4
def convertTeaspoonToCup(teaspoon): cup = round(teaspoon*0.021, 2) return cup def convertCupToTeaspoon(cup): teaspoon = round(cup/0.021, 2) return teaspoon def convertTeaspoonToTablespoon(teaspoon): tablesoon = round(teaspoon/3, 2) return tablespoon def convertTablespoonToTeaspoon(tablespoon): teaspoon = rou...
fc96135c8b4f6c999956aca666e5a55ccf71e3a9
mroswell/python-snippets
/download-census-shapefiles.py
1,862
3.515625
4
''' Download selected census shapefiles, unzip them in directories named by state abbreviation fips.csv looks like this: statename,code,twoletter Alabama,1,AL ...