blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f3a185452cd98aeb260d833e0de2cb8dd70bfc38
bargc/GabrielClasses
/HomeWork1/save_files_functions.py
829
3.65625
4
import csv def write_to_file(content, filename, writetype): savefile = open(filename, writetype) savefile.write(content) savefile.close() def write_to_csv(content, filename, writetype): resultFile = open(filename, writetype) wr = csv.writer(resultFile, dialect='excel') wr.writerows(content) i...
2ca75fc01b20f0610dced05e7ffc33574f269a9d
xianyunguh/py_congrumendaoshijian
/012_players.py
854
4.09375
4
# 4.4 使用列表的一部分 page 54 # 4.4.1 切片 page 54 """ 要创建切片, 可指定要使用的第一个元素和最后一个元素的索引。 与函数range()一样, Python在到达你指定的第二个索引前面的元素后停止。 要输出列表中的前三个元素,需要指定索引0~3 """ players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) print(players[2:4]) print(players[:3]) # 如果你没有指定第一个索引,Python将自动从列表开头开始 print(players[1...
5c100b461be22ce191d29a18915750d544f68c14
xianyunguh/py_congrumendaoshijian
/025_parrot.py
175
3.640625
4
# 第7章 用户输入和while循环 page 100 # 7.1 函数 input() 的工作原理 message = input("Tell me something, and I will repeat it back to you: ") print(message)
449668affd37c935e348f34c03a3289a2139916d
xianyunguh/py_congrumendaoshijian
/022_user.py
4,624
3.8125
4
# 6.3 遍历字典 page 87 # 遍历字典的方式:可遍历字典的所有键—值对、键或值。 # 6.3.1 遍历所有的键—值对 user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi', } for key, value in user_0.items(): # 方法items()返回一个键—值对列表。 print("\nKey: " + key) print("Value: " + value) ''' 注意,即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存 储顺序,...
24d8f3028a353bbe4eafdd54d60b0b189dfc5497
PTNobel/dotfiles
/bin/bin/startup.py
6,328
3.5625
4
#!/usr/bin/python3 import os import sys import datetime as dt import time import process import i3exit def warning(*objs): """Usage: warning(as, many, objects, as, desired) Will print everything passed to it to stderr with the prefix WARNING:""" printed_list = 'WARNING' for i in objs: printed...
b1495dec1ab96b86aa537c74642e27f534f44857
tschelbs18/Python-fun
/word_finder.py
1,261
4.25
4
# Word Find based on english_dictionary # Script will find all words made from the word input. # Author: Ted Schelble # Date: 4/21/2019 print("Enter your name/word to find all words that can be built from it: ") master_str = input() english_dictionary_file = open("words_alpha.txt") # This file should get repla...
407437c77323ef9df0bd43a375b89c05f7ac728e
comicxmz001/LeetCode
/Python/27_RemoveElement.py
407
3.515625
4
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ index = 0 for i in xrange(len(nums)): if nums[index] == val: del nums[index] else: index += 1 return...
758f576071bd557ce340ca9627b516e2114ff977
comicxmz001/LeetCode
/Python/71. Simplify Path.py
397
3.890625
4
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ stack = [] path = path.split("/") for block in path: if block == "" or block == ".": continue elif block == "..": if stack: stack.pop() else: stack.append(block) return "/" + "/".join(stack...
0ca786cd7ee4256b64e33d99fa9bc360499dffdf
comicxmz001/LeetCode
/Python/263 Ugly Number.py
414
3.828125
4
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False if num == 1: return True factors = [2,3,5] for factor in factors: while num%factor == 0: num /= factor ...
4153250b72aff397ec98390b491e9315cf1e8dbc
comicxmz001/LeetCode
/Python/58_LengthofLastWord.py
291
3.703125
4
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if len(s.split()) == 0: return 0 return len(s.split()[-1]) if __name__ == '__main__': s = " sdf" print Solution().lengthOfLastWord(s)
5ed6bfbede824b1dc2fcecfb670eec146ace1a4e
comicxmz001/LeetCode
/Python/35. Search Insert Position.py
973
3.765625
4
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int O(logn) """ low = 0 high = len(nums) - 1 if target <= nums[low]: return low if target > nums[high]: ...
3fcef5fcf10f2a44095e059e681935c15d6825fa
comicxmz001/LeetCode
/ds/BST/rank.py
545
3.984375
4
# rank will use size(node x) function, # which returns the number of subnodes under node x # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.cout = None def size(node): if not node:...
a636ee44da5d9245c25a1ee120131bdb9fcc4df6
comicxmz001/LeetCode
/Python/147_InsertionSortList_Improved.py
1,518
4.09375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None """ Time exceed with Python!!!! Pass with C/C++ """ class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: List...
ae524e262f7759204c793d2a6b0ea7647dc6eb80
comicxmz001/LeetCode
/Python/19_RemoveNthNodeFromEndofList.py
871
3.828125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ count...
28c6bb7763ff665b488465123006de7f46dfe44f
comicxmz001/LeetCode
/Python/151_Reverse_Words_in_a_String.py
383
3.78125
4
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ # Method 1, 44ms return " ".join(reversed(s.split())) # Method 2, 40ms with slicing operator, where -1 is step. # return " ".join(s.split()[::-1] if __name__ == '__ma...
2e4808d3c618cf23556569cfec8455ea5cbd46dc
comicxmz001/LeetCode
/Python/371. Sum of Two Integers.py
954
3.59375
4
class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ if (a >= 0 and b >= 0) or (a <= 0 and b <= 0): return self._sum(a,b) else: # different sign a,b = max (a,b),min(a,b) if a > abs(b)...
8c82850118d60ba39067d92b5a884cd7446262af
jackfan108/Level_1_Puzzle-Games
/main.py
242
3.515625
4
#The main python file #initiate cars with their positions board = [] for i in range(6): for k in range(6): board[i][k] = '.' printboard(board) while True: #ask for user input move(board) printboard if win: print something break
01d303bdbb2040b2298ea3eae6445a99377e0520
Ledz96/ML_Project_1
/least_squares_gd.py
886
3.578125
4
# -*- coding: utf-8 -*- """GD functions""" import numpy as np from costs import* def compute_gradient(y, tx, w): """Compute the gradient.""" e = (y - tx.dot(w)) return - tx.transpose().dot(e) / y.shape[0] def least_squares_GD(y, tx, initial_w, max_iters, gamma): """Gradient descent algorithm."""...
e7c59368f48255f0a9ab8efd2a3b11e84e779cc3
Ledz96/ML_Project_1
/Alessandro_funcs/build_polynomial.py
404
3.765625
4
# -*- coding: utf-8 -*- """implement a polynomial basis function.""" import numpy as np def build_poly(x, degree): """polynomial basis functions for input data x, for j=0 up to j=degree.""" coefficients = np.empty((x.shape[0], degree + 1)) exps = np.linspace(0, degree, degree + 1) for i, xn in...
c799788046d7b88ea368f9fe1140db97cf705d48
ZQ774747876/AID1904
/untitled/day03/search.py
732
3.5
4
""" search.py 基本查找方法训练 """ # def search(list_,key): # low=0 # high=len(list_)-1 # while low<=high: # mid = (low + high) // 2 # if list_[mid]>key: # high=mid-1 # elif list_[mid]<key: # low=mid+1 # else: # return mid def buble(list_): for...
6085b8b1142840277e9b20240aaaa3a4280de056
ZQ774747876/AID1904
/python_base/day12/code01.py
346
4
4
""" 封装 数据角度 行为角度 设计角度 """ class A: b=50 def __init__(self,a): self.a=a def fun01(self): print("fun01") obj01=A(10) print(obj01.a) obj01.fun01()#自动传递对象地址 # 通过类访问实例方法,但必须手动传递对象地址 obj02=A(20) A.fun01(obj02) print(A.b) print(obj01.b)
b44d581ac508ae42a92f284149ce1805ffbe9350
ZQ774747876/AID1904
/untitled/day02/lstack.py
936
3.921875
4
""" lstack.py 栈的链式存储 重点代码 """ # 异常类 class StackError(Exception): pass #节点类 class Node: def __init__(self,data,next=None): self.data=data self.next=next #栈操作类 class LStack: def __init__(self): # 定义栈顶位置属性 self._top=None def is_empty(self): return self._top is None ...
282fe2eaa371c1a0fba4b11c139a14f655440e91
ZQ774747876/AID1904
/python_base/day17/code03.py
761
4
4
""" 迭代器 """ class EmployeeIterator: def __int__(self,target): self.__target=target self.__index=0 def __next__(self): if self.__index>len(self.__target)-1: raise StopIteration result=self.__target[self.__index] self.__index +=1 return result class employee: ...
f104c7c91c511174fe478ed1d122d2d15e25b8a0
ZQ774747876/AID1904
/python_base/day02/exercise04.py
141
4.15625
4
# 文件式python 对下列代码进行了优化,创建的1000 num01=1000 num02=1000 print(num01 is num02) print(id(num01)) print(id(num02))
68df3c749463a424ecd2058c3a021adfb7a4bc14
ZQ774747876/AID1904
/python_base/day08/code01.py
4,020
4.1875
4
""" 函数: """ def fun01(): print("fun01执行咯") #返回数据 #退出方法 return 100 print("函数有蜘蛛侠你看就是 ") result=fun01() print(result) #-----------------定义函数,两个数值相加--------------------- #分而治之 # 函数职责单一 def add(number_one,number_two): #获取数据 result=number_one+number_two return result #获取 number_one...
1bf2a3ab241e1f7dbc6986b659883750de619173
ZQ774747876/AID1904
/python_base/day05/exercise.py
466
3.59375
4
# import random # list1=[] # for red in range(1,8): # red=random.randint(1,33) # list1.append(red) # blue=random.randint(1,17) # list1.append(blue) list01=[] count = 1 i=0 while count<7: num01=int(input("请输入第%d个红球号码"%(count))) count +=1 if num01>33 or num01<1: print("不在范围") ...
447c821456e8151b79e21eed06f8b7c5149b3cdb
ZQ774747876/AID1904
/python_base/day08/exercise10.py
162
4.03125
4
tuple01=(1,2,3,4,5,5) tuple02=("jk","kj","ko","fj") tuple03=tuple01+tuple02 tuple05=[1,2,"nihao ",54,] print(tuple03) print(len(tuple03)) print(tuple(tuple05))
78cadeb7d76e903697fc4ed3e2d7d7604f4e4200
ZQ774747876/AID1904
/python_base/day09/exercise.py
791
4.3125
4
""" 练习: 定义类:具体事物,抽象化的过程 创建对象:抽象事物,具体化的过程 定义汽车类,数据(品牌,型号,价格),行为(启动,行驶) 创建至少2个对象 """ class Car: # 两个下划线开头,两个下划线结尾 def __init__(self,brand,model,price=1000000): # self 是调用当前方法的对象地址 self.brand=brand self.model=model self.price=price def action01(self): print(self.bran...
b3057584f844aae047ac90d10d12c5653cc9a140
simospirit/openstreetmap
/count_tags.py
1,234
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #https://classroom.udacity.com/courses/ud032/lessons/768058569/concepts/8443086480923 #!/usr/bin/env python # -*- coding: utf-8 -*- """ Your task is to use the iterative parsing to process the map file and find out not only what tags are there, but also how many, to get...
faa15cf45cce80194fc728babd730d1cfca2b8e2
NEIGHFAN/idk4
/G3/g3.py
14,933
3.625
4
def showgrid(): for i in range(10): print(Rgrid[i]) print('') #showgrid() def can_placeV(): empty =0 for i in range(LENGTH[placed]): if grid[(cy//75)+i][(cx//75)] == 0: empty += 1 if empty == LENGTH[placed]: return True else: return Fals...
65148d6a66cce9b9522ecb8575e15826ab46d17a
justinm329/Time-Series-Blog
/Time_series_101.py
7,143
3.9375
4
# Import libraries and dependencies import numpy as np import pandas as pd %matplotlib inline import yfinance as yf # Retrieve AMZN data amzn_data = yf.download("AMZN", start = "2010-01-01", end = "2021-05-28") # Visualize top rows amzn_data.head() # lets take a look at the closing prices for Amzn close = amzn_data["...
dd9e9d7ace4b41b5691366d5f755de4d5114cb8e
MaDickal/Python-for-Informatics-Exercise-11.2
/Exercise 11-2.py
362
3.609375
4
import re fname = raw_input('Enter a file name: ') try: fhandle = open(fname) except: print 'File cannot be opened:', fname exit() numlist = list() for line in fhandle: line = line.rstrip() num = re.findall('^New .*: ([0-9]+)', line) if len(num) > 0: for number in num: number = float(number) numlist.append...
8208a37183eece77a1890783c6c405e9941e1fe7
Abhishekbestha/Python
/Array/InsertionSort.py
580
3.921875
4
class InsertionSort(): arr = [] def __init__(self, arr): self.arr = arr self.doSorting() def doSorting(self): for i in range(1, len(self.arr)): key = self.arr[i] j = i-1 while j >=0 and key < self.arr[j] : self.arr[j+1] = self.arr...
294f36b6871b32cde19ecd4df82ad2a5d509f671
SonnyBurnett/codechallenge2
/koyan/assignment1/main.py
1,546
3.8125
4
import abc from math import pi class IArea(abc.ABC): @abc.abstractmethod def get_area(self): pass class ShapeSquare(IArea): def __init__(self, width): self.__size = width self.__area = self.__size ** 2 def get_area(self): area = self.__area return area ...
fa58951069b05af9803dba17fc85f4dd09f0eae8
hpausiello/python-challenge
/PyPoll/PyPoll.py
2,846
3.515625
4
#dependencies import os import csv import pandas as pd import numpy as np #create a path to current working directory resourcePath = os.getcwd() #create a list and add all .csv files from current directory to it using a for loop filepaths = [] for file in os.listdir(resourcePath): if file.endswith(".csv"): ...
b0743f9dc5f8fe7eaac966697fc8401da1d2e616
acolmena26/homework2
/maze.py
2,553
3.890625
4
moves = 0 passcode = 'SSNWES' userPasscode = "" won = False while moves < 30: userInput = input("You are in the magic maze. Which way do you want to go? ") moves = moves + 1 userPasscode = userPasscode + userInput print(userPasscode) if userPasscode[0] == passcode[0]: print("you got the ...
9ec25f5567d991b22aa2963ecee9549af9e5e478
Yunif3/pandemic_game_helper
/pandemic.py
597
3.84375
4
d = {} add = True def add_card(card): if card in d: d[card] += 1 else: d[card] = 1 def remove_card(card): if card in d: d[card] -= 1 if d[card] == 0: d.pop(card) while True: card = input(f"input the card [add is {add}]: ") if card == "show": ...
980cb2445bc9f047825dacb2e2da6ac8787ba8f0
yinakhoilian/Final-Project
/final_game.py
7,010
4.21875
4
import textwrap from random import randint print('****************************Escape to New York****************************') opening = 'Welcome to the Concrete Jungle. You just moved to New York and need \ to find a studio to rent. You are an experienced day trader. To see how much \ money you can spend per month on...
a1d27880b73709ae0e3d2c5c5e7cefef63230056
Norbo11/PyHang
/src/game.py
3,525
3.53125
4
from player import Player from util import get_choice, format_points from word import Word MAX_GUESSES = 9 class Game: def __init__(self): self.players = [] self.guessed = False self.num_players = 0 self.current_word = Word() self.guesses = 0 def end_game(self): ...
2ef104d0ef629cbfcc1d7d093aa99ff04fed2280
narkyzbzrgl/PP2
/HW7_1.py
1,241
3.640625
4
import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures x = np.array([0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]).reshape((-1, 1)) y = np.array([40,41,43,42,44,42,43,42]) #giving the data model = LinearRegression().fit(x, y) #fitting the model r_sq = mo...
52fbd5a209077c1de9a359169bd145208d396489
m7dev/python_learning
/simple/reference_links.py
644
3.75
4
print('Просте присвоювання') # Виведе одинакові значення об'єкта shoplist = ['яблука', 'молоко', 'морква', 'банани'] mylist = shoplist #milist - ще одно ім'я, яке вказує на той самий об'єкт del shoplist[0] #Видаляєм перший елемент списку print('shoplist:', shoplist) print('mylist:', mylist) ### print('К...
95a92d44c64563636cac06c892b14cd461cb6a08
m7dev/python_learning
/simple/doc.py
323
3.828125
4
def printMax(x, y): ''' Виводить максимальне значення з двох цілих чисел''' x = int(x) y = int(y) if x > y: print(x, 'більше') else: print(y, 'більше') printMax(100,3000) print(printMax.__doc__) help(printMax)
654810572f4d653ccf2e457b4efc2465c2575d53
crscillitoe/SMSSpamDetection
/data_loader.py
543
3.609375
4
############################################################### # load_data.py - functions for loading the data into memory # ############################################################### import csv def load_data(file_path): to_return = [] with open(file_path, encoding='ISO-8859-1') as csv_file: r...
4278e98acb777c4a8f48aa8324090f49eb584e24
dishagarg/hackerRank
/camelcase.py
176
4
4
# -*- coding: utf-8 -*- """Given s in CamelCase, print the number of words in s on a new line.""" s = raw_input().strip() print sum(s[i].isupper() for i in range(len(s))) + 1
c92b40b344f592539b69019c32a536d283e15964
stalinpedro/pythonproyect
/retooperadores.py
317
3.984375
4
print("inserta número") a = input() print("inserta otro número") b = input() num1 = int(a) num2 = int(b) print("La resta de los numeros es") print(num1-num2) print("El modulo de estos numeros es") print(num1%num2) dato1 = True dato2 = False print("Operacion or de un true y un false ") print(dato1 or dato2)
5d3a891dc7244de906a160657fa1de5b354825a9
tmsanrinsha/LP100knock
/chapter1/09.py
1,052
3.84375
4
#!/usr/bin/env python # coding: utf-8 import random # 09. Typoglyemia # # スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ. def typo...
d120ea02e9313bdd9dd1ab37d1fadc269ca219a9
dinos3741/ecosystem
/main.py
4,735
3.734375
4
from world import * from wasp import * # Set the characteristics of the world: window dimensions and gravity (indicative value 4): WIDTH = 1200; HEIGHT = 800; GRAVITY = 10 BUTTERFLIES = 13 # number of butterflies in the world OBSTACLES = 3 # number of obstacles WASPS = 1 # number of wasps in the world REFRESH_TIME ...
fbd0c57e20300268a9fb56902d531a177d14d910
huangsheng6668/my_leetcode
/tree/501_binary_search_tree_mode.py
1,996
4
4
# 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 # # 假定 BST 有如下定义: # # # 结点左子树中所含结点的值小于等于当前结点的值 # 结点右子树中所含结点的值大于等于当前结点的值 # 左子树和右子树都是二叉搜索树 # # # 例如: # 给定 BST [1,null,2,2], # # 1 # \ # 2 # / # 2 # # # 返回[2]. # # 提示:如果众数超过1个,不需考虑输出顺序 # # 进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内) # Related Topics...
13afc9dd250a82426b7d5b6d32e6d0b650a59c2c
ronny-souza/Lista-Entrega-05-Python
/Exercicio04.py
1,839
4.0625
4
# QUESTÃO 04 - Escreva uma função que receba o total gasto pelo cliente e a opção de pagamento, que pode ser: # 1) Opção: a vista com 10% de desconto # 2) Opção: em duas vezes (preço da etiqueta) # 3) Opção: de 3 até 10 vezes com 3% de juros ao mês (somente para compras acima de R$ 100,00). def menuPagamento(): pr...
c52c13b3d5bb1c29590111d3817690569ed0dac9
thereactgirl/cs-module-project-hash-tables
/hashtable/notes/LinkedList_beej.py
1,694
3.921875
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return f'Node({repr(self.value)})' class LinkedList: def __init__(self): self.head = None def insert_at_head(self, node): node.next = self.head self.head =...
8c347b8f9367a2aca0f60ccf9f0e7d728dae4342
booleanLegend/CECS228
/hw2.py
5,885
4.46875
4
#!/usr/bin/env python # coding: utf-8 # # CECS 228: Coding Assignment #2 # # ### Submission Instructions: # # Attach your coded solution to the programming tasks below. When you are finished... # # 1. Rename this file so that your actual name replaces "YOUR NAME" in the current notebook name, and submit it to the d...
49d4e2ba8d5f504428ebea9a7c3b5648c4bbc9c3
shm4771/Data-Science-From-Scratch
/ds_modules/vectors.py
1,003
4.15625
4
##In this file we will provide vector operations using list as representation from functools import partial, reduce import math def vector_add(u, v): """This function adds two vectors componnet wise """ return [u_i + v_i for u_i, v_i in zip(u, v)] def vector_subtract(u, v): """This function subtracts two vectors ...
7be1b0afab3598404c330dc634d215aff92be4bc
shm4771/Data-Science-From-Scratch
/ds_modules/gradient.py
4,143
3.765625
4
## first we will apply batch gradient algorithm #rather than fixing constant step size, we will range of step sizes and will choose which will minimize the error function or bigger benefit import vectors from functools import partial, reduce import vectors import random def linear_hypothesis(X, theta): return vector...
732022af956ceee47a73df7270320032ee60c58b
shm4771/Data-Science-From-Scratch
/ds_modules/central_limit_theorem.py
678
3.578125
4
## The theorem says that the avg of identically distrubted independent variables ##is roughly normal distributed ## we will use bunomial distribution to draw variable import random from collections import Counter import matplotlib.pyplot as plt def bernoulli_trial(p): return 1 if random.random() < p else 0 def bi...
b261e58249e010d12458977ed343bedaaff35fe2
Dakota-G/PY_Algos
/StringMath.py
1,054
3.921875
4
def stringMath(s): operators = ['+', '-', '*', '/'] ops = [] numbers = [] number = '' for i, x in enumerate(s): if x in operators: numbers.append(int(number)) number = '' ops.append(x) elif i == len(s)-1: number += x numbers...
f575f94ae08397947981d35739440724778a63e6
pinyass/VirusContamination
/epidemic.py
10,096
3.75
4
import math import random import tkinter as tk class Simulation(): def __init__(self): '''initialization''' self.day_number = 1 '''taking population size as input''' self.population_size = int(input('Enter the population size : ')) '''checking if i/p is perfect s...
061caf8d420712a87bcfb8de1de5e9dc04cc64fb
swapnilvishwakarma/100_Days_of_Coding_Challenge
/100.Unique_Binary_Search_Trees_II.py
970
3.9375
4
# Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.le...
dcc3fa5fe118574c066c639fcda4ccf021c7fe51
swapnilvishwakarma/100_Days_of_Coding_Challenge
/20.Spiral_Matrix_II.py
1,047
3.5
4
class Solution: def generateMatrix(self, n: int) -> list: k = 0 # current number x = 0 # x position y = -1 # y position res = [[0 for _ in range(n)] for _ in range(n)] # empty n x n # Set these to opposite of what you want it to be dx = -1 # direction of x ...
52f6a46ea08917aebe01883ed68367c2d14ce62e
swapnilvishwakarma/100_Days_of_Coding_Challenge
/35.Rotate_List.py
1,306
3.953125
4
# Given the head of a linked list, rotate the list to the right by k places. # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: # If no head...
25a9c24ad8507de8e101151fd4f77859b70cc254
swapnilvishwakarma/100_Days_of_Coding_Challenge
/33.Remove_Nth_Node_From_End_of_List.py
750
3.890625
4
# Given the head of a linked list, remove the nth node from the end of the list and return its head. # Follow up: Could you do this in one pass? # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeN...
b79d38e15f0bba9fa6e5ab225370636823d69676
swapnilvishwakarma/100_Days_of_Coding_Challenge
/63.Binary_Search_Tree_Iterator.py
1,825
4.125
4
# Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): # BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number small...
bd0718be25d962ad4bf5c4a923ea590f6a433269
swapnilvishwakarma/100_Days_of_Coding_Challenge
/21.Unique_Paths.py
909
4.0625
4
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the # bottom-right corner of the grid (marked 'Finish' in the diagram below). # How many possible unique paths are there? ...
c8e0590c9c7a9285e6001453726c9fd9794375c3
swapnilvishwakarma/100_Days_of_Coding_Challenge
/69.Decode_String.py
1,148
3.875
4
# Given an encoded string, return its decoded string. # The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. # You may assume that the input string is always valid; No extra white spaces, squar...
b36a29f3627270a6f4ff7fc3be4f088088f13b6b
leminhthu/Oppro
/Data_Requirement/Requirement.py
982
3.828125
4
''' Created on Jun 10, 2015 @author: le_minh_thu ''' import types import datetime class Requirement(object): ''' class Data_Requirement contains the components to be produced, time period and quantity required ''' def __init__(self): self.time = datetime.date.today() self.code = "" ...
e332396373f180c85f85cd5d4bde8e55dad8656b
ssghule/Image-Classification-using-Neural-Networks-and-Adaboost
/image.py
1,548
3.78125
4
#!/usr/bin/env python # Script that contains the Image class class Image: """Object representation of an image """ def __init__(self, line_str): """Constructor that parses a string and stores the fields in the fields :param line_str: line from the training file """ temp_arr...
9f4a33aef6ab559b8cefdc660ba3c40bd15a80d2
bill-neely/ITSE1311-1302-Spring2018
/Python/Zoo/main.py
1,494
3.59375
4
import repository myZoo = repository.makeTheZoo() visitorName = raw_input('Welcome to ' + myZoo.name + '. What is your name? ') while myZoo.stillActive: print '' print 'Your current location is: ' + myZoo.currentLocation.name if myZoo.currentLocation.animal is not None: print ' Animal: ' + myZoo.c...
3c86aca50f88ed3938db2718ce0bc9cc6b53fb55
fredrickochieng/five_commits
/dict.py
264
3.9375
4
menu = {} menu['Chicken'] =100 print menu['Chicken'] menu['Sukuma'] = 60 menu['omena'] = 110 menu['Fish A'] = 300 menu['Lamb rice'] = 150 # Your code here: Add some dish-price pairs to menu! print "There are " + str(len(menu)) + " items on the menu." print menu
ecb4f649857df333f0e339ef16702d05d81e4fb6
heyucongtom/PMSharing_TensorFlow
/Models/downpour_MNIST_train.py
11,655
3.59375
4
""" Mean to experiment downpourSGD on MNIST dataset """ import numpy as np import tensorflow as tf import time from tensorflow.examples.tutorials.mnist import input_data from tensorflow.examples.tutorials.mnist import mnist class DownpourSGDTrainer(object): """ Implement downpour asynchronous stochastic gr...
30c100224896e28d0ca2525125a87486dd4801ec
JialiangHan/Principle-of-Robot-Motion
/Grid-based Algorithm/D-star.py
5,966
3.859375
4
import math import os import time import pygame pygame.init() # trying to reproduce example in principle of robot motion, appendix H, H.3 D* algorithm class Node: def __init__(self, x, y): self.x = x self.y = y self.h = float('inf') self.k = 0 self.t = 'new' self...
c9adf1594efc0c4583389f0dfbe5337e3f47365a
NEHU-Developers-Group/DSA
/Cntb/GhostUser/Python/Merge_Sort.py
1,572
4.125
4
'''Merge sort is a divide-and-conquer algorithm based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element and merging those sublists in a manner that results into a sorted list. Idea: Divide the unsorted list into N sublists, each containing 1 element. Take adj...
e2c54b52c2ec1d8c1692f4afb1cc30b6f9ff3d3b
anhdangfc/Py_Automate_Outreach
/1_Python_Basics/10_Setdefault_Wordcount.py
379
3.90625
4
import pprint as pretty message = 'This is a silly way to do word count but it will help you to understand well the concept' # First create a empty dict count = {} for char in message: count.setdefault(char, 0) # setdefault() to prevent the error, if that key has not existed, add one with zero value count[cha...
3a397afc7758b1bdf07b7d8ab6926a803d8ad62c
anhdangfc/Py_Automate_Outreach
/1_Python_Basics/4_Guess_Games.py
4,297
3.96875
4
import random import sys def compare_message(guess, result): # write the function for repeated tasks if guess > result: if result > 10: bot_line = result - random.randint(1, 10) # add a bottom line to make the game easier else: bot_line = 0 print('Guess some small...
84258ccb7fb1f6a96c332b8df0b3860166b1cc2b
anhdangfc/Py_Automate_Outreach
/1_Python_Basics/14_Table_Printer.py
1,312
4.125
4
#! python3 # 14_Table_Printer.py - Take the list of lists of strings # and displays it in a well-organized table with each column right-justified tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def print_table(...
4a1c9d979f531383dd343af8f3fed264f2b0b9cd
Alejir/machinelearningclassification
/irisplot.py
916
3.84375
4
import matplotlib.pyplot as plt from sklearn.datasets import load_iris iris = load_iris() X = iris.data labels = iris.target_names #Symbols to represent the points for the three classes on the graph. gMarkers = ["+", "_", "x"] #Colours to represent the points for the three classes on the graph gColours = ["blue", "m...
c234bc89d4e5575ff2dc282e177bf55d1cd1f0a8
rasokan/pyway--learning-python
/ex6.py
653
3.984375
4
# code file for ex6 # Strings and Text x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" # str in str 1st y = "Those who know %s and those who %s." % (binary, do_not) print (x) print(y) # str in str 2nd print ("I said : %r." % x ) # str in str 3rd print ("I also said :%r." % y) hilarious ...
87a0a5409c6a5ffae9d67c9cb7669e3f18f697b3
IsaacJW26/JapanesePy
/main.py
719
3.796875
4
import random vowels = ["a", "i", "u", "e", "o"] consants = ["k","g","s","z","t","t","d","n","h","b","p","m","r"] others = ["ya", "yu", "yo", "wa", " "] space = " " new = vowels + consants words = "" syl = " " newRange = int(input("length of text is:")) for ii in range(0, newRange): isOther = random() % 25 if(((isO...
27346b6447be2b6dc065276aaec5dbaad9df8599
mariaIFPB/exercicios-estrutura-de-repeticao-16-40
/questao 36.py
891
4.1875
4
""" questao 36 Desenvolva um programa que faça a tabuada de um número qualquer inteiro que será digitado pelo usuário, mas a tabuada não deve necessariamente iniciar em 1 e terminar em 10, o valor inicial e final devem ser informados também pelo usuário. Montar a tabuada de: 5 Começar por: 4 Terminar em: 7 Vou ...
16bf7d4c8d82804c73fb7ba69e266ca61a72d937
mariaIFPB/exercicios-estrutura-de-repeticao-16-40
/questao 21.py
444
3.9375
4
""" questao 21 Faça um programa que peça um número inteiro e determine se ele é ou não um número primo. Um número primo é aquele que é divisível somente por ele mesmo e por 1. """ a = 2 b= "v" num = int(input(" digite um valor: ")) while ((b== "v") and (a <num)): if((num %a) == 0): b ="f" el...
d7e4c2c18b8ab8d32fdea5ffc35f1de3f0d3e6e5
JaWeyl/python-basics
/xml_lession.py
781
3.5
4
import xml.etree.ElementTree as ET tree = ET.parse("./data/xml_input.xml") # -> ElementTree root = tree.getroot() # -> Element # retrieve Elements by calling 'findall(elementname: str)' for id_, investor in enumerate(root.findall('investor')): # get text value name = investor.text investor.text = name.upper()...
a7dd533f4d24d49c7280a855d3400ec3e1aebe70
dhanraj404/CN_1BM18CS027
/lab12/udp_server.py
765
3.625
4
import socket localIP = "127.0.0.1" localPort = 20001 bufferSize = 1024 serverMsg = "Hello UDP Client!" bytesToSend = str.encode(serverMsg) # Create a datagram socket UDPServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind to address and ip UDPServerSocket.bind((localIP, localPort)) print("The UDP ...
eb756890fa5514d9a473fc72270de8a064367060
Maslan5/python
/Calisma_bir.py
546
4
4
def factorial(n): try: n = int(n) if(n<0): print("Lütfen pozitif bir tam sayı giriniz.") return factorial(input("Lütfen Faktöriyeli Alınacak Sayıyı Giriniz : ")) elif(n==0): return 1 else: return n * factorial(n-1) except ValueErr...
d7068725f3fcc7d04b8e638d8d4970729fc0a5e3
annaebair/parabolic-replicators
/gillespie.py
11,263
3.859375
4
""" Implementation of parabolic replicators on a 2D grid using the basic idea that elements can share the same grid square. """ import math import random import pickle import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.animation as animation from scipy.stats import expon cl...
0accc9bf7034293fdd8cb25fadb8939c2811177f
Att4ck3rS3cur1ty/sundaymornings
/first_n_odd_natural_numbers/first_integers.py
212
4.1875
4
# read the value of n n = input("Type the value of n: ") # shown odd counter i = 0 # output while i < n: print(2*i + 1) i = i + 1 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
54115a1513e828125ea08cba60fa191bc6056a26
RichardcLee/self-made-tools
/director-searcher/lib/utils/getDirectorTree.py
1,069
3.78125
4
''' 获取文件目录 ''' from os import listdir from os.path import isdir, isfile from queue import Queue def get_director_tree(prefix): dirs = Queue() dir_tree = [] current_path = '.' for one in listdir(current_path): # print(one, isdir(one), isfile(one)) if isdir(current_path + '/' + one): ...
834d75b9cc30860f7509fd60f0e63e41240bb618
suratpug/spug
/meetup_6_Jun_2020/script.py
311
3.84375
4
import sys # get arguments from python command line numbers = sys.argv[1:] # summation total = 0 for number in numbers: total += int(number) if __name__ == "__main__": # print output print("program name is:", sys.argv[0]) print("program arguments are:", numbers) print("total is:", total)
745002710bc12c1a48019a25e5b15cd153c1b3e8
SergioGonzalez24/PensameintoComputacionalParaIngenieria
/Ejercicios_EnClase/Ejercicio_if.py
536
4.09375
4
print("Detector de triangulos") while True: a=int(input("Introduce el lado a: ")) b=int(input("Introduce el lado a: ")) c=int(input("Introduce el lado a: ")) if a>0 and b>0 and c>0: if a==b and b==c and c==a: print("Es equilatero") elif (a==b or b==c or c==a): p...
f75a974c837e2aa8bb76e5504ae4ee2bc7462fd4
SergioGonzalez24/PensameintoComputacionalParaIngenieria
/Tareas/Tarea 5/Tarea5.py
2,493
4.15625
4
###Sergio Gonzalez ##A01745446 #Tarea 5 print("") print("Ejercicio 1\n") print("Se requiere repetir una palabra en n cantidad de veces. Genere un programa que pida la palabra y el nu ́mero de veces a repetirla.") def palabra (texto,num): repetir=texto*num return repetir def main(): p=input("Ingrese palab...
62d7436f145e8a190b45b2b53dde0c58a3eb8aa0
SergioGonzalez24/PensameintoComputacionalParaIngenieria
/Quizzes/Quiz de Pogramacion - Listas/Problema 1.py
822
4
4
''' Diseña y codifica un programa en Python en el cual el usuario ingrese la cantidad de elementos que va a ingresar a la lista, posteriormente el programa debe leer cada uno de los elementos de la lista, uno por línea y se van agregando a la lista. Importante: El programa debe validar que el número de elementos a ing...
a50685fec4d021a10a3edbe2da593a15f6c9ba7f
Smerly/Frequency-Counter
/HashTable.py
2,535
4.1875
4
from LinkedList import LinkedList class HashTable: def __init__(self, size): self.size = size self.arr = self.create_arr(size) # 1️⃣ TODO: Complete the create_arr method. # Each element of the hash table (arr) is a linked list. # This method creates an array (list) of a given size a...
527e4dc11dfc9fc4c205435c260cc9474609093f
shrujancheruku/Programming-Studio
/Assignment2.0/Scraper/Scrape.py
3,244
3.65625
4
import logging # logging.basicConfig(level=logging.DEBUG) import requests from bs4 import BeautifulSoup from Scraper import Extract """ Main scraper methods These are to scrape actor and movie pages for further links They call the Extract methods to get more specific information that is then passed to Main """ def ...
e0c14db4f71ef62d6241886c46caa15f295b8dbd
denizgz/bipm
/3_mapper.py
1,704
3.984375
4
#!/usr/bin/env python # Import the sys library # for writing and reading the standard input and output import sys # Example Input data (minipurchase.txt) # Input is tabulator (\t) separated # New Line (\n) indicates a new record. # Input will be piped into the standard input (e.g. with cat on the command line) # Fie...
accc4e7927b46e31a3bd495b39dd5dd4cb62f54a
Tashanam-Shahbaz/DSA_codes
/toweofhanoi.py
236
3.734375
4
def toh(num,first,middle,last): if num==1: print("Move disk from",first,"to",last) return toh(num-1, first, last,middle) toh(1, first, middle, last) toh(num-1,middle,first, last) toh(4,"A","B","C")
030482cd8153c72f4e243b8b074a2138fbdd324f
Tashanam-Shahbaz/DSA_codes
/test_Queues.py
1,517
3.671875
4
# from priorityqueuewithlinkedlist import * # x = [[2, 3], [1, 7], [5, 4], [5, 8], # [1, 4], [3, 1]] # my_pq = priority_queue() # for i in range(len(x)): # my_pq.enqueue(x[i][0], x[i][1]) # my_pq.traverse() # print("removing", my_pq.dequeue()) # my_pq.traverse() # print("removing", my_pq.dequeue()) # my_p...
7704210f8a3acac69ac669d7c27769f1b13c36a0
cooltwin/Big-Integer-Calculator
/BigIntegerCalculator.py
12,831
3.671875
4
# Author: Twinkle Gupta # File Description : This program handles arithmetic operations on large integers of arbitrary size. # Negative numbers are not handled. # Date : Sept 23,2014 import re class ListOperations: # Dictionary (kind of hashmap)to map the variables given in input with their corresp...
3cc25628b1c806e1d86f8ddc3643aeaee5f48c9a
hajarhomayouni/DataStructures
/fill_bag.py
1,726
4.15625
4
def max_duffel_bag_value(cake_tuples, weight_capacity): # We make a list to hold the maximum possible value at every # duffel bag weight capacity from 0 to weight_capacity # starting each index with value 0 max_values_at_capacities = [0] * (weight_capacity + 1) for current_capacity in xrange(weight...
270020fffec66ba9723fe06388d78efc42b8bb24
PCLC7Z2/dissertation
/Do Not Use For MSC Project/functionsCollection.py
4,797
3.75
4
# Functions I will need for my dissertation import pandas as pd import os import numpy as np import sklearn import matplotlib.pyplot as plt import scipy.linalg as scplinag from sklearn.neighbors import KDTree # This will be needed for when I read in a dataset and I want to extract x,y,z and label def ge...
0dbae14a7be0adf4d0094a29834a5d29f042c92f
Collins1738/Minesweeper-solver-AI
/minesweeper.py
13,797
4.34375
4
import itertools import random class Minesweeper(): """ Minesweeper game representation """ def __init__(self, height=8, width=8, mines=8): mines = 14 # Set initial width, height, and number of mines self.height = height self.width = width self.mines = set() ...
6ad0d049ae36519a1b4c83feb979c319b4be8f1a
jmosinski/ml-basics
/ml/linear_models.py
7,897
3.59375
4
import numpy as np from ml import kernels class LinearRegression: """Class representing Linear Regression""" def fit(self, x, y): try: self.weights = np.linalg.solve(x.T@x, x.T@y.reshape(-1, 1)) except: self.weights = np.linalg.pinv(x.T@x) @ x.T @ y.reshape(-1, 1) ...
3aa9e234faa82db5e8ed5c46f7257f8706f1592a
Yangqqiamg/Python-text
/基础学习/python_work/Chapter 7/text.py
2,066
4.15625
4
#one message = input("please input a num: ") print(message) #two name = input("please enter your name: ") print("hello! " + name + ".") #three prompt = "if you tell us who you are, we can personalize the message you see." prompt += "\nWhat is your first name?" name = input(prompt) print(name) #four age = input("How...
f53e15ab68cbd06720f421198f3cd6835daffa22
Yangqqiamg/Python-text
/基本库运用/正则表达式/search_text.py
234
3.640625
4
'''search() 扫描整个字符串,返回第一个匹配合适的选项 ''' import re content = 'Extra stings Hello 12345 7 World_This is a text' result = re.search('Hello.*?(\d+).*is',content) print(result) print(result.group())