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 |
|---|---|---|---|---|---|---|
e2346faec29d56dd2a858d43d18a3fec95929162 | fagan2888/E4008-Computational-Discrete-Optimization | /Recitation 3/facility.py | 4,164 | 3.65625 | 4 | #!/usr/bin/python
# Copyright 2018, Gurobi Optimization, LLC
# Facility location: a company currently ships its product from 5 plants
# to 4 warehouses. It is considering closing some plants to reduce
# costs. What plant(s) should the company close, in order to minimize
# transportation and fixed costs?
#
# ... |
29586532ff3449eacbfde0593babbac9d2202509 | my-xh/DesignPattern | /03行为型模式/22模板模式/模板模式.py | 958 | 4 | 4 | from abc import ABCMeta, abstractmethod
class Template(metaclass=ABCMeta):
"""模板类"""
@abstractmethod
def step_one(self):
pass
@abstractmethod
def step_two(self):
pass
@abstractmethod
def step_three(self):
pass
def template_method(self):
"""模板方法"""
... |
06f8d33f6ee6ef677bb439dd1827f7c1b873ab06 | my-xh/DesignPattern | /03行为型模式/14命令模式/game_command.py | 5,044 | 3.84375 | 4 | import time
from abc import ABCMeta, abstractmethod
class GameRole:
"""游戏角色"""
# 每次移动的步距
STEP = 5
def __init__(self, name):
self.__name = name
self.__x = 0
self.__y = 0
self.__z = 0
def left_move(self):
self.__x -= self.STEP
def right_move(self):
... |
cec52af17b39763781b88628720920d38290c86c | my-xh/DesignPattern | /03行为型模式/15解释模式/解释模式.py | 3,042 | 3.8125 | 4 | from abc import ABCMeta, abstractmethod
class Expression(metaclass=ABCMeta):
"""抽象表达式"""
@abstractmethod
def interpreter(self, var):
pass
class VarExpression(Expression):
"""变量解析器"""
def __init__(self, key):
self.__key = key
def interpreter(self, var):
return var.g... |
5122893d898726377da5c2910fca3575eeb09348 | my-xh/DesignPattern | /01创建型模式/05原型模式/克隆模式.py | 1,036 | 4.34375 | 4 | from copy import copy, deepcopy
class Clone:
"""克隆的基类"""
def clone(self):
"""浅拷贝"""
return copy(self)
def deep_clone(self):
"""深拷贝"""
return deepcopy(self)
class Person(Clone):
"""人"""
def __init__(self, name, age):
self.__name = name
self.__age... |
d32ae91128cec3a270e1c54d9ac90a0d5fdbeb0c | my-xh/DesignPattern | /01创建型模式/04构建模式/构建模式.py | 2,507 | 3.78125 | 4 | from abc import ABCMeta, abstractmethod
class Toy(metaclass=ABCMeta):
"""玩具"""
def __init__(self, name):
self.__name = name
self.__components = []
@property
def name(self):
return self.__name
def add_component(self, component, count=1, unit='个'):
self.__component... |
add5d0a107fddbb992a75b508eda4f0d9b2e5b55 | my-xh/DesignPattern | /01创建型模式/01工厂方法/简单工厂模式.py | 1,214 | 4.15625 | 4 | from abc import ABCMeta, abstractmethod
class Coffee(metaclass=ABCMeta):
"""咖啡"""
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@abstractmethod
def get_taste(self):
pass
class LatteCoffee(Coffee):
"""拿铁咖啡"""
def ... |
149b33793d9b9d56b771d32a4c36bd4253a9b9b3 | tyler-burkett/CS460-HW3 | /calculations.py | 241 | 3.59375 | 4 | import math
import numpy as np
def mean_square_error(a, b):
"""
Mean Square Error Function
Arguments:
a, b - Pandas Series object
"""
diffs = np.subtract(b, a)
return 1 / len(a) * sum(diff**2 for diff in diffs)
|
764a3d777da00681901ef7251ac5c2925d57576c | kazamari/Stepik | /course_568/2.245_repetition coding.py | 687 | 4.375 | 4 | '''
Encoding of repeats is carried as the following: s = 'aaaabbсaa' is converted into 'a4b2с1a2', that is, the groups of
the same characters of the input string are replaced by the symbol and the number of its repetitions in this string.
Write a program that reads a line from the file corresponding to the string, com... |
1d872b5d91839e6f28f4e99a50380d9ef6bd49c2 | kazamari/Stepik | /course_568/2.296_chess-board.py | 580 | 3.6875 | 4 | '''
You are given two coordinates on a chess board of the first queen and two of the second. Find out, whether two queens
hit each other or not.
INPUT
Four integer numbers x1,y1,x2,y2 are being typed.
OUTPUT
Type "YES" (uppercase) if they hit each other or "NO" if the don't.
Sample Input 1:
1 1 3 3
Sample Outpu... |
fb42e824d054e5823174e0ceb0a85ad719dbdcc6 | kazamari/Stepik | /course_568/2.288_substring.py | 661 | 3.984375 | 4 | '''
On input your program gets the two strings s and t, consisting of lowercase Latin letters.
Output one number – the number of occurencies of the string t in the string s.
Example:
s = "abababa"
t = "aba"
Occurrences of string t into string s:
aba baba
ab aba ba
abab aba
Sample Input 1:
aba... |
5e039eca4779a9200ac661b12492bb8fe77e6feb | kazamari/Stepik | /course_512/2.3_Iterators, generators/problem_2.3.5.py | 1,554 | 3.71875 | 4 | '''
Целое положительное число называется простым, если оно имеет ровно два различных делителя, то есть делится только
на единицу и на само себя.
Например, число 2 является простым, так как делится только на 1 и 2. Также простыми являются, например, числа 3, 5, 31,
и еще бесконечно много чисел.
Число 4, например, не явл... |
9a34599d4bab721fd842873a090fe7ab2eb559ea | kazamari/Stepik | /course_431/3.2_Math functions.py | 853 | 4.28125 | 4 | '''
Напишите функцию f(x), принимающую дробное число x и возвращающую значение следующей функции, определённой на всей
числовой прямой:
f(x)=⎧⎩⎨⎪⎪1−(x+2)2,−x2,(x−2)2+1,при x≤−2при −2<x≤2при 2<x
Требуется реализовать только функцию, решение не должно осуществлять операций ввода-вывода.
Sample Input 1:
4.5
Samp... |
16b4c66261f6057635577382f87f38df85f3c289 | kazamari/Stepik | /course_568/2.316_re-occurrence-of-a-symbol.py | 2,386 | 4.625 | 5 | '''
In this problem, we will look how to implement re-occurrence of a symbol using regular expressions.
We may use the three various constructions to implement the repeat:
1. Wildcards { }, inside which we can place the minimum/maximum number of repeats that we are satisfied with, or the
exact number of repeats tha... |
21784e9043ab8725e3c61ca3f2b7fcda60fa2654 | kazamari/Stepik | /course_512/3.3_Regular Expressions/problem_3.3.16.py | 953 | 3.734375 | 4 | '''
Вам дана последовательность строк. Выведите строки, содержащие двоичную запись числа, кратного 3.
Двоичной записью числа называется его запись в двоичной системе счисления.
Примечание 2:
Данная задача очень просто может быть решена приведением строки к целому числу и проверке остатка от деления на три,
но мы все... |
2cb534265e1010770d009ffe0ed04713afe23f46 | kazamari/Stepik | /course_568/2.329_assigments.py | 3,894 | 4.5625 | 5 | '''
In this problem, we will deal with the implementation of a group of symbols.
We use wildcards "( )" to group symbols.
Grouping of characters allows us using repetitions for the sequences: thus, under the pattern "(ab)+" will fit any
string like "ababababab...ab".
Also, grouping of characters allows us to find in... |
6f642469296d3b9c7a40c55f8e79470af60431d3 | kazamari/Stepik | /course_568/2.281_bowling-pins.py | 832 | 3.65625 | 4 | '''
N bowling pins were put in one row and numbered from left to right with numbers from 1 to N. Then K balls were thrown
at this row; i-th ball knocked down all pins with numbers from li to ri inclusive. Find which pins remained standing.
Input data format
On input the program gets the number of pins N and the num... |
d864dba35327c12db39feb551a765d8da32c5ea0 | kazamari/Stepik | /course_431/5.19_Find a substring.py | 1,181 | 3.953125 | 4 | '''
Напишите программу, которая находит все позиции вхождения подстроки в строку.
Формат ввода:
На первой строке содержится исходная строка, на второй строке ввода указана подстрока, позиции которой требуется найти.
Строки состоят из символов латинского алфавита.
Формат вывода:
Строка, содержащая индексы (индексация ... |
6afb4c76020ade8c19294dbd36574926ed37223f | kazamari/Stepik | /course_568/2.325_message-encoding.py | 578 | 4.46875 | 4 | '''
We will be dealing with a trivial example of message encoding, where the mapping of original symbols to the "code" is
simply taking the ASCII value of the symbol. For example, the "code" version of the letter 'A' would be 65.
You will be given as input a string of any length consisting of any possible ASCII charac... |
1f8855f3343820d438c8d63270bdf133677e9860 | jamesboyd2008/ytla | /client/models/graph/graphers/gantt/one_gantt_g.py | 1,298 | 3.59375 | 4 | # This file defines the one_gantt_g function.
import random
from .... search.search_imports import *
import string
def one_gantt_g(graph, title):
"""
This function generates and opens an HTML document containing a graph.
Parameters:
graph (Graph) : The data to be graphed.
title (str) : Th... |
11d9e7c4ef3202182638187ddc39e32c1b8dc0e7 | Person-Maink/Phase-Diagrams | /trial.py | 192 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,100)
y = np.linspace(20,55, 100)
result = zip(x,y)
result = list(result)
print(result)
plt.plot(x, y)
plt.show()
|
037d5a76ef68a2c73ee95f0d88900ae4e016dc89 | jflygood/pythonLearningCourse | /Week 3-Stop watch.py | 2,102 | 3.53125 | 4 | # template for "Stopwatch: The Game"
# define global variables
import simplegui
total_time = 0
timer_display = "0:00:0"
win_times_display = "0/0"
position_timer = [200,200]
position_win = [300,50]
interval = 1 # 0.1 second
win_times = 0
total_try_times = 0
# define helper function format that converts time
# in tenth... |
aa75cd0b963ddb835801ddac9676116444a0fc58 | nnniuzy/python | /explore-python/5_decorator.py | 560 | 3.546875 | 4 | # def makeitalic(func):
# def wrapped():
# return "<i>" + func() + "</i>"
# return wrapped
#
# @makeitalic
# def hello():
# return "hello world"
from functools import wraps
class Tag(object):
def __init__(self, tag):
self.tag = tag
def __call__(self, func):
@wraps(func)
... |
6b35e8c533c180e329ee3343569a302ed3ebcf4e | jalonthomas/Tic-Tac-Toe-AI | /Tic-Tac-Toe-AI.py | 4,100 | 3.703125 | 4 | from math import inf
import time
human = 1
computer = -1
board = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
#Checks if either player has won
def has_won(board, player):
win_states = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], ... |
4c2de39f0221c488a0f65e025538665de907610f | ymnie/machine_learning | /machine_learning_git/polyReg.py | 1,595 | 3.6875 | 4 | '''
Created on Feb 24, 2014
this module gives the algorithms of polynomial regression
https://github.com/ymnie/machine_learning.git
@author: yimin.nie
'''
from numpy import *
import matplotlib.pyplot as plt
'''
generate the testing data set
'''
def createDataSet(N):
data = []
for i in range(N):
... |
8e64da783c376668d7cbafbaaf4117d7dbd50e55 | ymnie/machine_learning | /machine_learning_git/naiveBayes.py | 2,427 | 3.875 | 4 | '''
Created on Mar 19, 2014
this module shows how to use naive Bayes method for classification
@author: yimin.nie
'''
from numpy import *
'''
create a small data sample with labels +1 and -1
'''
def createDataSet():
dataSet = [[1,3,-1],[2,1,1],[1,2,-1],[3,6,1],[1,-2,-1],[4,3,1]]
return dataSet
'''... |
a50ee4df62837e5f1937da58444d87f577ef3e00 | wangztim/cs61a | /Practice Problems/first_upper_case.py | 343 | 3.703125 | 4 | def string_trimmer(string):
if len(string) > 1:
return string[1:]
else:
return ""
def first_upper_case(string):
if len(string) == 0:
return ""
if string[0].isupper():
return string[0]
else:
return first_upper_case(string_trimmer(string))
print(first_upper... |
a7b309a69615e43cb16a296fbcbf70e4ccb9b52c | veeteeran/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 687 | 3.96875 | 4 | #!/usr/bin/python3
"""MyInt Class inherits from int"""
class MyInt(int):
"""MyInt inherits from int"""
def __eq__(self, other):
"""
Redefine equality to be unequal
Parameters:
self: instance of the object
other: other object to compare against
... |
5fb5b95299d438ee287792597a7e776feff9a27e | veeteeran/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 197 | 4.15625 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
items = a_dictionary.items()
sorted_items = sorted(items)
for k, v in sorted_items:
print("{}: {}".format(k, v))
|
aef70d26ee65286d377eccb4a477dafd45ddc8aa | veeteeran/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 754 | 4 | 4 | #!/usr/bin/python3
"""
text_indentation() prints text with two newlines after characters in list
"""
def text_indentation(text):
"""
prints text with two newlines after characters in list
Parameter:
text: A string
"""
if type(text) is not str:
raise TypeError("text must be... |
f35b4f7921ac3f206f00e28333afc3d5e6487fe8 | veeteeran/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 210 | 3.75 | 4 | #!/usr/bin/python3
"""Creates a Square object"""
class Square:
"""Creates a Square object"""
def __init__(self, size):
"""Initializes a size to private attribute"""
self.__size = size
|
dc692ca38a90020ba5ed2ccb1c2eb4f58f9072de | veeteeran/holbertonschool-higher_level_programming | /0x11-python-network_1/6-post_email.py | 417 | 3.703125 | 4 | #!/usr/bin/python3
"""Takes in a URL, sends a request to the URL and an email address,
sends a POST request to the passed URL with the email as a parameter,
and finally displays the body of the response
"""
from requests import post
from sys import argv
if __name__ == "__main__":
try:
email = {'email... |
882f0ec2de52a7510bb51bf115c62053e2dcfd4a | veeteeran/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 4,270 | 3.5 | 4 | #!/usr/bin/python3
"""Docstring for Base class"""
import json
import csv
class Base:
"""The Base class"""
__nb_objects = 0
def __init__(self, id=None):
"""
Init method for Base class
Parameter:
id: an id
"""
if id is None:
Base.__nb... |
425ca0ff6d29d1e0fb04429d01f5c09ecd77cb31 | doimoi9191/python4tuan | /Bai 30 Lenh while else.py | 596 | 3.71875 | 4 | """
python hỗ trợ else block trong th while kết thúc một cách bình thường
- tức là ko dùng beak để kết thúc
while condition:
while block
else:
else block
nếu while kết thúc 1 cách bt thì else-block sẽ tự động dc thực hiện ngay sau đó.
"""
count = sum = 0
print("Nhập danh sách các số dương để tính trung bình")
... |
db954f528c9b2d42ca086f586300058f123c7187 | doimoi9191/python4tuan | /Bai 61 Khai niem va cau truc cua chuoi.py | 1,192 | 3.84375 | 4 | """
Chuỗi là tập các ký tự nằm trong nháy đơn hoặc nháy đôi, hoặc 3 nháy đơn hoặc 3 nháy đôi.
Chuỗi rất quan trọng trong mọi ngôn ngữ, hầu hết ta đều gặp xử lý chuỗi
"""
s1 = 'Hê lô ABC'
s2 = "Bê nhô"
s3 = """
Quanh năm buôn bán ở mom sông
Nuôi đủ năm con với một chồng
Lặn lội thân cò khi quãng vắn... |
21a720b20efbbcb647d694e0d2e7fe0f2b2a3089 | doimoi9191/python4tuan | /Bai 43 Ham Eval.py | 202 | 3.5625 | 4 | """
tự tính toán chuỗi phép toán phức tạp nào đó
"""
from math import *
s="(5*6)-(7/2)+8+sin(0.5)+pow(2,3)"
x=eval(s)
print(x)
x1,x2=eval(input("nhập x1,x2:"))
print("x1=",x1,"x2=",x2) |
23ef53faab922a4bba59e547b23e2645d3ff8630 | doimoi9191/python4tuan | /Bai 68 Ham tach chuoi.py | 540 | 3.53125 | 4 | s='sv007;nguyễn duy xuân;19/07/1991'
arr=s.split(';')
for x in arr:
print(x)
s1="""
cuộc đời là
bể khổ
còn lâu!
"""
a=s1.splitlines()
for line in a:
print(line,"a->",line.count('a'))
s2="""
sv01;nguyễn thị hạnh;1/2/2991
sv02;trần trùng trục;1/1/1990
sv03;hồ văn an;2/3/1998
... |
8b830f2e1beb2a03ead8c3e03a97fd79d5c68444 | doimoi9191/python4tuan | /Bai 13 Tinh diem trung binh/TinhDiem.py | 218 | 3.6875 | 4 | t = float(input("Nhập điểm toán: "))
l = float(input("Nhập điểm lý: "))
h = float(input("Nhập điểm hóa: "))
dtb = (t+l+h)/3
print("Điểm trung bình=",dtb)
print("Điểm trung bình=",round(dtb,2)) |
5f5fdd04b7f9645907b9467ab24ace91177fd2df | doimoi9191/python4tuan | /Bai 32 Vong lap long nhau.py | 800 | 3.640625 | 4 | """
vẽ chữ N dùng vòng for lồng nhau
"""
n = int(input("Nhập chiều cao: "))
# print("Vẽ chữ N")
# for i in range(n):
# for j in range(n):
# if i==j or j==0 or j==n-1:
# print("*",end='')
# else:
# print(" ",end='')
# print()
# """
# Vẽ tam giác dùng vòng for lồng nhau
# "... |
3b2e1b7341efb902133c16a253af2346b1d83f44 | causelovem/4-course | /python 2017/dz7/task4_yura.py | 442 | 3.6875 | 4 | class Double:
c = 0
def __init__(self, a):
self.c = a * 2
def what(self):
return self.c * 2
def swap(self, a):
tmp = self.c
self.c = a.c * 2
a.c = tmp * 2
return
class Normal:
c = 0
def __init__(self, a):
self.c = a
def what(self)... |
e84bae45734ed217ace27e364d5ae6802341af10 | causelovem/4-course | /python 2017/dz8/task1_yura.py | 844 | 3.796875 | 4 | class Vector():
x = 0.0
y = 0.0
z = 0.0
def __init__(self, a, b, c):
(self.x, self.y, self.z) = (a, b, c)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - ot... |
ad4884ea220f7b23dd16927fb40c3b6bf71a9d89 | causelovem/4-course | /python 2017/dz2/task1.py | 271 | 3.53125 | 4 | # ParallelSegments
p = eval(input()) # x1 y1 x2 y2 x3 y3 x4 y4
x1 = p[2] - p[0]
x2 = p[6] - p[4]
y1 = p[3] - p[1]
y2 = p[7] - p[5]
s1 = x1 ** 2 + y1 ** 2
s2 = x2 ** 2 + y2 ** 2
sp = (x1 * x2 + y1 * y2) ** 2
if (sp == s1 * s2):
print('YES')
else:
print('NO')
|
7a09b5c4a6616f296b64ef2f9797799193fdc167 | ZacharyLasky/Algorithms | /recipe_batches/recipe_batches.py | 956 | 4.125 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
min_batch = None
for ingredient in recipe:
if ingredient in ingredients:
batches = ingredients[ingredient] // recipe[ingredient]
if min_batch is None:
min_batch = batches
else:
... |
304461b3766685bc125481e6b4b2d8d6f2947e35 | itzvnl/python-basic-programs | /python/exit.py | 239 | 4.03125 | 4 | # This is the Example of Exit function in python
import sys
while True:
print('Type Exit to Exit the application')
response = input()
if response == 'exit':
sys.exit()
print('You are Exited From the application')
|
998ee551b11a404ec4e876e1326173c64726a6ef | sial-ari/project_euler | /problem_5.py | 217 | 3.609375 | 4 | def gcd(a,b):
while b != 0:
a, b = b, a % b
return a
def lcm(a,b):
return a * b // gcd(a,b)
def lcmm(*args):
return reduce(lcm, args)
if __name__ == '__main__':
print lcmm(*range(1,21))
|
a740340a8670af0eeb2524779176e4377ebf59db | PlanteVodu/system | /old/test.py | 743 | 3.59375 | 4 | # import sqlite3
# conn = sqlite3.connect('example.db')
# c = conn.cursor()
# # c.execute('''CREATE TABLE stocks
# # (date text, trans text, symbol text, qty real, price real)''')
# # Insert a row of data
# # c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# c.execute('''SEL... |
29a00d5c563dc100b8e3e07fd813b23838961cff | Nyajur/python-pill | /18 exponent_again.py | 572 | 4.125 | 4 | base = float(input("Please enter a number: "))
exponential = float(input("Pleae enter a power to raise to: "))
def raiser():
return base**exponential
print(raiser())
def raiser():
base = float(input("Please enter a number: "))
exponential = float(input("Pleae enter a power to raise to: "))
return base*... |
06c0759cde7e6f98b718cee0eebe9e6d459caaa0 | Nyajur/python-pill | /5-Numbers.py | 262 | 3.5625 | 4 | from math import *
print(2)
print(10 % 4)
my_num = -6
print(str(my_num) + " my most boring number")
print(abs(my_num))
print(pow(5, 2))
print(min(5, 2))
print(max(5, 2))
print(round(5.2))
print(round(5.7))
print(floor(256.57))
print(ceil(58.7))
print(sqrt(90.7)) |
a5c9b64ac0a1c82caeefa5202893f7e15686def9 | Nyajur/python-pill | /17-For_loop.py | 214 | 3.921875 | 4 | days = ["sin","two","carter","kionjo","friday"]
len(days)
""" for p in days:
print(p)
for r in range(1,5):
print(r)
for h in range(20):
print(h) """
for h in range(len(days)):
print(h)
print(days[h]) |
0a9a3d74b9efc22425d5a73d5bcb107a60b46298 | WindMillCode/Python | /python_tuple_functions.py | 496 | 3.921875 | 4 | print "min of data"
data=(10,20,'rahul',40.6,'z')
print min(data)
print "\n"
print "max of data"
data=(10,20,'rahul',40.6,'z')
print max(data)
print "\n"
print "len of data"
(10,20,'rahul',40.6,'z')
print len(data)
print "\n"
print "cmp(tuple1,tuple2):"
data1=(10,20,'rahul',40.6,'z')
data2=(20,30,'sachin',50.2)
pri... |
0c12a32529d9cc305dd21e90eb9bdb6edfe980b1 | WindMillCode/Python | /python_membership.py | 211 | 3.859375 | 4 | a=10
b=20
list=[10,20,30,40,50];
if (a in list):
print "a is in given list"
else:
print "a is not in given list"
if(b not in list):
print "b is not given in list"
else:
print "b is given in list" |
1b171a3bf57cac7cc75150fdeed57e36654310da | WindMillCode/Python | /python_access_string.py | 108 | 3.53125 | 4 | name="Rajat"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print name[i],"\t",name[n]
i+=1 |
6a3a8026700b2caea129d23d93f02e0642f1a0a3 | SaniaRahaman/census-main | /census_plots.py | 1,846 | 3.84375 | 4 | # Code for 'census_plots.py' file.
# Import necessary modules.
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Define a function 'app()' which accepts 'census_df' as an input.
def app(census_df) :
st.subheader('Visualise Data')
st.set_option('deprecation.... |
12941b020bb7f40387b1e65e2f71eee95ef65b93 | smjt/first | /strep.py | 126 | 4.125 | 4 | x=input("enter 1st string")
y=input("enter 2nd string")
z=input("enter 3rd string")
if y in x:
x=x.replace(y,z)
print(x) |
dd20f678000c1adcee54ccbb6abc8ebf294cfdeb | pedrochaves/pyjson | /pyjson/__init__.py | 713 | 3.765625 | 4 | from stringifier import Stringifier
from parser import Parser
__all__ = ['parse', 'stringify', 'to_file']
def parse(jsonstr):
"""
Parses a JSON string and returns a list or a dictionary
"""
return Parser().parse(jsonstr)
def stringify(obj):
"""
Returns a string with a valid JSON according ... |
1d6b586520df0f7c9e86d101132161b3527181df | vinisn/facilitadores | /drop_duplicados.py | 658 | 3.625 | 4 | import pandas as pd
#Importando o arquivo com numeros duplicados
dataset = pd.read_csv('C:\\Users\\vinis\\Desktop\\listas_paneas\\report_ligacao_20210409_143857_862.csv', sep=';')
#Transformando o dataset em um DataFrame
listatel = pd.DataFrame(dataset)
#Alterando o nome da coluna principal para que seja possivel... |
6624e19220a052c8bca4ac012fdf98f66c77e5f5 | AbhijeetKrishnan/codebook | /CodeChef/practice/FSQRT.py | 96 | 3.578125 | 4 | import math
t = int(input())
for test in range(t):
n = int(input())
print(int(math.sqrt(n))) |
8d20e2ee086ad63656648be98f6c9fcc301fc4e9 | AbhijeetKrishnan/codebook | /AoC-2022/Day 5.py | 1,947 | 3.53125 | 4 | import re
from typing import List, Tuple
def chunks(_list: list, n: int):
"""Yield successive n-sized chunks from list.
Ref: https://stackoverflow.com/a/312464
"""
for i in range(0, len(_list), n):
yield _list[i:i + n]
def process_stack_config(stack_config_strs: List[str]) -> List[List[str]]:... |
ebccfc2477c92a7ed4a477a9b4a156cefc43aa79 | irsol/Udemy | /Python-Bootcamp3/guessing_game.py | 710 | 4.0625 | 4 | import random
# Guessing game with yes/no repeat.
random_number = random.randint(1,10) # numbers 1-10
player_guess = None
while True:
player_guess = input("Guess a number between 1 and 10: ")
player_guess = int(player_guess)
if player_guess < random_number:
print(f"{player_guess} Too small, try ... |
c0802baba0623f0396515c1a35ccec750f4f18aa | yurtsiv/graphs | /test/test_graph_basics.py | 3,809 | 3.53125 | 4 | import unittest
from graph.graph import Graph
class TestGraphBasics(unittest.TestCase):
def test_add_node(self):
graph = Graph()
graph.add_node(1)
graph.add_node(2)
self.assertEqual(graph.nodes, {
1: [],
2: []
})
self.assertRaises(Exception, Graph.add_node, 1)
def test_add_ed... |
09199b4ae3cbb59af7ab5c7887b816ea8b2f8939 | alfador/anfo | /stats.py | 6,294 | 3.890625 | 4 | '''
This module provides various statistics functions, which all operate on a list
of songs.
'''
import math
def group_by(songs, function, cutoff=None):
'''
Groups the given songs by the given function.
Returns a dictionary mapping f(song) -> all songs s such that f(s) = f(song)
Arguments:
son... |
476d40ea559afc418b9f6c50f30d8b1b4124ea06 | Mathieusc/OpenclassRooms_project3 | /version2/position.py | 616 | 3.765625 | 4 | class Position:
def __init__(self, x, y):
self.position = (x, y)
def __repr__(self):
return str(self.position)
def __hash__(self):
# Transform into a 'str'
return hash(self.position)
def __eq__(self, pos):
return self.position == pos.position # 'in' will find each position in the set
... |
ec4018a1fa082a493b37591fd5039c58f4ee02a8 | fidler3/Puzzle-Problems | /InterviewQuestionsCh1.py | 3,397 | 3.59375 | 4 | <<<<<<< HEAD
def UniqueString(str):
a = sorted(str)
for i, letter in enumerate(a):
if i == len(a)-1:
return True;
elif letter == a[i+1]:
return False
print(UniqueString("lollipop"))
print(UniqueString("join"))
def isPermutation(stringa, stringb):
stringa = ''.join(sorted(stringa))
stringb = ''.join(sor... |
51ee025924fd958cb52989c200fd47ccb9a22191 | fidler3/Puzzle-Problems | /CH1 1.2/isPermutation.py | 268 | 3.96875 | 4 |
def isPermutation(stringa, stringb):
stringa = ''.join(sorted(stringa))
stringb = ''.join(sorted(stringb))
return (stringa == stringb)
print(isPermutation("cinema", "iceman"))
print(isPermutation("William", "Jennifer"))
print(isPermutation("Cinema", "iceman"))
|
b1a7293ddcc79d75dd066ab9b7da54cb61950570 | wqw-900902/my-git | /test/简单线性回归.py | 487 | 3.546875 | 4 | import numpy as np
x = np.array([4,8,5,10,12])
y = np.array([20,50,30,70,60])
def fit(x,y):
x_mean=np.mean(x)
y_mean=np.mean(y)
fenzi=0
fenmu=0
for i in range(x.size):
fenzi+=(x[i]-x_mean)*(y[i]-y_mean)
fenmu+=(x[i]-x_mean)**2
w=fenzi/fenmu
b=y_mean-w*x_mean
return w,b
... |
44b65949a503f73bfc6e9d29f51fc8d84af882d2 | MelvinFMQ/CP2015 | /March CT/2015Y6CPMCTDataFiles/Q2.5.py | 164 | 3.953125 | 4 | def swap(string, index=0):
if string == '':
return ''
return string[index+1] + string[index] + swap(string[2:])
#normal
print(swap('hiyo'))
|
db336cf5ed32c2d252d2a95f0ec70207e1d7ee43 | MelvinFMQ/CP2015 | /Practical/A lvl 2014 pract/Q3.2.py | 3,199 | 3.953125 | 4 | #Task 3.1
def print_opt():
print('''1. Add an item
2. Traverse the linked list of used nodes and output the data values
3. Output all pointers and data values
5. exit''')
#Task 3.2
class ListNode:
def __init__(self, data, pointer):
self.PointerValue = pointer
self.DataValue = dat... |
a44587abdc37522a52a3a55f06e19f21f9205e57 | srbgd/2048 | /bot4.py | 212 | 3.53125 | 4 | #!/usr/bin/python3
import board
def f(a):
max = 0
ans = 0
for i in range(1, 5):
if not a.deadlock(i):
b = a.copy()
t = b.move(i)
if (t >= max):
ans = i
max = t
return ans
board.main(f)
|
35cc7905d043dece75300d24b035ba4863f58cf2 | dalehp/advent19 | /19/beam.py | 1,563 | 3.6875 | 4 | from typing import Optional
from intcode import Computer, IntcodeTerminated
class BeamSearcher():
def __init__(self, c: Computer, x: int, y: int):
self.c = c
self.x = x
self.y = y
def big_enough(self) -> bool:
self.find_bottom()
top_right_x = self.x + 99
top_ri... |
f484da71438394b8f006bec7ff7f24489671458e | abishekabi/algorithms-sem1 | /project1/insertion_sort.py | 620 | 4.09375 | 4 | #!/bin/python3
"""
Insertion sort algorithm
"""
def insertion_sort(input_list):
n = len(input_list)
for j in range(1, n):
key = input_list[j]
i = j-1
while i > -1 and input_list[i] > key:
input_list[i+1] = input_list[i]
i -= 1
input_list[i+1] = key
return input_list
def main(input_list):
return in... |
c3c2e2870d6556541ecb5e79ea03bdc2dbf6deef | archu2020/list-revarse | /prob-prac3.py | 717 | 4.09375 | 4 | # list reversing
print("Enter the number of list one by one\n")
size=int(input("Enter the size of the list\n"))
mylist=[]
for i in range(size):
mylist.append(int(input("Enter the numbrt of list \n")))
print(f"My original list is {mylist}")
revs1=mylist[:]
revs1.reverse()
print(f"the 1st reverse of ... |
eaa3e22cabb29391f6aaf4531f8b76e7d465c321 | xlaw-ash/VSLearn-Python | /PythonBasics/comprehensions.py | 1,624 | 4.90625 | 5 | # for loops have some special uses with List Comprehensions
# Make a list of letters in greeting string.
greeting = 'Hello World!'
letters = []
for letter in greeting:
letters.append(letter)
print(letters)
letters = []
# Above 3 statements can be combined in a single line.
letters = [letter for letter in greeting]... |
8aac407392e79b9f910e117562de31c5dd678d7a | xlaw-ash/VSLearn-Python | /PythonBasics/booleans.py | 2,490 | 4.625 | 5 | # Booleans have only two values. Either True or False.
# Booleans are used for conditions.
yes = True
no = False
print(yes)
print(type(yes))
# Booleans are mostly used with logical operators. There are three main logical operators.
# 'and' operator between two conditions returns True only when both conditions are True... |
11594db27a7a30cbba654cd4bc140a4d4594177f | stoddabr/chairbot_ui_rework | /server/scripts/BrettControllers/robot_entity.py | 6,022 | 3.5 | 4 | '''
Robot entity class
written by Brett Stoddard for the neato robot ChairBot
uses formatting based on this article
https://realpython.com/documenting-python-code/
Changelogs:
- 6/4 Brett started class. Wrote basic public interfaces
- 6/20 Brett continued class. extended class to include ROS interface
'''
from m... |
d4701afadc306985d744bdc1b613fd1a5330fd4b | kehillah-coding-2020/ppic04-ForresterAlex | /set_d.py | 1,748 | 4.5625 | 5 | #!/usr/bin/env python3
#
# pp. 148, 151
#
"""
4.36 Modify the frequency chart function to draw wide bars instead of
lines.
"""
"""
4.37* Modify the frequency chart function so that the range of the x axis
is not tightly bound to the number of data items in the list but
rather uses some minimum and maximum values.
"... |
c7e0c8c419d83e40ccfaa6be416df2757941205e | lee-dk/Programmers | /Lv.1/solution1-1.py | 1,044 | 3.765625 | 4 | # 두 개 뽑아서 더하기
""" 문제
정수 배열 numbers가 주어집니다.
numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아
더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아
return 하도록 solution 함수를 완성해주세요.
"""
''' 제한사항
numbers의 길이는 2 이상 100 이하입니다.
numbers의 모든 수는 0 이상 100 이하입니다.
'''
#풀이
def solution1(numbers):
answer = []
if len(numbers) >= 2 and l... |
fed4c39acc3a814d448c3190196807bce026f2f3 | damirshakirov/python-basic | /hw04_easy.py | 3,120 | 3.984375 | 4 | __author__ = 'Шакиров Дамир Харисович'
# Все задачи текущего блока решите с помощью генераторов списков!
def newlist(): # Функция для генерации списка, заполненного произвольными целыми числами
import random
l=[]
for _ in range (10): l.append(random.randint(-10,10))
return l
# Задание-1:
# Дан список, заполненны... |
9c314afb1306d843876ab1dd705b65cdcc92f447 | bennypowers/exercism-kata | /python/bob/bob.py | 594 | 3.578125 | 4 | """Historical reenactment of the average 80's era U.S. highschooler"""
QUESTION = "Sure."
YELL = "Whoa, chill out!"
YELLED_QUESTION = "Calm down, I know what I'm doing!"
EMPTY = "Fine. Be that way!"
DEFAULT = "Whatever."
def hey(phrase):
"""Historical reenactment of the average 80's era U.S. highschooler"""
s... |
10179f28b944f03cb7ba284e892eeb8be3912c85 | leoaliaga10/aprendiendoPython | /Intermendio/ejm9.py | 401 | 3.90625 | 4 | def lower(elementos):return elementos.lower()
lista = ["LEONCIO","ALIAGA SALDAÑA","Peruano"]
print(list(map(lower, lista)))
print([cad.lower() for cad in lista ])
#--------------------------------
def saludo(idioma):
def saludo_es():
print("Hola")
def saludo_en():
print("Hello")
idioma_func = {"es":saludo_es,... |
d4d3cbd3d9784834baef82f895c624e5378df6ed | leoaliaga10/aprendiendoPython | /Intermendio/ejm3.py | 290 | 3.546875 | 4 | #Ejemplo de polimorfismo
class Perro:
def avanzar(self):
print("Corre")
class Perico:
def avanzar(self):
print("Volar")
def mover(animal):
animal.avanzar()
perro = Perro()
perico= Perico()
perro.avanzar()
perico.avanzar()
#llamando a metodo generico
mover(perro)
mover(perico)
|
cc8fb32f315e2a231c3f80ad9aaa678e37d957ba | leoaliaga10/aprendiendoPython | /Intermendio/ejm11.py | 441 | 3.578125 | 4 | #busqueda de patrones
import re
print(re.search(r"k","Kilometro"))
print(re.search(r"\d\d\d","Kilo911metro"))
patron = re.compile("\d\d\d")
print(patron.search("Kilo123metro").group())
if (re.search("\Aa[0-9].*(end|fin)$","a4 es una marca de fin")):
print("Se encontro el patron")
#Sustituciones
print(re.sub(r... |
a8d3e23da5fc98ffd52b805b11171bfa72f9eb6d | joseph-cheng/ascii_art_generator | /src/main.py | 1,659 | 3.640625 | 4 | from PIL import Image
import sys
import math
import argparse
# Takes an RGB colour and converts it to an ascii char to print
def colour_to_char(colour, available_chars):
brightness = max(colour)/255
return available_chars[math.floor(brightness/(1/len(available_chars)))-1]
#Takes an image path and given the m... |
679e5e6734b9f3fa577e914c7b6ca3655dfc3884 | StefanoskiZoran/Python-Learning | /Practise provided by Ben/Clock Calculator by Me.py | 1,210 | 4.125 | 4 | """
Request the amount of seconds via keyboard, turn the seconds into months/days/years/decades etc.
"""
def main():
seconds_request = int(input(f'Please input your desired seconds: '))
minute_result = 0
hour_result = 0
day_result = 0
month_result = 0
year_result = 0
decade_result = 0
... |
cb6f6cde771bda1158ac8bc3869d95a99dab1b85 | StefanoskiZoran/Python-Learning | /Practise provided by Ben/Algorithmic Boost.py | 326 | 3.84375 | 4 | def main():
adult_price = 28
children_price = 15
adult_count = int(input('How many adults will enter? '))
children_count = int(input('How many children will enter? '))
total_price = adult_count * adult_price + children_count * children_price
print(total_price)
if __name__ == '__main__':
... |
78332461902a6f14ac6b7db33c2c81c3e40e7f4c | ekeilty17/Project_Euler | /P063.py | 1,265 | 4.09375 | 4 | def is_d_digit_number(N, d):
return 10**(d-1) <= N < 10**d
def numDigits(N):
return len(str(N))
# The tricky part of this problem is to know when to stop searching
# we are looking at numbers of the form b^n
#
# What is an upper bound for the base, b
# Notice that 10^n will always have n+1 digits
# Thus, ... |
eaefa43ad79ba1cbbda3b2d4be254611a9835c86 | ekeilty17/Project_Euler | /P057.py | 996 | 3.890625 | 4 | def numDigits(n):
return len([int(d) for d in str(n)])
def gcd(a, b):
if b > a:
return gcd(b, a)
if a % b == 0:
return b
return gcd(b, a%b)
def reduce_fraction(numerator, denominator):
k = gcd(numerator, denominator)
return numerator // k, denominator // k
def partial_continue... |
dbcc526b936e79b9e79883579a5b78f010550851 | ekeilty17/Project_Euler | /P020.py | 432 | 3.796875 | 4 | def factorial(n):
if n < 0:
return 0
if n == 0:
return 1
return n*factorial(n-1)
# Python can just do this, but I'm not sure how else I would do it because this is pretty fast
def cheating(n):
f = factorial(n)
return sum(int(d) for d in str(f))
def main(N=100):
total = cheating... |
5e4353718e8a538482c8bbd0f5e360fc81f71399 | ekeilty17/Project_Euler | /P089.py | 3,661 | 3.96875 | 4 | # Basic Rules of Roman Numerals
# 1) Numerals must be written in descending order
# 2) M, C, and X must not be equalled or exceeded by smaller demoninations
# 3) D, L, and V can only appear once
# But then we want subtractive combinations, so we add these rules
# 4) Only one I, X, C can be used as the leading ... |
83c870f751da0d138df513abf5f7e504bfa1b4b2 | ekeilty17/Project_Euler | /P050.py | 2,787 | 4.0625 | 4 | def Sieve_of_Eratosthenes(n):
#Error Check
if type(n) != int and type(n) != long:
raise TypeError("must be integer")
if n < 2:
raise ValueError("must be greater than one")
m = (n-1) // 2 #list only needs to be half as long bc we dont care about even numbers
sieve = [True] * m
i =... |
27eddaf74587729081f397b1fb33c0f3a642b8d1 | ekeilty17/Project_Euler | /P028.py | 1,306 | 3.953125 | 4 | # to add to a list in a spiral fashion
def add_right(L, a):
for i in range(len(a)):
L[i] += [a[i]]
return L
def add_bottom(L, a):
return L + [list(reversed(a))]
def add_left(L, a):
a = list(reversed(a))
for i in range(len(a)):
L[i] = [a[i]] + L[i]
return L
def add_top(L, a):
... |
6ea1bf9965013870c1ae23471cf0101bae466419 | ekeilty17/Project_Euler | /P015.py | 530 | 3.703125 | 4 |
# It you look at it mathematically, it turns out the answer is just 2nCn
# nCr = n!/r!(n-r!)
def factorial(n):
if n == 0:
return 1
if n == 1:
return 1
if n < 0:
return 0
total = 1
for i in range(1,n+1):
total *= i
return total
def lattice_paths(n):
return f... |
db99c408545f1f2a5a5dd4996df1b88b077857e0 | ekeilty17/Project_Euler | /P007.py | 733 | 3.90625 | 4 | import math
def isPrime(n):
# This helps rule out easy ones
prime_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
if n < 2:
return False
if n in prime_list:
return True
for i in range(2, int(math.sqrt(n))+1):... |
b7886c7bbb18204362f784b0b5d25a9f4fc8fa7e | ekeilty17/Project_Euler | /P067.py | 2,917 | 3.921875 | 4 | def getLeftChild(i, j):
return i+1, j
def getRightChild(i, j):
return i+1, j+1
# The reason this is slow is because we do a lot of repeated computation
# if two different paths hit the same node, we will do the computation at the node multiple times
def brute_force(root, i=0, j=0):
# base-case
if i ==... |
5b6a80870770b3b3cea5815db5b66494a673955d | ekeilty17/Project_Euler | /P027.py | 1,022 | 3.765625 | 4 | import math
def isPrime(n):
prime_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
if n < 2:
return False
if n in prime_list:
return True
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
... |
fd59e899f9dd8db8be390666bda704c58a0d0c75 | ekeilty17/Project_Euler | /P053.py | 1,284 | 3.84375 | 4 | def factorial_list(n):
out = [1]
f = 1
for i in range(1, n+1):
f *= i
out += [f]
return out
# This is actually very fast
def brute_force_simple(N, n):
F = factorial_list(n)
total = 0
for k in range(1, n+1):
for r in range(1, k+1):
kCr = (F[k] // F[k-r]) ... |
8d57357f8a8dd14248f31e1478f1ce51918bf617 | jaredjk/FunWithFunctions | /FunWithFunctions.py | 482 | 4.125 | 4 | # for i in range(1,2001):
# if i%2 !=0:
# print "Number is {}. This is an odd Nnumber".format(i)
# else:
# print "Number is {}. This is an even Nnumber".format(i)
def multiply(arr,num):
for i in range(len(arr)):
arr[i] *= num
return arr
a = [2,4,10,15]
b = multiply(a,5)
... |
423f59ea31e6a1c96fd3a58c8d121d933c5d28d7 | KitsuneNoctus/makeschool | /site/public/courses/CS-1.3/Code/Archive/all-starter-code/linkedlist_test.py | 6,144 | 3.953125 | 4 | #!python
from linkedlist import LinkedList, Node
import unittest
class NodeTest(unittest.TestCase):
def test_init(self):
data = 'ABC'
node = Node(data)
assert node.data is data
assert node.next is None
class LinkedListTest(unittest.TestCase):
def test_init... |
0793ff72b089184ab37c8f48011e1f11582e1559 | KitsuneNoctus/makeschool | /site/public/courses/CS-1.3/Code/Archive/all-starter-code/sorting_test.py | 8,617 | 4.0625 | 4 | #!python
from sorting import (is_sorted, bubble_sort, selection_sort, insertion_sort,
merge_sort, random_ints)
import unittest
# Change this variable to the sort function you want to test
sort = bubble_sort
class IsSortedTest(unittest.TestCase):
def test_is_sorted_on_sorted_i... |
4a3a5dc2cf4bed027f9381f9ee6bde6249a642e2 | KitsuneNoctus/makeschool | /site/public/courses/CS-1.1/Projects/herdimmunity_starter_term2_2019/Virus.py | 535 | 3.765625 | 4 | class Virus:
'''Represents the virus that will be used to infect people in the simulation'''
def __init__(self, name, reproduction_num, mortality_num):
'''Sets up the virus to include the name of the virus, the reproduction number that controls how infectious it is, and the mortality rate or how de... |
254aa0ded80bba9f1cefcf1bee130276579604a6 | KitsuneNoctus/makeschool | /site/public/courses/CS-1.2/src/PlaylistLinkedList-StarterCode/main.py | 1,584 | 4.5 | 4 | from Playlist import Playlist
playlist = Playlist()
while True:
# Prints welcome message and options menu
print('''
Welcome to Playlist Maker 🎶
=====================================
Options:
1: View playlist
2: To add a new song to playlist
3: To remove a song from playlist
4: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.