blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ecb22a71fa96de80fdad4c190f8d653b1e253c9e | ved93/data-structure-algorithms | /week2_algorithmic_warmup/4_least_common_multiple/lcm.py | 619 | 3.609375 | 4 | # Uses python3
import sys
def lcm_naive(a, b):
for l in range(1, a*b + 1):
if l % a == 0 and l % b == 0:
return l
return a*b
def lcm_fast(a, b):
product = a * b
gcd = gcd_fast(a, b)
return product // gcd
def gcd_fast(a, b):
if a == 0:
return b
if b == 0:
... |
1d6019ff041ec7a1cb86fe8ce949e8e22f740731 | alanx3x7/python_projects | /Click_Game/part_2.py | 11,147 | 3.546875 | 4 | # Alan Lai, 2019/11/02
# Neocis Coding Challenge
import math
import sys
import numpy as np
from PyQt5.QtCore import Qt, QPoint, pyqtSlot
from PyQt5.QtGui import QPainter, QBrush, QPen, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class Window(QMainWindow):
""" Main clas... |
322b919d59bebf15467bd13167f7ec1bea19ba37 | HamburgerPlsdotexe/PyEx | /Analysis/ex2.py | 1,334 | 4.03125 | 4 | # Truth table loop
for p in[True, False]:
print(p, not(p))
print("\n")
for p in [True, False]:
for q in[True, False]:
print(p, q,(p and q))
print("\n")
for p in [True, False]:
for q in[True, False]:
print(p, q,(p or q))
print("\n")
for p in [True, False]:
for q in[True, False]:
... |
fe913d6d3e4df8ed238354e6a864907739dc72b3 | HamburgerPlsdotexe/PyEx | /Exercises/12(ranges).py | 848 | 3.921875 | 4 | # myList = list(range(101))
# print(myList)
#
# for i in range(0,101):
# print(i)
#
# even = list(range(0,100,2))
# odd = list(range(1,100,2))
#
# print(even, odd)
#
# myString = "abcdefghijklmnopqrstuvwxyz"
# print(myString.index('e'))
# print(myString[4])
smallDecimals = range(0, 10)
print(smallDecimals)
print(... |
6ed1a5a5f3d87cc78108447dbf7349e27dbdc1c0 | HamburgerPlsdotexe/PyEx | /Exercises/10(lists).py | 389 | 4.03125 | 4 | # ipAddress = input("enter an IP address: ")
# print(ipAddress.count('.'))
parrot_list = ["not pinin'", "no more", "a stiff", "bereft of live"]
for state in parrot_list:
print("This parrot is " + state)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7]
numbers = even + odd
print(sorted(numbers))
if numbers == numbers:
... |
cc22d6c7e0fdc6ec6c426d005e652a193ec569c5 | avzero07/machine-learning-course | /Assignment3/Scripts/scratch-3-final-data100D.py | 6,370 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 10:08:01 2020
@author: akshay
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.mixture import GaussianMixture
# K-Means Algorithm
# Implementing Functions
#testData = data2D[0:5,:]
#testMu = np.array([[1,1],[-1,-1],[1,0]])
# Func... |
da2232963a3c4aca362b4cca1785297a27ed550b | sergius-la/Algorithms-Python | /LeetCode/valid_parentheses.py | 1,030 | 3.796875 | 4 | class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0: return False
check = []
c = ""
for i in range(0, len(s)):
if s[i] == "(" or s[i] == "[" or s[i] == "{":
check.append(s[i])
if s[i] == ")" and len(check) > 0:
... |
0c46c2fcdacc09772e257f7a954a299b68517fe9 | sergius-la/Algorithms-Python | /LeetCode/jump_game.py | 812 | 3.921875 | 4 | """
Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 ... |
306df02f2123e656366a7932b580c693c363bbc7 | syd359/chinesenum2int | /chineseNumtoInt.py | 1,758 | 3.5625 | 4 |
def chineseNumtoInt(strs):
"""
暂时不支持非法输入的检测
"""
if strs == "":
return 0
# 可以根据需求,添加单位
unit_dict = {'亿': 100000000,
'万': 10000,
'千': 1000,
'百': 100,
'十': 10}
num_dict = {}
for key, val in zip(list("一二三四五... |
54c502f68f8fac02b50950eabe8c4a9282e5b91d | allamberto/cse-30872-fa18-assignments | /challenge12/program.py | 2,187 | 3.671875 | 4 | #!/usr/bin/env python3
import collections
import sys
# Candy Tuple
Candy = collections.namedtuple('Candy', 'weight yummy')
# Functions
def organize_bag(Bars, maxweight):
# Create 2D "bag" with Bars(x) v maxweight(y)
Weights = [[0 for _ in range(maxweight + 1)] for _ in range(len(Bars) + 1)]
# Organize... |
2bc1bcc117b95d227677543c6579b322763845c5 | allamberto/cse-30872-fa18-assignments | /challenge22/program.py | 394 | 3.5 | 4 | #!/usr/bin/env python3
import sys
CACHE = {}
def findCaleb(sum):
if sum == 1:
return 2
if sum == 2:
return 5
if sum == 3:
return 13
if sum not in CACHE:
CACHE[sum] = 2 * findCaleb(sum - 1) + findCaleb(sum - 2) + findCaleb(sum - 3)
return CACHE[sum]
if __name__ == '... |
7ff97f32b4af0a5415dca3e1f5424a48a8acd7ca | EuniceGatehi/Yummy_Recipes | /app/tests/test_userclass.py | 4,420 | 3.578125 | 4 | """ test_userclass.py"""
import sys
import unittest
# import module useraccounts
from app.userclass import User
class AccountTestCases(unittest.TestCase):
"""
Test for duplicate accounts(user already exists)
Test for short passwords
Test for correct output/account creation
Test login with no accou... |
ba6c2372c70371db557bafe27e5886eb2ce9bc1b | emrekutlug/machine_learning_refined | /mlrefined_hw_solutions_backup/mlrefined_hw_wrappers_and_data/Python2/Chapter_3/Exercise_3_2/exercise_3_2_hw.py | 1,054 | 3.5625 | 4 | # This file is associated with the book
# "Machine Learning Refined", Cambridge University Press, 2016.
# by Jeremy Watt, Reza Borhani, and Aggelos Katsaggelos.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv
# import the dataset
reader = csv.reader(open("kleibers_law_data.csv", "rb"... |
c3a80c7616c82bf949854b3b09d871d534d826b8 | emrekutlug/machine_learning_refined | /mlrefined_hw_solutions_backup/mlrefined_hw_coding_solutions/Python2_solutions/Chapter_4/Exercise_4_14/exercise_4_14_solution.py | 4,538 | 3.640625 | 4 | # This file is associated with the book
# "Machine Learning Refined", Cambridge University Press, 2016.
# by Jeremy Watt, Reza Borhani, and Aggelos Katsaggelos.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# import training data
def load_data(csvname):
# load in data
data = np.asarr... |
3fe433a64f24f76e7e1a26806c3d1464ddaa6c4c | emrekutlug/machine_learning_refined | /mlrefined_hw_solutions_backup/mlrefined_hw_wrappers_and_data/Python2/Chapter_3/Exercise_3_1/exercise_3_1_hw.py | 1,060 | 4.09375 | 4 | # This file is associated with the book
# "Machine Learning Refined", Cambridge University Press, 2016.
# by Jeremy Watt, Reza Borhani, and Aggelos Katsaggelos.
import numpy as np
import matplotlib.pyplot as plt
import csv
# import the dataset
reader = csv.reader(open("student_debt_data.csv", "rb"), delimiter=",")
d ... |
9996d1adb7d6ed4c33386964026f2c7de6abc551 | emrekutlug/machine_learning_refined | /mlrefined_hw_solutions_backup/mlrefined_hw_coding_solutions/Python2_solutions/Chapter_8/Exercise_8_1/exercise_8_1_solution.py | 3,051 | 3.765625 | 4 | # This file is associated with the book
# "Machine Learning Refined", Cambridge University Press, 2016.
# by Jeremy Watt, Reza Borhani, and Aggelos Katsaggelos.
import numpy as np
import matplotlib.pyplot as plt
import csv
# import training data
def load_data(csvname):
# load in data
reader = csv.reader(... |
60ee39bbc461099881e0292bb89e17cdeb849dba | Lynnlan/Search-Engine-Simulation-for-Story-Book | /codes.py | 9,795 | 3.84375 | 4 | import string
import math
# *******************************************************************************
# create a list of stopwords: forbidden.
stopword = open('stopwords.txt', 'r', encoding='utf-8')
forbidden = []
for line in stopword:
word = line.strip()
forbidden.append(word)
stopword.close()
# ****... |
adc9b5d5bf684217f196e5a0a0763d44ac9fe4f7 | blueboy1593/algorithm | /Programmers/Hash/완주하지못한선수_others.py | 696 | 3.5625 | 4 | import collections
def solution(participant, completion):
print(collections.Counter(participant))
print(collections.Counter(completion))
answer = collections.Counter(participant) - collections.Counter(completion)
print(answer)
return list(answer.keys())[0]
# 이거는 실제로 hash를 사용해버림
def solution(parti... |
342f63cb663c0bb4f57c52ad64d4f27414a89dde | blueboy1593/algorithm | /SSAFY알고리즘정규시간 Problem Solving/8월 Problem Solving/0828이론/QueueTest.py | 295 | 3.6875 | 4 |
myque = []
def enQueue(item):
myque.append(item)
def deQueue():
return myque.pop(0)
print("myque", myque)
enQueue(100)
enQueue(200)
enQueue(300)
print("myque", myque)
print("deQueue", deQueue())
print("deQueue", deQueue())
print("deQueue", deQueue())
print("myque", myque)
print("OK") |
48426958c074b98f811c2fccde6074578a37f2c8 | blueboy1593/algorithm | /SSAFY알고리즘정규시간 Problem Solving/10월 Problem Solving/1004/prac.py | 131 | 3.75 | 4 | mydict = {}
mydict[(1,2)] = 1
mydict[(1,4)] = 3
# if mydict[(2, 5)] ==:
# mydict[(2,5)] = 10
print(mydict)
print(mydict[(1,1)]) |
72884af0e61ab580af295648f71c8e59acf06afe | blueboy1593/algorithm | /Programmers/월간코드챌린지시즌1/두개뽑아서더하기.py | 264 | 3.640625 | 4 | from itertools import combinations
def solution(numbers):
answer = set()
combs = combinations(numbers, 2)
for comb1, comb2 in combs:
answer.add(comb1 + comb2)
answer = list(answer)
answer.sort()
return answer
solution([2,1,3,4,1]) |
c8a02867a46c19419f5bb6094bb1446a3630d6eb | blueboy1593/algorithm | /SSAFY알고리즘정규시간 Problem Solving/9월 Problem Solving/0910실습/5185이진수.py | 667 | 3.578125 | 4 | import sys
sys.stdin = open("5185_input.txt", "r")
alph_dict = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
def change_to_2jin(num):
a = num // 8
aa = num % 8
b = aa // 4
bb = aa % 4
c = bb // 2
d = bb % 2
return str(a) + str(b) + str(c) + str(d)
T = int(input())
for tc in ... |
d2b9cc95790c7ea203a7b89c46c62fbd4b1e1975 | blueboy1593/algorithm | /baekjoon_collection/1541잃어버린괄호.py | 683 | 3.640625 | 4 | equation = input()
equation_list = []
temp = ''
for char in equation:
if char == '-':
equation_list.append(int(temp))
temp = ''
equation_list.append('-')
elif char == '+':
equation_list.append(int(temp))
temp = ''
# equation_list.append('+')
else:
temp... |
f5d97baa5b84debdeb154bc035d6296a5504dafc | SnehaShet22/RCPIT-BCA | /DAY-5.py | 4,332 | 4.5625 | 5 | '''
# 0 1 2
this_tuple = ('strawberry','orange', 'kiwi')
print(this_tuple) #('strawberry', 'orange', 'kiwi')
print(this_tuple[2]) #kiwi
print(this_tuple[-1]) #kiwi
t = ( 'strawberry', 'pinapple', 'mango','grapes','pomogranate','papaya','kiwi','orange')
prin... |
1d50bb66c6d6d7388df83434601ae7084cc49027 | broten15/alien-game | /settings.py | 1,471 | 3.640625 | 4 | class Settings():
"""A class to store the settings for Alien invasion"""
def __init__(self):
"""Initializes static game settings"""
# Screen setings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
# Ship settings
... |
bb5f4a063a2cb00435a0f24282bd37bbe8865001 | cmput401-fall2018/web-app-ci-cd-with-travis-ci-machung21 | /service.py | 612 | 3.75 | 4 | import random
class Service():
# returns a random number
# NOTE: You do not need to modify this method!
# Mock it instead
def bad_random():
file = open('/Users/dchui1/datafile', 'r')
numberStrings = file.readlines()
numbers = [int(x) for x in numberStrings]
return rando... |
85cb41aaa8c90e6985a7edde67d13f073edc90f4 | c1c3ro/Golfing-Extreme | /terrain_util.py | 2,064 | 3.515625 | 4 | import random
import math
from constants import *
def getDivSizes(app_width, x_div):
#Definindo um tamanho relativo de
#cada subdivisão
return app_width/x_div
def XDiv(app_width, x_div, divs_size):
#O terreno vai iniciar em x = 0
#por isso a lista de pontos x é iniciada
#contendo um 0
X = ... |
3330ebc55a4e696d02f5bcf2aa102c911e0da164 | AmberHsia94/ml-basics | /knn.py | 2,862 | 3.765625 | 4 | # coding=utf-8
'''
The implementation of KNN algorithm.
(1)收集数据:确定训练样本集合测试数据;
(2)计算测试数据和训练样本集中每个样本数据的距离;
(3)按照距离递增的顺序排序;
(4)选取距离最近的k个点;
(5)确定这k个点中分类信息的频率;
(6)返回前k个点中出现频率最高的分类,作为当前测试数据的分类。
@Author: AmberHsia
@Date: 18.11.2018
'''
import time
import pandas as pd
import numpy as np
import operator
from sklearn.metric... |
7541791550b6271c695f022e0866a02b9a1b08e1 | gourabbhattacharyya/Python-Hobby-Projects | /classImplementation/multipleInheritance.py | 639 | 3.59375 | 4 | class Mario(): #class no:1
def move(self):
print('I am moving')
class Shroom(): #class no:2
def eatShroom(self):
print('I am big now!!!!')
class idle(): #class no:3 with no functionality or blank class for future use
pass #string ... |
6dd6bd1e31c469fdaa2904b76a170166ff1cb284 | gourabbhattacharyya/Python-Hobby-Projects | /dictionary/dictionary.py | 240 | 3.640625 | 4 | age_test_dict = {'A':'10', 'B':'20', 'C':'30', 'D':'40', 'E':'50', 'F':'60', 'G':'70'}
print(age_test_dict)
#loop over dictionary items
for k,v in age_test_dict.items():
print('Key is :',k + ' and ' + 'Value is :',v)
print('\n')
|
4b3b3573a019225c100b740ccbee789f6a3b28f3 | horeckyt/MUNI | /tyden3/tyden3.py | 3,464 | 3.875 | 4 | def factorial_for(n):
fac = n
for i in range(n-1):
fac *= (n-1)
n -= 1
return fac
def factorial_while(n):
fac = n
while n>1:
fac *= (n-1)
n -= 1
return fac
def digit_sum(n):
digitSum = 0
while n > 0:
digitSum += n % 10
n = n // 10
r... |
5b8ded9aaa1a666894395ad034da832e8857b8c5 | horeckyt/MUNI | /tyden8/tyden8_but_really_its_week9.py | 1,994 | 3.578125 | 4 | from collections import deque
from random import randint
def to_morse(text):
t = text.upper()
trans = ""
for c in t:
if c in morse_dict.keys():
trans += morse_dict[c] + " / "
else:
trans += c
return trans
def freq_analysis(text):
t = text.lower()
words... |
dd877b1c4d80a231d6f573fc7d5bf639af998afa | krskelton/crypto | /caesar.py | 585 | 4.15625 | 4 | from helpers import alphabet_position, rotate_character
def encrypt(text, rot):
#create a new empty string
return_string = ''
#for loop to go through each character in the message
for char in text:
#check if the character is an alpha character
if char.isalpha() == False:
#if... |
bc5e5a497ba7b37e449514ff7ce335a37e2a7775 | ThatRustySpoonMate/Major | /S.T.A.V/TkinterResolution.py | 1,743 | 3.5 | 4 | #resolution = get_user_resolution("640x480", "1280x720", "1920x1080", "2560x1440", "3840x2160") SYNTAX
from tkinter import *
def get_user_resolution(*args):
global tkvar, confirmed, target_res
confirmed = False
root = Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.w... |
aded828b2879726aefb048ca8cfeacabaf36ffd2 | pishchynski/python_mag | /lab_5/iterators.py | 336 | 4.09375 | 4 |
def unique(iterable):
result = set()
for item in iterable:
if item not in result:
yield item
result.add(item)
def transpose(matrix):
return map(list, zip(*matrix))
if __name__ == '__main__':
# res = unique([1, 2, 1, 3])
# print(list(res))
print transpose([[1,... |
060e4d5c131ce5237ce6b2614e352d0c8ee26452 | Devesh-Maheshwari/ML_basics | /KNN/knn.py | 2,626 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix,classification_report,roc_curve,roc_auc_score
from sklearn.model_selection import GridSearchCV
df=... |
2661c26cabaf5f464d541a6790d5d1c7cb8dbdf5 | paulmirel/MICA-EIR-Spring-2021 | /test-codes/TBD-take-button-input/code.py | 1,256 | 3.578125 | 4 | #pushbutton test
import time
import board
def verbose(msg):
print(msg)
# our special button handler
from record_button import RecordButton
record_button = RecordButton(board.D12)
broken_button = RecordButton(board.D12) # should cause a readable message!
loop_time = 0
print( "Button Check" )
while True:
st... |
f33211c6f3bcfa98e07ebcfadb694bee8e3cc3f4 | gigaiDX/CS1999-buggy-race-editor | /init_db.py | 4,287 | 3.515625 | 4 | import sqlite3
DATABASE_FILE = "database.db"
# important:
#-------------------------------------------------------------
# This script initialises your database for you using SQLite,
# just to get you started... there are better ways to express
# the data you're going to need... especially outside SQLite.
# For examp... |
eca14719f8fa7be1ba791b2e97abc56c6bf67610 | gautamsw5/Hackerrank-Project-Euler-Plus | /16 Sum of digits of 2^N/soln.py | 218 | 3.53125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def sod(n):
s=0
while(n>0):
s=s+n%10
n=n//10
return s
t=int(input())
for i in range(t):
print(sod(2**int(input())))
|
645d6d03d0d750f0184ab035a8b8ff463a37eb38 | gautamsw5/Hackerrank-Project-Euler-Plus | /63 Powerful digit count/soln.py | 168 | 3.671875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
for i in range(1,10):
x=i**n
if x>=10**(n-1) and x<10**n:
print(x)
|
7b1c6f016299f8ef18a537deae21b54d459a80f5 | gautamsw5/Hackerrank-Project-Euler-Plus | /24 K-th Lexicographic Permutation of abcdefghijklm/soln.py | 1,337 | 3.8125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
'''
1. Build a list of all elements in ascending order.
The length of this list is n (i.e. not the original input size).
2. Given k we know what the first element will be in the kth permutation of the current list.
There are n groups in the lexicogra... |
8014846ce83062fd1302ccabf1f26ef71a82eb9c | gautamsw5/Hackerrank-Project-Euler-Plus | /70 Totient Permutation/euler - try2.py | 1,387 | 3.53125 | 4 | import math
def isperm(a,b):
x=[0]*10
y=[0]*10
while a>0:
x[a%10]+=1
a=a//10
while b>0:
y[b%10]+=1
b=b//10
return x==y
N=10**6
prime=[True for i in range(N)]
print("Init done")
p=set()
P=[]
for i in range(2,N):
if prime[i]==True:
p.add(i)
P.append(... |
5b1cc6f8732328af448951b01e01c66b7c0451e0 | NoahRoseLedesma/PegPuzzle | /puzzle.py | 1,061 | 3.8125 | 4 | """
Peg puzzle game
An example of state-space search
"""
from state import PuzzleState
from operators import RedSlideOperator, RedJumpOperator, BlueSlideOperator, BlueJumpOperator
import sys
def peg_puzzle(start_state_str: str, goal_state_str: str):
start_state = PuzzleState.from_string(start_state_str)
goal... |
f06c919f76123180d8057f192de7b6d5a3e6357c | fraboto/Data-Science-Study | /IntrComputationalThinkingPy/code/aproximation.py | 429 | 3.5625 | 4 | import sys
objective = int(input('Escoge un número: '))
if objective < 0:
sys.exit('No se puede encontrar la raíz cuadrada de números negativos')
epsilon = 0.01
step = epsilon**2
response = 0.0
while abs(response**2 - objective) >= epsilon:
response += step
if abs(response**2 - objective) <= epsilon:
p... |
17f9eef01d8ca71460c60f47efc5591477bd580a | xiaoyuehui/LintCode | /naive/Sort_Integers.py | 577 | 3.796875 | 4 | # -*- coding: utf-8 -*-
class Solution:
"""
@param: A: an integer array
@return:
"""
def sortIntegers(self, A):
# write your code here
for i in range(len(A) -1):
for j in range(len(A) - i - 1):
if A[j] > A[j + 1]:
'''
... |
14eb853ad1ef4dbaab47480d2c5c4b5ab64ca0da | xiaoyuehui/LintCode | /easy/Rotate_String.py | 685 | 4.1875 | 4 | # -*- coding: utf-8 -*-
#给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
#代码未能通过测试....return:nothing
class Solution:
"""
@param: str: An array of char
@param: offset: An integer
@return: nothing
"""
def rotateString(self, strs, offset):
# write your code here
liststr = []
i = offset
... |
cd03fb13d2b081fc29f9c9700377a2e6b7447ee5 | uponup/MyPython | /面向对象.py | 3,200 | 3.59375 | 4 |
def main0():
arr1 = [(suite, face) for suite in '♠️♥️♣️♦️' for face in range(1, 4)]
arr2 = [(suite, face) for suite in '♠♥♣♦' for face in range(1, 4)]
for (suite, face) in arr1:
print(suite, face)
print('\n=====================\n')
for (suite, face) in arr2:
print(suite, face)
... |
bd3d252c1058d81875005149cf626ff5bfdc679a | uponup/MyPython | /python爬虫/5、beautifulSoup4.py | 908 | 3.640625 | 4 | # bs是一个高效的网页解析库
# 类似于前端开发的数模转换,可以讲一个网页内容,转换成一个soup对象,然后我们直接访问标签内容
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>学习python的正确姿势</title></head>
<body>
<p class="title"><b>小帅b的故事</b></p>
<p class="story">有一天,小帅b想给大家讲两个笑话
<a href="http://example.com/1" class="sister" id="link1">一个笑话长</a>,
<a href="htt... |
d5c3021474b02612594752fb92d35d7e2c3b2d7f | yaoxy2010/rul | /torch_lua/regression.py | 4,976 | 3.578125 | 4 | def savitzky_golay(y, window_size, order, deriv=0, rate=1):
r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
The Savitzky-Golay filter removes high frequency noise from data.
It has the advantage of preserving the original shape and
features of the signal better than other ty... |
2227f98221b73b820404a85c5600b6c7975f6252 | Makneeskern/Lab_4 | /Lab_four_solution.py | 8,709 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 19:19:25 2019
@author: Mikef
"""
from RBTree import RedBlack
#Code courtiously provided by a classmate, Kimberly Arenas, for a fuctioning Red Black Tree
#because mine didn't work. I hope that's alright.
from BTrees import BTree
#Code taken from Blackboard... |
00151d27d5747091603f83967363362a19cbcf6f | gilady19-meet/yl1201718 | /cheack.py | 823 | 3.625 | 4 | rom turtle import *
import random
import time
colormode(255)
tracer(0)
hideturtle()
class Circle(Turtle):
def __init__(self,x,y,dx,dy,radius):
Turtle.__init__(self)
self.pu()
self.goto(x,y)
self.dx = dx
self.dy = dy
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
r = random.... |
2b6cc0f1650f875aa9c62f62fc52a20534ebbfe6 | gilady19-meet/yl1201718 | /ball.py | 1,017 | 4.03125 | 4 | from turtle import *
import random
import math
class Ball(Turtle):
def __init__(self, x, y, dx, dy, radius, color):
Turtle.__init__(self)
self.pu()
self.goto(x, y)
self.x=x
self.y=y
self.dx=dx
self.dy=dy
self.radius=radius
self.shape("circle")
self.shapesize(radius/10)
self.color(color)
def mov... |
36a6c2f32d24e6d637c36103b3d6cc7fb61ed94d | amlanpatra/programs | /python3/Check primality functions.py | 346 | 4.03125 | 4 | #Exercise 11 : Check prime number
def pn():
a=[]
num=int(input("Enter a number : "))
hf = (num//2 + 1)
x = ("is not a prime number.")
for i in range(1,hf+1):
if num % i ==0:
a.append(i)
if max(a) > 1:
print (num,"is not a prime number.\nThe divisors of",num," are :",a)
else:
print (num,"i... |
3e83db239864d4c5a5608ccc3cbd269c07cef554 | amlanpatra/programs | /python3/Graph.py | 208 | 3.734375 | 4 | import matplotlib.pyplot as plt
x = [1,2,3,6,7,10]
y = [-2,2,3,10,12,15]
#z = [3,7,6]
plt.plot(x,y)
plt.xlabel("X - Axis")
plt.ylabel("Y - Axis")
#plt.zlabel("Z - Axis")
plt.title("My first graph")
plt.show() |
63f60fb178995e3b66072d74cbfcc3d0ec3ca75b | amlanpatra/programs | /python3/Peterson number.py | 409 | 3.96875 | 4 | import math
x = input("Enter the number : ")
y = len(x)
z = float(x)
d = z
a = 0
for i in range(0,y):
b = int(d% 10)
c = math.factorial(b)
d = int((d-b)/10)
a += c
# print(d,b)
# a = int(a)
if a==z :
print(x,"is a Peterson number")
else :
print("The sum of the factorial of the digits is",a,"... |
ece1ea2bda7af815578bae4b8d7cc38eeae39c98 | amlanpatra/programs | /python3/divisor_of_a_number.py | 208 | 4.15625 | 4 | # Program to find out divisors of a number
x = float(str(input("enter the number : ")))
a = []
for i in range(2,int((x/2)+1)):
if (float(x) % i == 0):
a.append(i)
else:
continue
print (a) |
31b8a1a663029f62cffee75844b0949cf85b8177 | CachadaF/ML_Python_Intro | /Intro_Pandas/intro_hubble_data.py | 600 | 3.71875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
#%pylab inline -> para usar en una Jupyter-Notebook
#How to read the file with a header
data = pd.read_csv("hubble_data.csv")
data.head()
print ("Data:\n{}\n".format(data))
#Reading the same file, without a header
headers = ["dist", "rec_vel"]
data_no_headers = pd.... |
46231eb1bb2bfa718d971096235d1eb11137a128 | haroonsh/interview-prep | /leetcode/increasing-order-search-tree/python/Solution.py | 1,004 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
traversal = []
... |
bf07bbeb1bc21857a56e83d07cd9c565defc16d1 | HervisDaubeny/matrix_class | /matrix.py | 3,390 | 3.96875 | 4 | #!/usr/bin/env python3
'''Matrix class.'''
import sys
class Matrix:
'''Matrix representation class. Supports: addition, subtracrion,
multiplication'''
value = []
rows = 0
columns = 0
def __init__(self, value, size):
'''Constructor.'''
self.value = value
self.rows = s... |
83479acc325ca68ef430b1ca7af7f579399fb87d | piscokristian/Number-Guessing | /number_guessing.py | 1,489 | 4.21875 | 4 | import random
print("Welcome to the number guessing game!")
while True: #Create loop for 'Would you like to play again'
rng = random.randrange(0,50)
print("Guess from 0 to 50.")
numGuess = 0
while numGuess <= 5:
guess = input()
guess = int(guess)
#Doesn't reduce guesses ... |
74566194bd438d163da6729a4f921bfb52bd8634 | devil-py/Hacktoberfest | /python files/FahrenheitToCelsius.py | 184 | 4.21875 | 4 | # take input of Fahrenheit
f = float(input("Temperature in Fahrenheit is: "))
# calculate the celcius
c = (f - 32) * (5/9)
# print the celcius
print("Temperature in Celcius is ", c)
|
0fc49c30c43d28cfff6b5aa83c1c905b07f7c2c9 | mjbhobe/dl-pytorch | /directml/quickstart/quickstart.py | 3,899 | 3.609375 | 4 | """ quickstart.py - copy of the Pytorch quick start Fashion MNIST classification example"""
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
import torchmetrics
import torch_directml
# Download training data from open... |
ef3805eb50413bb4da4beda2317b0838d3b7dd88 | mjbhobe/dl-pytorch | /pyt_mnist_dnn2.py | 11,690 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
pyt_mnist_dnn.py: multiclass classification of MNIST digits dataset using a Pytorch ANN
@author: Manish Bhobe
My experiments with Python, Machine Learning & Deep Learning.
This code is meant for education purposes only & is not intended for commercial/production use!
Use at your own risk!! I... |
ba1aaac2e63a7fd3e091f4b73435627abe5fcae2 | syphox/banking-system | /main.py | 6,114 | 4.125 | 4 | from random import randint
import sqlite3
class Bank:
def __init__(self):
self.conn = sqlite3.connect('card.s3db')
self.cur = self.conn.cursor()
self.user_id = 0
self.card_number = "400000"
self.card_pin = ''
self.balance = 0
def drop_table(self):
... |
6ee9a3cfb29e8c11713073d56c2426776d7b21b6 | yawpei/pylearning | /test/module/me.py | 644 | 3.671875 | 4 | # me.py
# import file
#
# print(file.create_name())
# import file as f1
#
# print("f1:", f1.create_name())
# class File:
# def create_name(self):
# return "new file.txt"
#
#
# f2 = File()
# print("f2:", f2.create_name())
# from file import create_name
#
# print(create_name())
# 第一种,之前介绍了
import file
... |
782fd2452238c7bff2e4f831b351df925d540b7b | yawpei/pylearning | /test/Picklejson/Pickle.py | 2,529 | 3.609375 | 4 | import os
import pickle
data = {"aaa": 1, "bbb": 2, "ccc": 3}
print(pickle.dumps(data))
data = {"filename": "f1.txt", "create_time": "today", "size": 111}
with open("data.pkl", "wb") as f:
print(pickle.dump(data, f))
print(os.listdir())
with open("data.pkl", "rb") as f:
data = pickle.load(f)
print(data)
... |
0394248da042bdc1a261a3ce6d1fffd682b73343 | FedeEscudero154/Proyectos-Python | /Fibonacci.py | 1,144 | 3.84375 | 4 |
def fiboNVeces(n):
num_anterior = 0
num_siguiente = 1
contador = 0
serie = []
if n == 1:
serie.append(1)
elif n == 2:
serie.append(1)
serie.append(2)
else:
while contador < n:
serie.append(num_anterior)
aux = num_siguient... |
8442143a71ab2f065c90bc0a2d2eaadf30938b23 | ragwis/FYS3150-Project-1-delivery | /FYS3150_project_1.py | 2,926 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 18:21:38 2020
@author: rawis
"""
import numpy as np
import matplotlib.pyplot as plt
"""
make the toeplitz matrix with lower diagonal a, diagonal b and upper diagonal c,
assumes that |a|+1 = |b| = |c|+1
def toeplitz_matrix(a,b,c):
n = len(b)
A = ... |
80155e9f285dab2174df3bc616be5b62d85086af | Hema113/python_puzzles | /circle_circumference.py | 442 | 4.5 | 4 | #find area of circle and circumference
PI=3.14 #Define PI as constant value
#This function find area of circle
def area_circle(r):
return PI * r * r
#This function find circumference of circle
def circumference_circle(r):
return PI * 2.0 * r
"""Get user input"""
r=float(input("Enter the circle radius:"))
pr... |
f54effd5e5a3380936e0fa635e830c2f4c0ee80d | Hema113/python_puzzles | /fact.py | 206 | 4.1875 | 4 | def fact(n):
fact = 1
for i in range(1,n+1):
fact *= i
return fact
if __name__ == "__main__":
n=int(input("Enter number>>>"))
print("The Factorial of given number is", fact(n))
|
a916b0a85a83f215e649a69a25c24ed1f464bc6f | Hema113/python_puzzles | /list_largestno.py | 364 | 3.59375 | 4 | def large_no(user_ip):
max_value = user_ip[0]
for i in user_ip:
if i > max_value:
max_value = i
#lst.append(list)
return max_value
if __name__ == "__main__":
user_ip = input("Enter thr number:: ").split(" ")
lst = []
for i in user_ip:
lst.append(int (i))
... |
c277d1f2cee275a5a4e93c51a4f00c9fbd417179 | chopptimus/codewars | /python/count_change.py | 214 | 3.828125 | 4 | def count_change(money, coins):
if money < 0 or not coins:
return 0
elif money == 0:
return 1
else:
return count_change(money - coins[0], coins) + count_change(money, coins[1:])
|
aea822cffa2b1e74111279c71b3ed1597d5bea9e | William0523/smart_deal_tool | /stock.py | 882 | 3.515625 | 4 | #!/usr/bin/python
# coding=utf-8
from const import MARKET_SH, MARKET_SZ, MARKET_ELSE
class Stock:
def __init__(self, code, name="" ,price = 0):
self.code = code
self.price = price
self.name = name
self.market = self.market()
def market(self):
if (self.code.startswith(... |
78fa91e77bdd8ac3b84d4bc396ccd0246dd16c80 | amalvg/myproject | /PycharmProjects/My works/list_pro1.py | 341 | 3.953125 | 4 | list1=["app;e","orange","grapes","pineapple"]
# print(list1)
# print(list1[3])
# list2=[1,2,3,4,5]
# print(list1+list2)
# print("vegetables" in list1)
# print("orange" in list1)
# list1[2]="vegetables"
# print(list1)
# list1.append("xyz")
# print(list1)
# list1.insert(1,"egg")
# print(list1)
# print(len(list1))
print(l... |
761a9c98238ae2dac6980b4f09ecd72caea6353e | amalvg/myproject | /PycharmProjects/My works/code_challenge_1.py | 146 | 3.859375 | 4 | P=int(input("enter the principal amount"))
N=int(input("enter the no. of years"))
R=int(input("enter the rate"))
print("interest is", (P*N*R/100)) |
e9725e578ef2ac7cb5a3324f80e2e982a3d2e554 | bartekwalon/learning-git-task | /git_task.py | 357 | 3.640625 | 4 | shopping_list = {
"warzywniak": ['marchew', 'seler', 'rukola'],
"piekarnia": ['chleb','bulki','pączek']
}
sum=sum(map(len, shopping_list.values()))
for key, value in shopping_list.items():
print(
f"Idę do {key.capitalize()} kupię tu następujące rzeczy: {value}."
)
print(f"W sumie kupuję {sum... |
5187507f33d5ba2cd4c1c5d23e357341c9812ef5 | dengwenyue/leetcode | /generateParenthesis.py | 551 | 3.609375 | 4 | # -*- coding:utf-8 -*-
# @Time : 3/1/18 3:21 PM
# @Author : dengwenyue
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
def generate(s='', left=0, right=0):
if len(s) == 2 * n:
... |
97ed2f998e66e7cc9403185acc8590353ef56e1f | Fuzail96/Exercises | /Untitled4.py | 2,127 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
import numpy as np
num=int(input("Please provide no. of digits you want to print: "))
print(round(np.pi,num))
# In[9]:
decimal=int(input("Enter the no. you want to convert: "))
binary=bin(decimal).replace("0b", "")
decimal=int(binary,2)
print(binary)
print(decimal... |
022b62042759ae15c88b60bab88d646acb95bc8e | CyborgVillager/Gui_Tutorial | /Kivy_tutorial_files/Kivy_App_Tutorial_00/ShoppingCart/shopingcart_info.py | 7,222 | 3.96875 | 4 | import csv
class item:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
class store:
def __init__(self):
self.itemList = {}
def __init__(self, itemList):
self.itemList = itemList
def listItems(self):
... |
3cc603c6011b69982ea7450cd1192392e26d7f05 | CyborgVillager/Gui_Tutorial | /Kivy_tutorial_files/Kivy_App_Tutorial_00/Kivy_App_Tutorial/Example_Projects/Project_1.py | 815 | 3.96875 | 4 | #Project will be using printtouch/self touch basically allow user to use their fingers
#print will show the information to the user, depending on where the user has clicked on
#then draw an ellipse with color, pos x & y
#remember width, height
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graph... |
2bcd9a6121bde20be046d7c1383907386e5fc5ff | CyborgVillager/Gui_Tutorial | /Kivy_tutorial_files/Kivy_App_Tutorial_00/Kivy_App_Tutorial/Intro/runTouchApp_01.py | 526 | 3.625 | 4 | from kivy.base import runTouchApp
from kivy.lang import Builder
#This will load a string that will be shown onto your window
#runTouchApp(Builder.load_string('''
#StackLayout:
# Label:
# text:"Hello This is a Label, cannot interact with me"
#'''))
#By changing Label to Button your able to make the while... |
513c421c70ee63c3eac3c4f186c8330d18050d4f | CyborgVillager/Gui_Tutorial | /PyQt_tutorial_files/5grid_layout_pyqt.py | 2,472 | 3.65625 | 4 | from pyqt_source import *
# this program will make a continaer that will let the buttons/widgets show in a
# grid like pattern
# pyqt colors tutorial : https://pythonspot.com/pyqt5-colors/
class Window(QDialog):
def __init__(self):
super().__init__()
self.title = 'Grid Layout Gui'
self.top... |
7ec40488281f06e7ba4e4822cfff437b346637de | venterachallenge/dev_challenge | /JsonConverter.py | 2,184 | 3.640625 | 4 | import json
# this program takes the old format json file and converts it to the new format given in the readme
# I did leave the variable order the same in order to match with the data transformed in the json file so that
# either file could be run in the solutions.py file with as little trouble as possible
# @pre... |
6744149754f053a952023ec4e3425daa09e7a435 | honglingjinliu/hanshu | /hanshu.py | 14,363 | 3.59375 | 4 | #############内置函数##################
#
#
#############abs()####################
#函数返回数字的绝对值
#语法abs(x)
# print(abs(50))
# print(abs(-50))
############dict()####################
#函数用于创建一个字典
#class ditc(**kwarg)
#class ditc(mapping,**kwarg)
#class ditc(iterable,**kwarg)
# print(dict(a="a",b="b",c="c"))
# 映射函数方式构造字典
# print... |
62a342a521e635b959a2a29ec9f1e89109b05cb3 | alihoffmann/Settlers-of-Catan | /term project/player.py | 5,882 | 3.734375 | 4 | from board import *
class player(object):
def __init__(self, color):
self.color = color
self.roads = ["road"] * 15
self.settlements = ["settlement"] * 5
self.cities = ["cities"] * 4
self.points = 0
self.brick = 20
self.ore = 20
self.wheat = 2... |
76a8cfe1c91cef352484e11e353791411791e0de | Nur-aly/task2 | /task2.2.py | 144 | 3.96875 | 4 | numbers1=[1,2,5,9]
numbers2=[1,2,4,9]
new_number=[]
for i in numbers1:
if i not in numbers2:
new_number.append(i)
print(new_number)
|
92ce551c8f768f05345ecc09a9bba163c2d1fc3d | nitinvinayak/AlgorithmCoursera | /week2_algorithmic_warmup/3_greatest_common_divisor/gcd.py | 337 | 3.578125 | 4 | # Uses python3
import sys
def gcd_naive(a, b):
current_gcd = 1
max=b
min=a
if (a>b):
max=a
min=b
while(max%min==0):
current_gcd=min
max=min
min=max/min
return current_gcd
if __name__ == "__main__":
input = sys.stdin.read()
a, b = map(int, input.split())
print(... |
803002d1bca0fd004ef0567e3241b1b59c691a11 | Kianqunki/StreamAnalytics | /src/kmeans.py | 5,577 | 3.625 | 4 | # NOTE: Please note that, to change the distance function of k-means there are two
# ways. First way is to override the distance function by pointing the distance function to a function
# e.g.:
# def myfunc(a, b):
# pass
# kmeans = sklearn.Kmeans()
# kmeans.distance_function = myfunc
# But most of the useful librar... |
b0111bf191b76583d573cb7b1837f9a203067857 | Srivatsan-T/AI1103 | /Assignment-7/codes/Assignment-7.py | 864 | 3.9375 | 4 | #importing the numpy module to use uniform distribution
import numpy as np
#defining the simulation size
sim = 1000000
#initialising the sum of random variables
sum_random_var = 0
#defining the upper and lower bound for the random variables
lower_bound = 0
upper_bound = 1
#defining number of rv's to be created on each... |
95133f49aad8109833b6ed12104369796dc061ec | cq2018-pttkdlnb-1823/midterm-lab | /basis_statistical/core/io.py | 515 | 3.53125 | 4 | """
Hàm đọc dữ liệu
"""
import pandas as pd
def from_file_csv(file_path, header=None):
data = pd.read_csv(file_path, header=header)
data.columns = ["V"+str(i) for i in range(1, len(data.columns)+1)] # rename column names to be similar to R naming convention
return data
def wine_sample(file_path):
dat... |
8121e0665a670b02a72b9ede66ca5e4f34d1b962 | 6sr/IDE | /TryTheBasics/BindArrowKey.py | 247 | 3.734375 | 4 | def arrow_down(event):
print "arrow down"
def arrow_up(event):
print "arrow up"
root = tk.Tk()
tk.Label(root, text="Press a key (Escape key to exit):" ).grid()
root.bind('<Down>', arrow_down)
root.bind('<Up>', arrow_up)
root.mainloop() |
b1708152914884b82926563ecde189795037fd83 | yardenTal1/Hang-Man-Game | /hangman.py | 7,813 | 3.78125 | 4 | import hangman_helper
def same_length(words, pattern):
"""
A auxiliary function for 'filter_words_lis', that receive word list and pattern and check if the in same length.
the function returns a filter list of those words
"""
new_list = list()
for i in words:
if len(pattern) ... |
9c00ee1ca1502597448cb6f487e5b9a6300fd4e3 | mirmohsen1367/factorypattern | /abstract_factory_pattern.py | 1,659 | 3.71875 | 4 |
from abc import ABCMeta, abstractmethod
class PizzaFactory(metaclass=ABCMeta):
@abstractmethod
def createVegpizza(self):
pass
@abstractmethod
def createNoneVegpizza(self):
pass
class Vegpizza(metaclass=ABCMeta):
@abstractmethod
def prepare(self):
pass
class NonV... |
96ff8d58dc34c681489022a3498ae1b8cff1a947 | ferran9908/Python-Course | /Milestone 2/Using files/utils/database.py | 941 | 3.6875 | 4 | def create_book_table():
with open('books.txt', 'w') as file:
pass
def _save_all_books(books):
with open("books.txt", "w") as file:
for book in books:
file.write("{},{},{}\n".format(book["name"], book["author"], book["read"]))
def add_book(name, author):
with open("books.txt"... |
a9076c85f839de0e319525b979279be3eecd3997 | ai-course-2019/settlers_of_catan | /algorithms/first_choice_hill_climbing.py | 2,593 | 3.828125 | 4 | from abc import ABC, abstractmethod
from typing import Iterable, Any
AbstractHillClimbingState = Any
AbstractHillClimbingStateEvaluation = Any
class AbstractHillClimbableSpace(ABC):
@abstractmethod
def get_neighbors(self, state: AbstractHillClimbingState) -> Iterable[AbstractHillClimbingState]:
"""... |
25ae4818aab9451c0349b722f2cec91a85bf418f | dbadrian/aad_playground | /algos/cs_sedg/quick_find.py | 969 | 3.703125 | 4 |
class QuickFindUF():
""" Find: O(1)
Union: O(N), but for n-Union operations this means O(N^2)
"""
def __init__(self, N):
self.data = list(range(N))
def connected(self, p, q):
return self.data[p] == self.data[q]
def union(self, p, q):
pid = self.data[p]
qid... |
1844e6870ded998bb6106fac237257564cad355a | juliancabezas/Support-Vector-Machine-FromScratch | /support_vector_machine_sklearn.py | 4,864 | 3.90625 | 4 | ###################################
# Julian Cabezas Pena
# Introduction to Statistical Machine Learning
# University of Adelaide
# Assingment 1
# Support Vector Machine Classifer using scikit-learn
####################################
# Import libraries
import numpy as np
import pandas as pd
from sklearn.model_select... |
1f39fec36f2991aa48a1addc32b1b6a589b9d98f | VijayVictorious/Python-Practice | /loop upto n/odd number upto n in reverse order.py | 241 | 4.21875 | 4 | """ Write a program odd number upto n in reverse order """
n = int(input("Enter n = "))
for i in range(n,0,-1) :
for j in range(i,0,-1) :
if j % 2!=0 :
print("odd number upto n in reverse order = ",j)
|
afc7ffd6b139c55a284bece6decc11a325086e69 | VijayVictorious/Python-Practice | /for loop upto n/prime number or not upto n.py | 292 | 4.09375 | 4 | """ Write a program print prime numbers upto n """
n = int(input("Enter n = "))
for i in range(2,n+1) :
flag = "not a prime number"
for j in range(2,i+1) :
if i % j == 0 :
print(flag)
break
else :
print("Is the prime number")
|
9cb6d42aae102d6b9b127893cd1f3de017bd8220 | VijayVictorious/Python-Practice | /if else programs/program --10.py | 175 | 4.21875 | 4 | """ check a year is leap year or not """
num=int(input("Enter Year : "))
if num % 4 == 0 :
print(num, "is the leap year")
else :
print(num, "is not a leap year")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.