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
85e3cb6ed5c432611d3f7dc67a7a22511170faef
txnguyen292/Logistic_Regression
/src/myLR.py
4,267
3.8125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy.typing import ArrayLike from typing import TypeVar X = TypeVar("X", int, float, str) # y = TypeVar("y", int) #=================================================================== #======== HELPER FUNCTIONS ===============================...
9d73c9cf69395b6f10979e0bbc4c0854526feb35
ma787/project-euler
/python/34 - Digit Factorials.py
704
4.0625
4
from utilities import factorial f_dict = {0: 1} for x in range(1, 10): f_dict[x] = factorial(x) def fact_sum(n): """Returns the sum of the factorials of the digits of n.""" fact = 0 m = str(n) for digit in m: digit = int(digit) fact += f_dict[digit] return ...
96ea332a5840cfcabd94a3178b046f76eb7508f0
petrstehlik/School
/SFC/jobclassifier/network.py
4,707
3.640625
4
from __future__ import print_function import logging from random import seed import time import sys from neuron import Neuron class Network(): def __init__(self, *args): """ inputs: number on input neurons layers: list of layers with number of neuros in it (i.e. [3,2] means 1st...
99dacc02b3116199894978797768529e8c7f3dc9
rafi06052002/itp-git
/01-Introduction/1.py
615
3.796875
4
print('my english score') value=eval(input('my score=')) if (value >=90 and value <=100): print('I passed the test and i feel inevitable') elif (value >=80 and value <=89): print('I passed the test and i feel great') elif (value >=70 and value <=79): print('I passed the test but i need to study harder') el...
3cc571c4933156b44ac88c62bcde07ae56aecf30
moose46/CSCI1511
/Week5/Assignments/find-upc-robertcurtiss.com.py
2,358
3.71875
4
""" Author: Robert W. Curtiss Class: CSCI-1511 -Project: CSCI1511 -File: find-upc-robertcurtiss.com -Created: Feb, 06, 2018 Description: Returns a check digit to determine if it is a valid upc http://wikipedia.org/wiki/Universal_Product_code (3x1 + x2 + 3x3 + x4 + 3x5 + x6 + 3x7 + x8 + 3x9 + x10 + 3x11 + x12) === (...
7735810d641bfa258efe86360e6887f5d0ef3173
essemfly/jupyter
/codility/Fish.py
546
3.546875
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A, B): # write your code in Python 3.6 fishes = len(A) ans = fishes downstream = [] for i in range(fishes): if B[i] == 0: while len(downstream) > 0: if downst...
9bc8bddcda973552ffbe785f4be1aa0d82526e51
kkeijuro/design_patterns
/bridge/python/bridge_abstract.py
1,341
3.640625
4
""" Bridge pattern example. Based on Wikipedia source """ from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." class Drawer: __metaclass__ = ABCMeta @abstractmethod def draw_circle(self, x, y, radius): raise NotImplementedError(NOT_IMPLEMENTED) class WindowsA...
a5d6f0dcde9229dc3fc4a95fb6c47f7893a546ae
zeroviral/leetcode_stuff
/average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.py
977
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: i...
c0af93cae32a8cbd90737535adc607ab0479a69c
zeroviral/leetcode_stuff
/kth-largest-element-in-a-stream/kth-largest-element-in-a-stream.py
597
3.703125
4
import heapq class KthLargest: def __init__(self, k: int, nums: List[int]): self.myList = nums self.k = k heapq.heapify(self.myList) while len(self.myList) > k: heapq.heappop(self.myList) def add(self, val: int) -> int: if len(self.myList) < self.k: ...
33cf3d9329899e8c95354308fcb526877e4e5f07
zeroviral/leetcode_stuff
/design-add-and-search-words-data-structure/design-add-and-search-words-data-structure.py
618
3.609375
4
class WordDictionary: def __init__(self): self.words = defaultdict(set) def addWord(self, word: str) -> None: self.words[len(word)].add(word) def search(self, word: str) -> bool: size = len(word) for choiceWord in self.words[size]: i = 0 while i < ...
31ec88d1a23e29cceb9a0a5e11e96c6b6222d56d
zeroviral/leetcode_stuff
/subtree-of-another-tree/subtree-of-another-tree.py
716
3.8125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: def dfs(root): ...
3690eb92ccb03029609dfd0ac4f38bfb363fb90e
zeroviral/leetcode_stuff
/trapping-rain-water/trapping-rain-water.py
1,519
3.75
4
class Solution: def trap(self, height: List[int]) -> int: ''' Setup: We need - leftmax, rightmax, left pointer, right pointer and area. 1. We will begin by declaring the variables, which are all 0 except right, which is going to close from the end. 2. While left < right, we iterate a...
0da1058b10349cc77b7554b013361b7bbf35b6df
zeroviral/leetcode_stuff
/two-sum-iii-data-structure-design/two-sum-iii-data-structure-design.py
905
3.890625
4
from collections import defaultdict class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.lookup = defaultdict(int) def add(self, number: int) -> None: """ Add the number to an internal data structure.. """ self.look...
c1f151e4802a0d2ba6ef0460aa05d1243fadfd4f
chuzhinoves/DevOps_python_HW2
/4.py
142
3.546875
4
sentence = input("Enter sentece: ").split(" ") [print(ind + 1, word if len(word) < 10 else word[:10]) for ind, word in enumerate(sentence)]
96a556b7c69fed82bce4dc9a18d01ab443dc9e89
AbdelrahmanReda/Python_Game
/tw0_player_Gmae(1).py
4,896
3.515625
4
# letters_onley=['A','B','C','D','E','F','G','H','I','J'] import random import time #---the ---- p1=0 p2=0 detecting_player = 0 #------- letter_list = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J'] random.shuffle(letter_list) print(letter_list) numbers ...
55fe980ce6c09bbe4b2ff4f061ef0ae087557235
djsabelo/DeepLearningWorkshop
/dnn_workshop_solved.py
3,852
3.578125
4
import tensorflow as tf import matplotlib.pyplot as plt from DeepLearningWorkshop.dnn_workshop_data import * ## Basics # Load data: # - plot X first time window; # plt.plot(X_train[0, :, 0]) # plt.show() # - load y data and plot it; # plt.plot(y_train) # plt.show() # - check X and y shapes print(np.shape(X_tra...
0e8c469efdef6f75f9556fb8e3eed67ce50f7c09
leowindwave/YAPT
/ClassExample.py
1,068
3.546875
4
class ClassExample(): '''This first line is a summary of this class. \ There must be ONLY one logical line in this overview. However (notice that must be an empty line between the summary and this block of text), the rest of this doctrings can be placed in several lines. These lines usually provide...
e95aea1bc3d8d25630a7923cb746b8359c93bc5a
dadhichvipul/pythonbite
/enigmum/Cryptography.py
3,265
3.546875
4
a=int(raw_input()) for i in range(0,a): arr=raw_input() array=raw_input() newstr=[] c=1 ar=[] for i in range(0,len(arr)): ar.append(arr[i]) #print ar for j in range(0,len(arr)-1): for k in range(j+1,len(arr)): if(arr[j]==arr[k]): c=0 ...
aefeb90c297b22ed12ff9876f219486cf545a51f
zack-song/python
/zack/quicksort.py
478
3.84375
4
def quicksort(arr,low,higth): pivot = arr[low] i = low j = higth while i < j: while i<j and arr[j] >= pivot: j -= 1 if i<j: arr[i] = arr[j] while i<j and arr[i] <= pivot: i += 1 if i<j: arr[j] = arr[i] arr[i] = pivot ...
43464230d5a30d66babb314b4dda733738a6ccac
dshar02/tools
/pstToUtc.py
564
4.0625
4
import datetime import dateutil.tz from dateutil.parser import parse flag = 0 answer = 'n' while flag == 0: string = input('Enter Pacific Time date in the format YYYY-MM-DD: ') date = parse(string) midnight = (datetime.datetime (date.year, date.month, date.day, 0, 0, 0, 0, dateutil.tz...
0c49bea2efbc9c8c97e23c33102a682c57dba9b1
tsetimmy/Inference-Algorithms
/assignment3/example/ECE521-week3.py
5,983
4.21875
4
# In[1]: ### ECE521 - 2015 Winter ### Example of neural network ### Written by: Alice Gao # In[2]: import numpy as np # In[3]: from copy import copy # In[4]: ################################### ## example of sigmoidal hidden layer implementation ## and stacking layers to make deep network ## you'll need to w...
61553d3b828ad7da5cfe0eb85e632964ff4ceb28
ShreyashSalian/Python-CRUD-Functionality-on-file
/File_operation.py
2,990
3.953125
4
print("Please Select any one option from below option!!!!") print("1. Adding Data to file : ") print("2. Displaying the Data : ") print("3. Searching the Record : ") print("4. Deleting the Reocrd : ") print("5. Updating the Record: ") x = int(input("Please Enter your choice : ")) if x == 1: wish = "Y" invfile...
bdae4a0eb0ca18b4291592a8fbff48343050cba2
Cbertugl/ia_d1
/environment.py
5,627
3.546875
4
import random import constants class Environment: # ============================================================================================== # CONSTRUCTOR # ============================================================================================== def __init__(self, size): self.__size...
016590c8b8b5bc8f65de81ad6a0b11017df69826
allen655915/PythonStudyNotes
/homework/homework1/TempConvert.py
408
3.609375
4
# 输入摄氏温度或华氏温度转换为对应的华氏温度或摄氏温度 TempStr = input("请输入带有单位的温度值:") if TempStr[0] in ['f','F']: C = (eval(TempStr[1:]) - 32)/1.8 print("转换后的温度是{:.2f}C".format(C)) elif TempStr[0] in ['C','c']: F = (eval(TempStr[1:])*1.8+32) print("转换后的温度是{:.2f}F".format(F)) else: print("输入格式错误")
67b110211c48f58f63f581bf59716e00f685a415
karsevar/tensorflow_projects
/tensorflow_projects/ML_python_ch10.py
10,173
4.65625
5
###Hands on machine learning with tensorflow and scikit learn: ###Chapter 10 Introduction to Artificial Neural Networks ##The Perceptron: #The Perceptron is one of the simplest ANN architectures. It is based on a slightly #different artificial neuron called a linear threshold unit: The inputs #and output are now numbe...
277d684a0539c8c1aa4c5d6b1f4ca3965ed17daf
karsevar/tensorflow_projects
/tensorflow_projects/python_ML_ch11.py
33,739
3.953125
4
###Hands on machine learning with Scikit learning and tensorflow ###chapter 11 Training Deep Neural Nets: ##Vanishing and Exploding Gradients problem: ##In this section the author mainly talks about the deep neural network problem #of exploding gradients (that plagues the upper layers of extremely large neural networ...
dbcf092b76937e1520b7166d531edb6afaa81553
karsevar/tensorflow_projects
/tensorflow_projects/pro_deep_learning_ch3.py
11,394
3.859375
4
###Pro Deep learning chapter 3: Convolutional Neural Networks ##Illustrate 2D convolution of images through an example: #Conceptualizing LSI system filters in a theoretical light. import scipy.signal import numpy as np import matplotlib.image as mpimg import matplotlib.pyplot as plt import tensorflow as tf chan...
6d0d02691553d88ee9ee7224b745bea97f7159c9
karsevar/tensorflow_projects
/tensorflow_projects/python_ML_ch8.py
8,074
3.703125
4
###Hands on machine learning with scikit learn and tensorflow: ###Chapter 8 Dimensionality Reduction: ##Two main approaches to dimensionality rediction (projection and manifold) #learning), and three of the most popular dimension reduction techniques are #PCA, kernel PCA, and LLE. ##Main Approaches for dimensionality...
90ad904b1e5c77ba8f736d00089c129f1b68f1c5
zbloss/PythonDS-MLBootcamp
/Python-Data-Science-and-Machine-Learning-Bootcamp/Machine Learning Sections/Linear-Regression/LRexample.py
2,399
3.921875
4
from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #try to predict housing prices based off of features path = '/home/zbloss/Github/PythonDS-MLBootcamp/Py...
de429dafc1e0289e1db3f2959c3898bf108da63f
zbloss/PythonDS-MLBootcamp
/Python-Data-Science-and-Machine-Learning-Bootcamp/Machine Learning Sections/Principal-Component-Analysis/PCA.py
1,536
4.125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # PCA is just a transformation of the data that seeks to explain what features really # affect the data from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() cancer.keys() cancer['...
2f1760f1041f6f1386d051d6a8bd4b102eba4b86
zbloss/PythonDS-MLBootcamp
/Python-Data-Science-and-Machine-Learning-Bootcamp/Python-for-Data-Analysis/Pandas/S6L26-28.py
2,921
3.96875
4
# DataFrames import numpy as np import pandas as pd from numpy.random import randn np.random.seed(101) df = pd.DataFrame(data=randn(5,4), index=['A', 'B', 'C', 'D', 'E'], columns=['W', 'X', 'Y', 'Z']) df # Grabbing values from the 'W' column df['W'] # A dataframe is just a bunch of series that share an index # Can...
45c6424e9e9774a88be83e668936936cb0c78a7c
Hemvati/1-June
/usrbdy.py
237
3.796875
4
def hpybdy(p): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday dear "+p+".") print("Happy Birthday to you!") h=str(input("Enter your name:")) b=str(input("Enter your name:")) hpybdy(h) hpybdy(b)
0a2b572e8c150b6595038a6b6ebb4b1814ad8cd1
NeraOS/Simulation-Python
/getmode.py
960
3.8125
4
"""Выбор режима""" print (""" Выберите режим загрузки: 1 - Стандартная загрузка с поддержкой сетевых драйверов 2 - Безопасный режим с записью действий в log 9 - Остановить загрузку Введите ТОЛЬКО цифру """) def wr(mode): f = open('config.ini','w') # открытие в режиме записи f.write(str(mode)) # за...
eda05fabbe9dd27f230eeedf3b71c9ea6f525bdd
prastabdkl/machine_learning
/supervised_learning/findingcoeffsusingnumpy.py
488
3.609375
4
import numpy as np import matplotlib.pyplot as plt from numpy import mean # mean()=sum/n x = np.array(range(1,14)) y = np.array([2,8,8,18,25,21,32,44,32,48,61,45,62]) #y=ax+b # a = (mean(x)*mean(y)- mean(x*y)) / (mean(x)**2 - mean(x**2)) # b = mean(y) - a*mean(x) # print(a,b) [a,b] = np.polyfit(x,y,1) # print(a,b) pl...
f9eacb076ca1e6efe49c9a3b3eff9f2a23e3cbd8
yipin3/products
/products.py
1,055
3.6875
4
import os # operating system # read file def read_file(file_name): product = [] with open(file_name, 'r') as f: for line in f: if '商品,價格' in line: continue name, price = line.strip().split(',') product.append([name, price]) return product # user input def user_input(product): while True: nam...
a2f9e5c3961f0cc76c98012fffe572d9c4b01d65
iesabadellDam/marcos
/Ejercicio7.py
353
3.96875
4
'''Ejercicio 7: ''' A = int(input("Introduzca el primer número: ")) B = int(input("Introduzaca el segundo número: ")) SUMA = A + B RESTA = A - B MULTIPLICACION = A * B DIVISION = A / B print("La suma es: ", SUMA) print("La resta es: ", RESTA) print("La multiplicación es: ", MULTIPLICACION) print("La divisió...
fed2b8b442e58d823e5a9ff626ae5c976c8ff768
Tselhacode/caesar-cipher-Project
/main.py
1,616
3.84375
4
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] from art import logo print(logo) direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type ...
46ec9a084ae3e98e217ccd160257b870111b8c4e
coshbar/Trabalhos
/Phyton/Max_Subarray.py
627
4.1875
4
#Have the function MaxSubarray(arr) take the array of numbers stored in arr and determine the largest sum that can be formed by any contiguous subarray in the array. #For example, if arr is [-2, 5, -1, 7, -3] then your program should return 11 because the sum is formed by the subarray [5, -1, 7]. #Adding any element b...
507d763a8196d7f37aeacc592130234b38cf3fa4
stevenjlance/videogame-python-oop-cli
/game.py
2,753
4.40625
4
import random class Player: # Class variables that are shared among ALL players player_list = [] #Each time we create a player, we will push them into this list. player_count = 0 def __init__(self, name): ## These instance variables should be unique to each user. Every user will HAVE a name, but each user...
3db3f1bec90997588a0a07d3750ac4fcf620e799
yanzewu/PyStiff
/polygon2d.py
690
3.921875
4
""" Utils of 2d polygon operations """ import numpy as np import matplotlib.path as mplPath def _origin_2d(node_coords): """ Return the origin point of an 2d polygon. Default is left down. """ return np.argmax(node_coords.dot(np.array([[-1], [-1]])), axis=0) def _area_2d(node_coords): """ Returns t...
63d19183d538b3f8896cbbc6ad9d167a86c39b71
WaterH2P/Algorithm
/Python/Sort/bubble.py
282
3.671875
4
def sort_bubble(l): max = len(l) while max > 0 : a, b = 0, 1 while b < max : if l[a] > l[b] : l[a], l[b] = l[b], l[a] a, b = b, b+1 max -= 1 return l L = [2, 5, 7, 1, 4, 3, 0] L2 = sort_bubble(L) print(L2)
226714031c6b7985c67fa3cfbe29466ca0897a21
WaterH2P/Algorithm
/Python/Code/generator.py
639
3.703125
4
# 生成器 # 用 () 代替 [] G = ( x*x for x in range(1, 11) ) for g in G : print(g) # 斐波拉契数列 def fib(max): n, a, b = 0, 0, 1 while n < max : print(b) a, b = b, a+b n += 1 print('') fib(8) # 斐波拉契数列 generator def fibG(max): n, a, b = 0, 0, 1 while n < max : yield b a...
96d320e2621bb377dd0644179f0a833eaa30998c
WaterH2P/Algorithm
/LeetCode/1-250/144 preorderTraversal.py
824
4
4
# 【中等】144. 二叉树的前序遍历 # 给定一个二叉树,返回它的 前序 遍历。 # 进阶: 递归算法很简单,你可以通过迭代算法完成吗? # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preorderTraversal(self, root: TreeNode): if not root: return [...
2533b8cf268c141b4bc276464c5a5a5d6e3dfa9a
WaterH2P/Algorithm
/LeetCode/1-250/26 removeDuplicates.py
725
3.84375
4
# -*- coding: UTF-8 -*- # 26. 删除排序数组中的重复项 # 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 # 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 class Solution: def removeDuplicates(self, nums): if len(nums) <= 1: return len(nums) else: l, r = 0, 1 while r < len(nums): if (nums[l]...
1fef0eb43ff46e6d79e7c27e8ebba7b47774162f
WaterH2P/Algorithm
/LeetCode/1251-1500/1411 AnimalShelf.py
1,862
3.953125
4
# 【简单】1411. 面试题 03.06. 动物收容所 # 动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。 # 在收养该收容所的动物时,收养人只能收养所有动物中“最老”(由其进入收容所的时间长短而定)的动物,或者可以挑选猫或狗(同时必须收养此类动物中“最老”的)。 # 换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,比如enqueue、dequeueAny、dequeueDog和dequeueCat。 # 允许使用Java内置的LinkedList数据结构。 # enqueue方法有一个animal参数,animal[0]代表动物编号,animal[1]代表动物种类...
431b4b7fb8c8be30421cde67e2e4cb26a06af7da
WaterH2P/Algorithm
/LeetCode/501-750/【未完成】698 canPartitionKSubsets.py
798
3.671875
4
# 【中等】698. 划分为k个相等的子集 # 给定一个整数数组 nums 和一个正整数 k,找出是否有可能把这个数组分成 k 个非空子集,其总和都相等。 class Solution: def canPartitionKSubsets(self, nums, k: int) -> bool: target, rem = divmod(sum(nums), k) if rem: return False nums.sort() if nums[-1] > target: return False if __name__ == '__...
75bdc635e57b0a169b0f44422d6224a2995a7da2
WaterH2P/Algorithm
/LeetCode/1501-1750/1531 permutation.py
1,326
3.765625
4
# 面试题38. 字符串的排列 # 输入一个字符串,打印出该字符串中字符的所有排列。 # 你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。 class Solution: def permutation(self, s: str) -> List[str]: self.res = [] mem = [*s] mem.sort() def makeup(index, rank, start): for i in range(start, len(rank)): temp = [*...
02cc18254bd3b2ace7efa0c08ea687cfb8892191
WaterH2P/Algorithm
/LeetCode/1-250/104 maxDepth.py
719
3.640625
4
# -*- coding: UTF-8 -*- # 104. 二叉树的最大深度 # 给定一个二叉树,找出其最大深度。 # 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 # 说明: 叶子节点是指没有子节点的节点。 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: return 0 if not root else max(self.maxDe...
dc69d3419b971c68d111e5b1b879f9ebfdd311c0
znekula/pyhank_NoMatrix
/docs/examples/usage_example.py
4,459
3.84375
4
""" Typical usage ================= To demonstrate the use of the Hankel Transform class, we will give an example of propagating a radially-symmetric beam using the beam propagation method. In this case, it will be a simple Gaussian beam propagating way from focus and diverging. First we will use a loop over :math:`...
9a52340002ffd0ac3b93cb796958deee21219aef
eguaaby/Exercises
/ex06.py
428
4.34375
4
# Check whether the input string # is a palindrome or not def ex6(): user_input = raw_input("Please enter a word: ") palindrome = True wordLength = len(user_input) for i in range(0, wordLength/2 + 1): if user_input[i] != user_input[wordLength-1-i]: palindrome = False if palindro...
0c032ee408fe893c744516c47908c8aac1f19ce0
eguaaby/Exercises
/ex05.py
980
3.890625
4
# Return a list of common # elements from two input lists from random import * def ex5(): # common=[] # c=[] # if len(a) < len(b): # c = a # else: # c = b # for num in c: # if num in a and num in b: # common.append(num) # print common # finding common n...
344dcd36cd16d7a5e02c48a4509a2d6b29d1ec8c
songx2-xy/HW4
/test_name.py
523
3.625
4
import unittest import name class TestName(unittest.TestCase): def test_name1(self): self.assertEqual(name.name("Joy","Zhang"),"Joy Zhang") self.assertEqual(name.name("Vivian","Song"),"Vivian Song") def test_name2(self): self.assertEqual(name.name("1","3"),"1 3") self.assertEqual...
5e6236b69bc08d63914dfa3058efbdc9bf389020
xredirector/playground
/program.py
366
3.9375
4
# -*- coding: utf-8 -*- # make print compatible with python 2.7 from __future__ import print_function """ Created on Mon Mar 12 21:11:54 2018 """ import argparse import fileinput import re import sys def is_greater (var1, var2): return var1 == var2 def is_smaller (var1, var2): return var1 < var2 if __name...
9b202673996e98dd7f8acf48ac98ffde2d46d934
GoldenKimchee/SimpleRPG
/src/players.py
5,841
3.765625
4
import random import time """Contains information on player attributes.""" class Player: """Describes a basic player.""" def __init__(self, name, level, health, will, strength): """Initializes stats""" self.name = name self.level = level self.health = health self.full_h...
063590b8528dfd30fbf8ef1f03fde04f7f4c34cb
Xxxz2016/TestGit
/solution1/mysolution.py
1,804
3.53125
4
# -*- coding: utf-8 -*- # @Time : 2018/3/19 21:03 # @Author : xxxz # @File : mysolution.py # @Software: PyCharm import re class Solution: def isvalid(self, str1): # isalnum # 出现1次或多次非数字字母字符,或空字符串 p = re.compile('([\W]+)|^$') if p.search(str1) is None: return ...
206ab02f5c3f1d3255987da534108c622081639b
amrmetwaly/python-sorting-algo-visualizer
/sorting_algs.py
4,375
4.03125
4
"""Sorting Algorithms in Visualized in Python using Tkinter.""" import random from bubble_sort import bubble_sort from merge_sort import merge_sort from quick_sort import quick_sort from tkinter import * from tkinter import ttk # region Tk initialize root = Tk() root.title('Sorting Algorithms Visualization') root.max...
aca8c9e3302fe49368db6079be6120b1bd7632cb
rebeca-maia/Projeto-e-An-lise-de-Algoritmos
/Prova2/Reconstruir.py
424
3.8125
4
def dic(frase): if frase =='eu' or frase =='amo' or frase =='programação' or frase =='dinâmica': return True else: return False def reconstruct(S,n): B=[] for i in range(n+1): for j in range(n,-1,-1): if dic(S[i:j]): B.append(S[i:j]+" ") print(""...
f92efc8bea36832a0681e8b3ba78089188171dba
vtech20/Python-Class
/20171105-Class9/functions_user.py
2,625
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 5 16:14:08 2017 @author: Vignesh """ def print_with_excl(word): print(word + "!") def print_sum(x,y): print(x+y) def print_sum(x=0,y=0): print(x+y) def return_sum(x=0,y=0): return(x+y) def return_sum(x=0,y=0): print("Func...
e73faba7db31c641b4306f77b0271e68a9ebdebe
brkyydnmz/PythonCamp
/PythonKamp-Hızlı Kısa/person.py
255
3.875
4
class Person: def __init__(self,name,lastName): self.name = name self.lastName = lastName musteri1 = Person("Ahmet","Demir") musteri2 = Person("Kerem","Varış") musteri3 = Person("İlker","Tural") print(musteri1.name)
5047bd9f2f7e256138feb0ac491ad73107572e6e
rstanleyc/progra-python
/ciclos/ej4.py
874
3.75
4
''' Un viajero desea saber cuánto tiempo tomó un viaje que realizó. Él tiene la duración en minutos de cada uno de los tramos del viaje. Desarrolle un programa que permita ingresar los tiempos de viaje de los tramos y entregue como resultado el tiempo total de viaje en formato horas:minutos. El programa deja de pedir ...
c181b126a7b8482eeacaf41e90f9fac319f326a6
rstanleyc/progra-python
/repaso-c1/guia.py
210
3.578125
4
def eliminar(texto, palabra): acum = '' final = '' for c in texto: print(c) if c != ' ': acum += c else: print(acum) if acum != palabra: final += acum + ' ' acum = '' return final[:-1]
c62fcfad7888b52f8a4d2e7efba5a2ad3d69af29
rstanleyc/progra-python
/listas/desviacion.py
290
3.5
4
# http://progra.usm.cl/apunte/ejercicios/2/desviacion-estandar.html def desviacion_estandar(valores): suma = 0 promedio = sum(valores) / len(valores) for v in valores: suma += (v - promedio) ** 2 desviacion = (suma / (len(valores) - 1)) ** 0.5 return desviacion
8cae93979ebd977ffc9856bf5e01966e5dc2e10b
rstanleyc/progra-python
/ciclos/bultos.py
950
3.6875
4
# ejercicio 2 # http://progra.usm.cl/Archivos/certamenes/2016-1_C1.pdf peso_total = 0 ingreso_total = 0 num_bultos = 0 mas_pesado = -1 flag = True while flag: bulto = int(input('Ingrese peso bulto: ')) if bulto > 500: print('No debe sobrepasar el limite de 500kg') else: if bulto <= 25: ...
b92a2ca4645cc1afe975a5d101d0dbe1eec9a485
rohitkrishna094/python_practice
/linked-list/LinkedList.py
632
4
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.size = 0 def getSize(self): return self.size def add(self, data): pass def clear(self): self.head = None ...
be933dfb8dd267af97a0011c85b71ade5dda3470
reverse/algorithmBook
/linkedList/cycler.py
273
3.734375
4
def Cycle(head): if head is None or head.Next is None: return head slow, fast = head, head while fast != None and fast.Next != None: slow, fast = slow.next, fast.next.next if slow == fast: return True return False
1ee490ee840b30bf6ce2aae871c2b3e302c4afc1
SKeerthi02/SeptemberLeetcodeChallenge
/WordPattern.py
579
3.546875
4
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: mapp = {} array = str.split(" ") isPresent = set() if len(pattern) != len(array): return False for i in range(len(pattern)): if pattern[i] not in mapp: if a...
319637f19ecd70d51c7fdcb4a8835acdb976e704
jwmarion/DC_lists
/list_positive.py
170
3.8125
4
#list5.py nums = [2,-4,5,-236,1,-2,7, 2, 4, -6] nums.sort() print("Positive numbers in list: ") for x in xrange(0,len(nums)): if nums[x] > 0: print nums[x]
96fdb56fe13ca8c87267a4efe63e7265ba850eae
therezacuet/URI-Beginner-Problem-Solution--Python-3-
/1011.py
357
3.71875
4
a,b,c=input().split(" ") A=float(a) B=float(b) C=float(c) triangle_area=0.5*A*C circle_area=3.14159*C*C trapezium_area=0.5*(A+B)*C square_area=B*B rectangle_area=A*B print('TRIANGULO: %.3f'%triangle_area) print('CIRCULO: %.3f'%circle_area) print('TRAPEZIO: %.3f'%trapezium_area) print('QUADRADO: %.3f'%square_area) pri...
1aac1e945e45d7e884931a5d379dda9e918583d5
KRuhl1662/python-challenge
/PyPoll/main_with_text_output.py
2,659
3.71875
4
#ON THE WAY TO THE STORE TODAY IT DAWNED ON ME THAT I FORGOT TO DO THE TEXT OUTPUT, I REALIZE I MAY NOT GET CREDIT, BUT I DIDN'T WANT TO LEAVE IT INCOMPLETE # Import csv import os import csv #Read csv election_csv = os.path.join("Resources", "election_data.csv") #set blank lists VoterID = [] County = [] Candidate = ...
1c3828dc198e181062f0dc03ca00e73772404595
taoma-commits/leetCode
/PythonSubmissions/[155]minStack.py
1,108
3.546875
4
# Runtime: 72 ms, faster than 33.40% of Python3 online submissions for Min Stack. # Memory Usage: 16.2 MB, less than 100.00% of Python3 online submissions for Min Stack. # @stack # Note: solution trade off speed for space. In Java, integer underflow. class MinStack: def __init__(self): """ initial...
55f931b42601d212bf037272c7205a97ef0fdee8
and1can/and1can-data-structures-and-algorithms
/ds_and_alg/copy_list_with_random_pointer.py
945
3.5625
4
from collections import defaultdict """ # Definition for a Node. class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': curr = head hashMap = defaultdi...
452cac2991623b9eb6865ecb7c7b5a2c5e4246e5
tectronics/zomatoData
/resultsShown.py
662
3.546875
4
#This is a part of the script.py files that is used to load json data into a dictionary and return data for a particular key #this was used to sense which of the files had errors while taking in input. Very essential to use it before combine.py as it gave idea that some files had random entries in them(not json ones) i...
67f957fe65caa6bbd0232e615ef1fdec222529b5
byrony/LeetCode
/326. Power_of_Three.py
968
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 16 01:54:13 2017 @author: caoxiang """ class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if n < 0: return False elif 0 < n < 1: n = 1/n...
4298867787ccb5d9c00f3abf7dfd28ec035826ff
byrony/LeetCode
/110. Balanced_Binary_Tree.py
894
3.875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # if we use the maxDepth() of question 104, then it's slow class Solution(object): def maxDepth(self, root): """ :type root: Tree...
ebdfc21dd9613c3a15f523d38e6a208599186a2a
byrony/LeetCode
/078. Subsets.py
2,429
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 7 23:43:28 2017 @author: caoxiang """ # Aug 14, 2021. Backtrace class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: res = [] self.dfs(nums, 0, [], res) return res def dfs(self, nums, s, curr,...
7c5a213334472f1497752787b762faa8f63d4e77
byrony/LeetCode
/122. Best_Time_to_Buy_and_Sell_Stock_II.py
1,926
4
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Administrator # # Created: 29/06/2016 # Copyright: (c) Administrator 2016 # Licence: <your licence> #--------------------------------------------------------------------...
0cf246c0ff357454066ccf307b31dded5c23c29c
byrony/LeetCode
/033. Search_in_Rotated_Sorted_Array.py
2,706
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 23 01:17:36 2018 @author: caoxiang """ class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ pivot = self.findPivot(nums) # print(pivo...
002305e1ad749e7940134282de2b6dad6c0039ae
byrony/LeetCode
/070. Climbing Stairs.py
1,281
3.984375
4
# Dynamic programming: bottom up, iterative class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ ways = {} ways[0] = 1 ways[1] = 1 ways[2] = 2 for i in range(3, n + 1): ways[i] = ways[i - 1] + ways[i -...
6e176cc1b5296dd84a5ad8b80ab35d9ee0472261
neo0311/pygeo_64845
/tests/test_objects.py
3,163
3.90625
4
from pygeo.objects import Point, Vector, Ray, Sphere # Point.__eq__ def test__point_equal__given_two_equal_points__return_true(): assert (Point((1, 2, 3)) == Point((1, 2, 3))) is True def test__point_equal__given_two_not_equal_points__return_false(): assert (Point((1, 2, 3)) == Point((4, 5, 6))) is False #...
4d6f78b29d735c6616e8dd3e14f8edb9cd48cece
grig-ar/Projects
/3/Python/pythonLab10/pythonLab10.1.py
627
3.78125
4
class Things: def __init__(self, n, t): self.namething = n self.total = t ###NEW1### def setColor(self, c): self.color = c def getColor(self): try: return self.color except: return 'No color' ###NEW1### th1 = Things('table', 5) th2 = Things('...
000ac0398eea3186c50b01be3bddbd75c70e429b
grig-ar/Projects
/3/Python/pythonLab10/pythonLab10.3.py
1,101
3.84375
4
class Figure: def __init__(self, c='White'): self.color = c def setColor(self, c): self.color = c def getColor(self): return self.color def getDescription(self): pass class Oval(Figure): def __init__(self, minAxis, maxAxis, color='White'): self.minA...
8ae1ee65adf0a13022b6d7e023eaa0db3509b713
eden-r/inf1340-2015-labs
/lab4.py
2,045
4.03125
4
#!/usr/bin/env python3 """ Graded Lab #4 for Inf1340, Fall 2015 This program computes federal and provincial sales tax. Assume that the provincial sales tax is 5 percent and the federal sales tax is 2.5 percent. It displays the amount of the purchase, the provincial sales tax, the federal sales ta...
8880680d0facb49196d07f6dd0d991882096a095
brandonwu/aoc2020
/3/1.py
554
3.953125
4
#!/usr/bin/env python def parse(line): return line def main(arr): tree_count = 0 width = 0 horiz_mult = 1 first = True for row in arr: if first: first = False width = len(row) else: x = horiz_mult * 3 if row[x % width] == '#': ...
2601ecb1a81cf85a65b1fc36434281bb645b21d2
brandonwu/aoc2020
/5/1.py
398
3.59375
4
#!/usr/bin/env python def parse(line): n = line.replace('F', '0').replace('B', '1') \ .replace('L', '0').replace('R', '1').strip() return int(n, 2) def main(arr): cur_max = -1 for line in f: n = parse(line) if n > cur_max: cur_max = n return cur_max if __n...
4b5b369fafd5657f10492685af047a6604254d05
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
/ex5_1_2.py
901
4.1875
4
# Chapter 5 # Exercise 1 & 2: Write a program which repeatedly reads numbers until the user enters # “done”. Once “done” is entered, print out the total, count, average of the # numbers, maximum and minimum of the numbers. If the user enters anything other than a number, detect their mistake # using try and except ...
eb4b36ee61f4541e2334038e366428a3b570d815
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
/ex7_2.py
1,030
4.1875
4
# Chapter 7 # Exercise 2: Write a program to prompt for a file name, and then read through the # file and look for lines of the form: # X-DSPAM-Confidence:0.8475 # When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart # the line to extract the floating-point number on the line. Count these lines ...
eee346b98c2726facf971db72ef2c5d6be0a7ee9
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
/ex8_4.py
472
4.3125
4
# Chapter 8 # Exercise 4: Write a program to open the file romeo.txt and read it line by line. For each line, # split the line into a list of words using the split function. # For each word, check to see if the word is already in a list. If the word is not in # the list, add it to the list. fh = input('Enter file: ...
4496a0a0617b3815bdc2f47b12f8008953881c59
KeyurMahajan1811/python_practice
/dice_roll.py
860
3.921875
4
import random def roll_dice(): total_count = random.randint(1, 6)+random.randint(1, 6) return total_count no_of_player = int(input("How many players are playing ?")) players = [] winner = 'none' if no_of_player <= 1: print("Players should be more than 1.") else: for i in range(no_of_player): ...
b0536f27205ab0f5de8c2931ea700ac884916644
pranaysagar1510/Python-programs
/type.py
569
3.625
4
x =10 y =-13 print(x,y,) print(type(y)) a = "bingo" b =25.0 print(type(b)) print(type(a)) c =3+5J print(c) print(type(c)) d =0B1010 print(d) print(type(d)) e =0XFF print(e) print(type(e)) f =0O1010 print(f) print(type(f)) g=True print(g) print(type(g)) h=int(b) p...
69c28f92350e4cd9a3ee18fd7727952d16d451f5
pjy970108/studying-algorithm
/baekjoon_problem/0826/백준_10872.py
121
3.984375
4
a = int(input()) def factorial(x): if x>1: return x*factorial(x-1) else: return 1 print(factorial(a))
df2ddc5896be3bd589ac2b74c6555fdeb721b41a
lihokim/GitHub_Python
/점프 투 파이썬/연습문제.py
616
3.71875
4
""" 2장 연습문제 #Q1 score=[80,75,55] print((sum(score))/len(score)) #Q2 print(13%2==0) #Q3 pin="881120-1068234" print(pin[0:6]) print(pin[7:]) #Q4 pin="881120-1068234" print(pin[7]) #Q5 a="a:b:c:d" print(a.replace(":","#")) #Q6 a=[1,3,5,4,2] a.sort() a.reverse() print(a) #Q7 a=['Life','is','too','short'] print(" ".jo...
6fd842e2080201f15316a06f2c490ff2e24a0a4b
WednesDay-Boy/python-ML
/perceptron.py
4,782
3.75
4
# -*- coding:utf-8 -*- from base import Classifier from base import Plot import numpy as np class Perceptron(Classifier): """ Class implementing perceptron classifier python version : 3.6.3 """ def __init__(self, path, eta, n_iter): """ constructor ---------------...
85c4960a3619a81a0b4066f8cdbb9d678e8eabf3
RFR77/my-repo
/MacroWT.py
275
3.8125
4
#!/usr/bin/env python3 dateWT = input("Enter the date needed for input (mm/dd/yy): ") currWt = float(input("Enter current weight: ")) f = open('output', 'w') f.write(str(dateWT) + '\n') f.write(str(currWt) + '\n') f.close() print("On",dateWT,"my weight was",currWt,".")
aa39ecf596e763c987cfed20a13198f95f967829
kearstenprince/Projects
/hangman.py
721
3.890625
4
hangman = input ("Type in a word in the subject: food: ") letters = [] for i in hangman: letters.append("-") y = 7 def hang_man(): global y x = input ("Guess a letter: ") count = 0 while count < len(hangman): if x == hangman[count]: letters [count] = x count = count + 1 if x not in hangma...
a313b98926fc1eb2ccd0ab3496cac897bffa7b60
kearstenprince/Projects
/babyPredictor/babyPredictor.pyde
1,259
4.09375
4
from random import * birthMonth = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] birthDate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] birthYear = [2018, 2019, 2020, 202...
fd4e7d90eff32547542cd8754328101836bb2c94
dr-neptune/DS_Python
/ch2_Analysis.py
4,099
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 11 14:48:22 2018 @author: michael """ import time from timeit import Timer import random #%% def sumOfN(n): theSum = 0 for i in range(1, n+1): theSum = theSum + i return theSum sumOfN(10) #%% def sumOfN2(n): star...
960e3bd17c18383b283fbfb8fc8d0d1691815a1a
Gekol/Algorithms-and-data-structures
/linked_lists/lab2.py
6,767
3.890625
4
class Node: def __init__(self, value, next_node=None): self.value = value self.next = next_node def __str__(self): return str(self.value) class LinkedList: def __init__(self, head): self.head = head self.tail = head def append(self, elem): self.tail.ne...
4326185f6d186a6b75edaceb140bca3615b62a74
Gekol/Algorithms-and-data-structures
/hash_tables/hashTableChaining.py
2,208
3.625
4
from .hash_func import get_hash from .merge_sort import sort_func from .linked_list import LinkedList, Node class HashTableChaining: """Hash-table using chaining""" def __init__(self): self.array = [] for i in range(10000): self.array.append(LinkedList()) self.codes = [] ...
eb03c0bdde775f705095b81801e1e911613b9f97
froprintoai/tetris
/src/tetris_view.py
10,544
3.53125
4
from tetris_layout import * from tetris_ctl import controller import pygame as pg import sys class view(): def __init__(self, screen): self.screen = screen # View functions here def draw_hold(self): # show string "HOLD" font = pg.font.Font(None, block_size) txt = font.rende...
55852121b8e8c80cce4107fcfc5da6d9871f930f
KristineYW/cs-module-project-hash-tables
/applications/no_dups/no_dups.py
338
3.609375
4
def no_dups(s): l = s.split(" ") l1 = list(dict.fromkeys(l)) s = " ".join(l1) return s if __name__ == "__main__": print(no_dups("")) print(no_dups("hello")) print(no_dups("hello hello")) print(no_dups("cats dogs fish cats dogs")) print(no_dups("spam spam spam eggs spam sausage spa...