blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
acb07a624696275872c60a2d23a7285b8dce9579 | maokitty/IntroduceToAlgorithm | /sort/heapSort.py | 6,269 | 3.59375 | 4 | import sys
class HeapSort(object):
"""核心思想:
堆定义:
可以看做完全二叉树,除最后一层外,其它层都是满的,而且左子树一定比右子树先填满
构建堆
维持堆的特性,以最大堆来讲,左右子节点都要比父节点要小,所以先找到当前节点的子节点最大的下标,如果当前节点不是最大的,则交换
,对交换过的节点再次循环以防堆结构被破坏【被替换节点数】
"""
def __init__(self, toSortFile):
super(HeapSort, self).__init__()
self.tsf = toSortFile
def loadData(self,fileName)... |
2a284c0174789853e2fe4640fba69deefcc3948e | maokitty/IntroduceToAlgorithm | /dataStruction/avl.py | 9,130 | 3.859375 | 4 | import random
class Node(object):
def __init__(self,key,right=None,left=None,parent=None):
self.right = right
self.left = left
self.parent = parent
self.key = key
# 树是单独的结构,BST用来操作BST树,确保BST的性质不会有改变
class AvlBST(object):
"""左子树的值小于父子树的值小于等于右子树的值
最坏情况是:成为一条链
"""
def __init__(self):
self.root = None
... |
0d4412ea1cd2ce514aad59b4c566d525a0b36757 | JorgeLuizAngioleti/gerador-de-datas | /semana.py | 1,171 | 3.5625 | 4 | import datetime
from datetime import date
import calendar
#4 é igual a abril
diasemana = ['Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado','Domingo']
def dia_da_semana(mes, dia_da_semana):
l = []
dia = 1
hj = date.today()
quantos_dias_tem_um_mes = cal... |
14815f912a78a946965ae95dec5bc819240bb63e | cookToCode/PythonConsoleReadingTxtVersion2 | /PythonReadingVersion2/PythonReadingVersion2/PythonReadingVersion2.py | 5,904 | 3.84375 | 4 | #cookToCode
#Written for my final project in beginner python
import csv
##IF YOU DIDNT CHANGE THE TXT FILE DESTINATION ON LINE 69 (lol) THEN IT WONT WORK
#------------Variable Dictionary---------------
numRec=0 #Holds the value of the amount of students on the file
name=[] #List holds the value of the ... |
189b934231f54b5fc3ed8682d87dd87a4584148d | Binaric/Python-Game | /Boss2.py | 1,836 | 3.609375 | 4 | from graphics import *
import pygame
import random
import time
import os
def drawAll(shapes):
for shape in shapes:
shape.draw(win)
def undrawAll(shapes):
for shape in shapes:
shape.undraw()
def colorAll(shapes, color):
for shape in shapes:
shape.setFill(color)
def out... |
387facf0cc473ad5edc097a18c11054c38ea8926 | MatheusPiske/AccuWeatherAPI_APP | /requisicoes_http.py | 658 | 3.5 | 4 | # Fluxo de uma requisição HTTP: Cliente prepara a requisição HTTP, ela vai ser enviada ao servidor, este vai recebê-la e procurar os dados e por fim, enviar a resposta com os dados solicitados.
# Instalação do módulo 'Requests';
# status_code = 200 = OK (REQUISIÇÃO BEM SUCEDIDA);
# 403 = Forbidden: informação prote... |
da94f6330d37a723dea39e9f619e68d7fd3adf5d | psuchta/lstm_stock_prediction | /predictor_program.py | 2,709 | 3.546875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from stock_predictor import StockPredictor
TRAIN_SET_PERCENT = 0.8
X_LABEL = 'Time in days'
Y_LABEL = 'Close price of stock'
def load_file(file_name, columns):
file_data = pd.read_csv(file_name,
... |
5688a17cdc4a6b43bc1eb474015a4dcdef6162a7 | fnava621/euler | /python/p2.py | 542 | 3.96875 | 4 |
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
""... |
f62559306859ec293d74972b8a988f0ed25b98cc | gabrielaRamos/Trabalho-de-IA | /algorithms/utils/union_find.py | 1,056 | 3.65625 | 4 | # Modulo para algoritmo de Disjoint Set - Union Find
class Node:
def __init__(self, id):
self.parent = id
self.rank = 0
class UnionFind:
def __init__(self, size):
self.nodes = list()
for i in range(0, size):
self.nodes.append(Node(i))
def find(s... |
866d94000af5474dd31190273b15f1887c176903 | jack-travis/u_finite_diff | /windmore.py | 2,490 | 3.890625 | 4 | import math
#pyplot needed only for __main__
if __name__ == "__main__":
from matplotlib import pyplot, rc
rc('font', size=12)
#unfortunately not easily generalisable
def wind_speeds(p, y_min, y_max, rho, f, N=10):
"""Calculates the geostrophic wind speeds between altitudes $y_min and $y_max.
Calculati... |
a5c7fa370c57d906e836e7d47d66adc753d2d87d | Tobiasz2817/Laboratorium_Python | /Laboratorium/Lab19/zad2.py | 903 | 3.796875 | 4 | import sys
class Operation_on_file:
def __init__(self):
pass
def LoadFile(self,plik):
row = []
try:
with open(plik, "r") as f:
row = f.readlines()
except FileNotFoundError:
print(f"Brak pliku {plik}")
return row
def Main(... |
cff069a4f4fdbf8c8092f6721d6bdb1fd5b5379d | devstik0407/CS384_1801EE55 | /Projects/P1_Quiz_via_CSV/p1_main.py | 12,428 | 3.515625 | 4 | import time
import os
import sys
import csv
import re
import threading
import keyboard
import sqlite3 as sq3
from tkinter import *
from tkinter import messagebox
if not os.path.exists(os.getcwd()+"\\quiz_wise_responses"):
os.mkdir("quiz_wise_responses")
if not os.path.exists(os.getcwd()+"\\individual_responses... |
e11b7de380e81cbb8b4fcea044294dc8fc5f448f | robertfrontend/Curso-Basico-Python | /for.py | 254 | 3.671875 | 4 | # contador con whle
# contador = 0
# while contador < 1000:
# contador += 1
# print(contador)
# contador con for
# a = list(range(1000))
# print(a)
# for contador in range(1, 101):
# print(contador)
for i in range(10):
print(12 * i) |
1e56c35a796c1f4d76c1dd46f8761da0b49922ee | wang12d/Project-Euler | /pe359.py | 1,118 | 3.609375 | 4 | import time
from math import sqrt, ceil, floor
def floor_number(f, r):
if f == 1:
return r * (r + 1) // 2
k = f - 2
if f % 2 == 0:
k += 1
n = r // 2
if r % 2 == 1:
n += 1
init = f * f // 2
return (2 * n + 2 * k + 1) * (n - 1) + init
else:... |
338f94f012e3c673777b265662403e5ef05a5366 | alyssaevans/Intro-to-Programming | /Problem2-HW3.py | 757 | 4.3125 | 4 | #Author: Alyssa Evans
#File: AlyssaEvans-p2HW3.py
#Hwk #: 3 - Magic Dates
month = int(input("Enter a month (MM): "))
if (month > 12) or (month < 0):
print ("Months can only be from 01 to 12.")
day = int(input("Enter a day (DD): "))
if (month % 2 == 0) and (day > 30) or (day < 0):
print("Incorrect amount of d... |
325d7cd8d88df22471e69456913269a58f5a368d | kenson2998/old_boy_study | /0411_random.py | 545 | 3.9375 | 4 | import random
print(random.random()) # 隨機0~1 浮點數
print(random.uniform(1, 2)) # 可自己設定浮點數區間
print(random.randint(1, 7)) # 隨機1~7 整數, 包含7
print(random.randrange(7)) # range 顧頭不顧尾, 0~7的範圍, 不包含7
print(random.randrange(1,101))
print(random.choice('hello')) # 隨機選擇可傳入可遞歸的東西,'字串',[1,2,3],["hello"]
print(random.sample('hell... |
872c94747aa1edd25b2aff5e29b273b3df4974ad | kenson2998/old_boy_study | /0221_set集合.py | 1,125 | 3.53125 | 4 | list_1 = [1, 3, 5, 7, 2, 4, 6, 8]
list_1 = set(list_1)
print(list_1, type(list_1)) #進行排序, 雖然用大括號包起來,但是它不是字典格式
list_2 = set([0,66,5,4,6,22])
print(list_2)
#交集
print('交集', list_1.intersection(list_2))
print('交集', list_1 & list_2)
#聯集 去重複
print('聯集', list_1.union(list_2))
print('聯集', list_1 | list_2)
#差集 我有你沒有
print('... |
513a99246af3102599f84eaf0a41c77a46ab83c3 | kenson2998/old_boy_study | /0526_私有屬性__屬性.py | 585 | 3.515625 | 4 | class Person:
def __init__(self, name):
self.name = name
self.__life_value = 100 # 私有屬性
def got_shot(self):
print('中槍 -50HP')
self.__life_value -= 50
def show_status(self):
print('HP : %s' % self.__life_value)
def __shot(self): # 私有方法
print('%s 開槍' % ... |
2c904ee99c5732b5cb79e6edaccd4536b31810be | Lcarrico/PythonChallenges | /temp_calculator.py | 648 | 3.984375 | 4 | import unittest
# write a method that allows you to convert the temperature using key word arguments
# example calculate_temp(temp =100, original='C', to="F") -> 212
def calculate_temp(**kwargs):
pass
########################### TESTS ##############################################################
class TestMethod... |
20033e39475231f9b359b0b1e867e689344a0d8f | thallesgomes/Curso-de-Python | /Exercícios/Exercício 058.py | 2,726 | 3.859375 | 4 | print('\n\033[1;7;30m {:=^150} \033[m\n'.format(' | EXERCÍCIO PYTHON 058 - JOGO DA ADVINHAÇÃO (2.0) | '))
# ========================================================================================================================= #
from random import randint
computador = randint(0, 10)
print('Sou seu computad... |
9b6bc3cf87827d2755d3081e398948a790bcd73d | khezam/algos_ds | /review/hashTable/stringHashing.py | 9,700 | 4.5625 | 5 | """
For a string, say `abcde`, a very effective function is treating this as number of prime number base `p`.
Let's elaborate this statement.
For a number, say `578`, we can represent this number in base 10 number system as 5*10^2 + 7*10^1 + 8*10^0$$
Similarly, we can treat `abcde` as a * p^4 + b * p^3 + c * p^2 + ... |
19db17d07c1cfeed462f97596745e307cea7f27b | khezam/algos_ds | /review/stack/stack.py | 2,157 | 3.75 | 4 | class Array:
def __init__(self, size):
self.stack = [ None for _ in range(size)]
class Stack:
def __init__(self, size):
self.stack = Array(size).stack
self.top = -1
def is_empty(self):
return self.top == -1
def push(self, element):
self.stack[self... |
8a86ad5425b0f50787cd0e7effd4891f2b04cea2 | khezam/algos_ds | /review/graph/dijkstraDistance.py | 5,068 | 3.78125 | 4 | class GraphNode:
def __init__(self, element, weight):
self.element = element
self.weight = weight
self.next = None
class Graph:
def __init__(self):
self.graph = {}
def traverse(self, node):
while node.next:
node = node.next
retur... |
899249000f86520637a3d27670ec140bbc436584 | khezam/algos_ds | /review/BST/BST.py | 9,740 | 3.828125 | 4 | class Node:
def __init__(self, element):
self.element = element
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def _add(self, node, new_node):
if node.element < new_node.element:
if node.ri... |
f36d2e98e033c3ada5246820d165c5f6fe9132ef | vikasz1/sample | /rhythmlist.py | 203 | 4 | 4 | list = []
# for x in range(7):
# a = int(input("Enter number:"))
# list.append(a)
# print(list)
# max_value = max(list)
# print(max_value*min_value)
a = 8
b = 9
print(a*b)
print("8*9") |
35ffd80d2cc170f349fb5a2eaedccd57199f0fb8 | aayushmnit/Algorithms | /karatsuba_multiplication.py | 1,143 | 3.984375 | 4 | def AddZeros(x, n, left=True):
"""
x is a string
n is number of zeros to be added
left true meaning leading zeros, false meaning lagging zeroes
"""
if left:
return str(0) * n + x
else:
return x + str(0) * n
def KaratsubaMultiplier(x, y):
## Convert x and y to string for... |
5f9025c27c752d521fa778f953c8962e18e2d6b4 | isabellacai/text-based-poker | /Blackjack.py | 1,778 | 3.5 | 4 | from random import shuffle
# poker_queue = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
spade = "\u2660"
heart = "\u2665"
diamond = "\u2666"
club = "\u2663"
class Dealer(object):
def __init__(self, arg):
self.arg = arg
class Player(object):
def __init__(self, arg):
se... |
cd70b992f1b64cafe8c6d14f1ba3a90a245ac390 | kaluabd/NisirBuster | /Nisirbuster_updated.py | 341 | 3.578125 | 4 | import requests
url = input("Enter the URL: ")
wordlist = input("Enter the path to the wordlist: ")
with open(wordlist) as f:
for line in f:
directory = line.strip()
full_url = url + "/" + directory
r = requests.get(full_url)
if r.status_code == 200:
print("[+] Director... |
852629017ffcf42592c1b87c33f3eee81961f5d0 | kcdriod/Fun-with-python- | /Password_generator.py | 296 | 3.90625 | 4 | import random
char ="qwertyuiopasdfghjklmnbvcxz1234567890"
no_pass =input("enter no of passwords you need")
digit =input("enter no of digits :")
no_pass =int(no_pass)
digit = int(digit)
for p in range(no_pass):
password = ''
for c in range(digit):
password += random.choice(char)
print(pass... |
076ddf62f1a91c88629654c356a2ad5dc8f343f5 | Kose-i/machine_learning_tutorial | /BayesMachineLearning/Distribution/binomialPlot.py | 344 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from math import factorial
M = 10 # 全体の試行回数
ave = 0.3
def comb(n, r): # nCr
return factorial(n) / factorial(r) / factorial(n - r)
def binomial(x):
return comb(M, x)*(pow(ave, x))*(pow(1-ave, M-x))
x = range(0,10,1)
x = np.array(x)
plt.plot(x, binomial(x))
p... |
300be693adc2e47e761ad5f22d90a4307a5b94df | Shubhangidixit/word2vec | /selectSentenceAlign.py | 1,346 | 4 | 4 |
import re
import itertools
def selectSentence():
engSentence = raw_input('Enter the name of English sentence file : ') # English file
hindiSentence = raw_input('Enter the name of Hindi sentence file : ') # Hindi file
word = raw_input('Enter the word whose sentences you want : ') # Word ... |
06f440220d432000176c0f8cd8b5931e4ee0db37 | Sona-aroraa/casimir_course | /test.py | 409 | 3.953125 | 4 | import numpy as np
print("Hello world")
def circumference(radius):
'''calculating the circumference of a circle
'''
return 2*np.pi*radius
# some more
# some text from hanifa
def surface(radius):
'''This fucntion calculates the surface of the circle
: param float radius : radius of the given circle
... |
de73def3f3cceea8711dcb87170beab4fe64c5b0 | JasonDClarke/codingground | /New Project-20170705/editDictionary.py | 709 | 3.828125 | 4 | def editDictionary(dictionary, currentKey, nextKey, keyToAdd):
#if know value of next key, write value of new key as current value plus first character of next value
if (dictionary[nextKey] != None):
dictionary[keyToAdd] = dictionary[currentKey] + dictionary[nextKey][0]
#if don't know value of next ... |
a25867eabd287bd0aad779279a3bcbe0930290ee | alexandrelff/mundo1 | /ex018.py | 510 | 4.0625 | 4 | #Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
import math
angle = float(input('Digite um ângulo:'))
seno = math.sin(math.radians(angle))
cosseno = math.cos(math.radians(angle))
tangente = math.tan(math.radians(angle))
print('Para o ângulo {}, o seno é {... |
15ab75166ff2c852821d9c4dadb563a30a9295f3 | alexandrelff/mundo1 | /ex011.py | 453 | 3.921875 | 4 | #Faço um programa que leia a largura e a altura de uma parede em metros, calcule a sua área
#e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m²
l = float(input('Digite a largura da parede: '))
a = float(input('Digite a altura da parede:'))
t = (l * a) / 2
print('A... |
ef8b3da9c09b5ca1ceb6acc12bd70209fa6dac39 | alexandrelff/mundo1 | /ex035.py | 420 | 4.15625 | 4 | #Desenvolva um programa que leia o comprimento de trÊs retas e diga ao usuário se elas podem ou não formar um triângulo
r1 = int(input('Digite o valor da reta 1: '))
r2 = int(input('Digite o valor da reta 2: '))
r3 = int(input('Digite o valor da reta 3: '))
if (r1 < r2 + r3) and (r2 < r1 + r3) and (r3 < r1 + r2):
... |
d584af670ec4e3b425c3c02405ce9f863cfafa19 | L200183174/Praktikum-7 | /PRAK7.AZI.py | 1,371 | 3.796875 | 4 | #Activity 1
d = {'Triangle' : 'L = 0.5 * a *t',
'Square' : 'L = s ** 2',
'Rectangle' : 'L = p * l',
'Circle' : 'L = pi * r ** 2',
'Parallelogram' : 'L = a * t'}
print '''
|No|Nama Bangun |Rumus Luas |
|--|------------------|-----------------|
|1 |Triangle |%s
|2 ... |
3b0f3bd8d100765ae7cb593a791c9f2908b1ce76 | rossvalera/inf1340_2015_asst2 | /exercise1.py | 2,159 | 4.1875 | 4 | #!/usr/bin/env python
""" Assignment 2, Exercise 1, INF1340, Fall, 2015. Pig Latin
This module converts English words to Pig Latin words
"""
__author__ = 'Sinisa Savic', 'Marcos Armstrong', 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
def pig_latinify(w... |
2591ae068b28c4d9e92470dd0348fabd32ee814a | CooperMetts/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 852 | 4.25 | 4 | """Numeric operators practice."""
__author__ = "730336784"
number_one: int = int(input("Pick a number "))
number_two: int = int(input("Pick another number "))
number_one_to_the_power_of_number_two: int = number_one ** number_two
number_one_divided_by_number_two: float = number_one / number_two
number_one_int_divide... |
a00293978a88a612e4b7a3ea532d334f43a279d5 | CooperMetts/comp110-21f-workspace | /sandbox/dictionaries.py | 1,329 | 4.53125 | 5 | """Demonstrations of dictonary capabilities."""
# Declaring the type of a dictionary
schools: dict[str, int]
# Intialize to an empty dictonary
schools = dict()
# set a key value pairing in the dictionary
schools["UNC"] = 19400
schools["Duke"] = 6717
schools["NCSU"] = 26150
# Print a dictonary literal representati... |
1aec324bec1147ff71846098f216a3ed99ff1a63 | CooperMetts/comp110-21f-workspace | /exercises/ex04/utils.py | 1,019 | 3.859375 | 4 | """List utility functions."""
__author__ = "730336784"
# TODO: Implement your functions here.
# from random import randint
# y: int = int(input("Enter a number: "))
# x: list[int] = [randint(0, 9), randint(0, 9), randint(0, 9)]
def all(x: list[int], y: int) -> bool:
if len(x) == 0:
return False
... |
125508563af213622772d1d6bb1c72dd94aa10f8 | mkukushkin2004/oop | /4_incapsulation/module.py | 1,034 | 3.9375 | 4 | from Point import Point
p1 = Point(5, 10, "red") # создаю объект
p1.name = "Ben" # имя меняю без проблем, что хочу, то и ворочу
delattr(p1, 'name') # удаление атрибута не проходит
del p1 # удаление точки
try:
pt2 = Point(-1, -1, "red") # пытаемся создать некорректную точку
except AttributeError:
print("... |
ae27d1a22c8b7fc0d80e7a019be35c1547186104 | mkukushkin2004/oop | /1_exceptions/11.py | 239 | 3.96875 | 4 | a = 3
b = 5
if a > b:
print("a больше b")
elif a == b:
print("a равно b")
else:
assert a < b # когда уверены, что что-то точно должно быть верно
print("a меньше b")
|
051b1a14170a5530925807ecb2c34649921f1ecd | Aliases/Sundar | /fibonacci-heap-mod-0.99/test.py | 131 | 4.09375 | 4 | #mylist=[]
"""mylist.append(1)
mylist.append(2)
mylist.append(3)
for x in mylist:
print x """
mylist=[1,2,3]
print(mylist[10])
|
8d45eb1e80bf7fa7867e94c6ff2323585b505c83 | blindly/rename.py | /rename.py | 348 | 3.515625 | 4 | #!/usr/bin/env python
import os
path = os.getcwd()
filenames = os.listdir(path)
count = 0
for filename in filenames:
filename_array = filename.split('-')
if len(filename_array) > 1:
new_filename = filename_array[0]
os.rename(filename, new_filename)
count = count + 1
print("%s files ... |
c43803e74388aae900b2d7a070ecc171809a1172 | rohanawale/E_tax_with_MySQL | /Assembly Files/edd project modules/startup login file for application.py | 345 | 3.8125 | 4 | import sys
import tkinter
import tkinter.messagebox
a = input("Enter username : \n")
b = input("Enter Password : \n")
if a!="pranesh67" or b!="Pass@123":
tkinter.messagebox.showwarning("Login Page","The username or Password is incorrect");
sys.exit(0)
else:
print("### write the whole program here w... |
efd42d1f1de431bf68509120a3165564df3e4871 | kta95/CS50-Python | /pset6/cash/cash.py | 566 | 3.78125 | 4 | def convert(value):
cent = round(value * 100)
coin = 0
while True:
if cent == 0:
break
elif cent >= 25:
cent -= 25
coin += 1
elif cent >= 10:
cent -= 10
coin += 1
elif cent >= 5:
cent -= 5
coi... |
e236f513da99f4240730078536ad637cb6bd8ee0 | hvr9/lab | /L5-BinarySearchUserFunDynInput.py | 771 | 3.703125 | 4 | """Harsha vardhan reddy
121910313001"""
#Binary search using dynamic inputs nd functions
def dynamic_input():
print("enter the elements:")
for i in range(n):
a=int(input())
ar.append(a)
return ar
def binary_search(s):
if(ar[mid]==s):
print("ele is found in",mid)
#c... |
2562fd81964a2d07744253ecbd3b7aa65d56e9fa | hvr9/lab | /L5-LinearSearchDynamicInput.py | 349 | 3.96875 | 4 | # Linear search of an array using dynamical input
n=int(input())
ar=[]
print("enter the elements:")
#taking array inputs dynamically
for i in range(n):
a=int(input())
ar.append(a)
#search element
s=int(input("enter an ele to search:"))
l=len(ar)
for i in range(l):
if(ar[i]==s):
prin... |
60bb77baa163904b88d3f61c741526ebacd06c32 | hvr9/lab | /L2.amstrong.py | 215 | 3.890625 | 4 | #amstrong number
n=int(input("enter the number:"))
count=0
dup=n
while dup>0:
r=dup%10
count+=r**3
dup//=10
if(n==count):
print("amstrong num")
else:
print("not an amstrong num")
|
e4b58179035b23968dc218fd024dda2a4041be8a | hvr9/lab | /L6-4.LinkedList(Add@end).py | 1,115 | 4.09375 | 4 | """Harsha vardhan reddy
121910313001"""
#Inserting a node at the end of the Linked List
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def append(self,data):
... |
65c9b5cc420f86fabace5b966594b7891ca2b490 | hvr9/lab | /L6-1.linked_list.py | 766 | 3.859375 | 4 | """Harsha vardhan reddy
121910313001"""
#Create a linked list with few sample nodes as static inputs
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
def listprint(self):
printv =... |
2ecb8c9c4caa9a7c7f0ef451c5ed82cf5a710260 | franco-ruggeri/kth-artificial-neural-networks | /Lab 2/lab2/som.py | 4,800 | 3.6875 | 4 | import numpy as np
import math
def manhattan(x, y):
"""Manhattan distance."""
return abs(x[0] - y[0]) + abs(x[1] - y[1])
def _neighbourhood_1d(winner, n_nodes, neighbourhood_size, circular):
"""Get neighbourhood, represented as indexes, of a node. The node itself is included. 1D version."""
idx_min,... |
abf569ffd06cc233fa5e19becfcd0ea00e9364d5 | anuj8june/submissions | /Question_Python/question1_part1.py | 289 | 4.0625 | 4 |
L1 = ['a', 'b', 'c']
L2 = ['b', 'd']
# For common elements
print("For finding common elements")
for val in L1:
if val in L2:
print(val)
# For non common elements
print("\n For non-common elements")
L3 = L1 + L2
for elem in L3:
if (elem not in L1) or (elem not in L2):
print(elem) |
dfc1f845726dc98fabf842d1d404d5ad08342337 | danielmorgan/grokking-algorithms | /recursive_sum.py | 416 | 3.78125 | 4 | # My solution, manipulate array and pass it down
def sum(arr, total = 0):
if (len(arr) == 0):
return total
else:
num = arr.pop()
total += num
return sum(arr, total)
print(sum([1, 2, 3, 4, 5, 5, 1])) # 21
# Terser solution from book
def sum_answer(list):
if list == []:
... |
c5ebaf4cf159ec72da02d5bf601dd0dc7c15a09f | ElenaCasado/Python | /prueba_exmanen_antonio.py | 1,247 | 3.96875 | 4 | # 1. diferencia entre variable contadora y acumuladora.
La diferencia entre un contador y un acumulador es que mientras
el primero va aumentando de uno en uno, el acumulador va aumentando
en una cantidad variable.
# 2.
#a.
def hago_algo():
x=input("Dime un numero ")
y=0
for cont in range(0,10,1... |
c9cb82aef7589e657b85b556a3d33d1fa959b9d7 | ElenaCasado/Python | /18.sumador_digitos.py | 789 | 3.90625 | 4 | def sumador_digitos():
numero=input("Dime un numero de dos digitos:")
decenas=numero/10
unidades=numero - 10*decenas #n%10#
print "La suma de",numero,"vale",decenas+unidades
sumador_digitos()
def sumador_cifras():
suma=0
numero=input("Dime un numero: ")
while numero>10:
... |
975964be9b282973ce0203ef569a2d3360af4fc9 | jindy-mine/pythonStudy | /1-数据类型/元组.py | 226 | 4 | 4 | """
=========================================
Author:薄咊
Time:2020-10-16 15:11
comments:python学习
==========================================
"""
tu1 = ("222","333",111,[333])
print(tu1)
res = tu1.index("222")
print(res) |
39ff2b1b4510a2e1f1765f91434e87d5dc125a56 | jindy-mine/pythonStudy | /2-控制流程/条件循环while.py | 1,157 | 3.90625 | 4 | """
=========================================
Author:薄咊
Time:2020-10-18 15:34
comments:python学习
==========================================
"""
"""
while应用:打印100遍hello python:
"""
# 创建一个变量用来保存循环次数
# n = 0
#
# while n < 100:
# print("hello python")
# n += 1
# print("这是第{}遍执行".format(n))
"""
死循环的应用:用户输入用户名或密码... |
6802efb889d2398af5e4eb31a15b4c3e1005d959 | accmohamedsaber/HackerRank19 | /BFSShortestReachInAGraph.py | 1,492 | 3.890625 | 4 | # HackerRank-19 by Alina Li Zhang
## HackerRank-19: Coding Interview Questions with Python Solutions and Explanations
### https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem
'''
unit test:
1
4 4
1 2
2 3
3 4
2 4
1
'''
class Graph(object):
def __init__(self, n):
self.num_nodes = n
... |
4b52b653fc336ea7a4accb86784eed79374f1cf9 | RgTheGreat/My-Python | /pandas_file1.py | 130 | 3.59375 | 4 | import panda as ps
data = {
'person1': ["Tim", "Marck", "Feranses"],
'ages': [13, 10, 8]
}
x = pd.DataFrame(data)
print(x)
|
9c909a7ff5cb0f07e1ae51cfa4728ca54ccebd04 | RgTheGreat/My-Python | /new_login.py | 793 | 3.734375 | 4 | a = input("Enter your name: ")
b = input("Enter your password: ")
c = input("Enter your age(in letters): ")
data = {
"username": a,
"password": b,
"age": c
}
class fail:
def __init__(self, exception, prevent):
self.exception = exception
self.prevent = prevent
def printError(self):
... |
0650f6a355bb7cdc9f33bc18c06f86d4cbe3a93d | semihamakinist/AdvancedPY | /Advanced/1_Magic_Methods-Dunder.py | 1,074 | 4.03125 | 4 |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __del__(self): # sınıfi otomatik sisler
print("Nesne silindi")
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self... |
aac305e8b25576b10e2e7431ad6b06cbbbe5c3ef | JonasSatkauskas/codewars | /Regex_PIN.py | 1,031 | 4.03125 | 4 | # Regex validate PIN code
'''ATM machines allow 4 or 6 digit PIN codes
and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.'''
import re
def validate_pin(pin=str):
#return true or false
listas = []
... |
590cab46ee48d2e7380fd4025683f4321d9a1a34 | dipak-pawar131199/pythonlabAssignment | /Introduction/SetA/Simple calculator.py | 642 | 4.1875 | 4 | # Program to make simple calculator
num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
ch=input(" Enter for opration symbol addition (+),substraction (-),substraction (*),substraction (/), % (get remainder) and for exit enter '$' ")
if ch=='+':
print("Sum is : ",num1+num2)
... |
86c83cf3af2c57cc3250540ec848a3d5924b6d4b | dipak-pawar131199/pythonlabAssignment | /Functions/Sumdigit.py | 691 | 4.15625 | 4 | ("""
1) Write a function that performs the sum of every element in the given number unless it
comes to be a single digit.
Example 12345 = 6
""")
def Calsum(num):
c=0;sum=0
while num>0: # loop for calcuating sum of digits of a number
lastdigit=num%10
sum+=lastdigit
... |
df13a154e79b15d5a9b58e510c72513f8f8e2fa0 | dipak-pawar131199/pythonlabAssignment | /Conditional Construct And Looping/SetB/Fibonacci.py | 550 | 4.1875 | 4 | '''4) Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
a. 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
b. By considering the terms in the Fibonacci sequence whose values do not exceed
four hundred, find the sum of the even-valued t... |
3fed76f86fd479b36817644905f85f4fcdf7da82 | efloti/plc_nsi_algo | /algo/struct/files.py | 4,727 | 3.6875 | 4 | from algo.struct.liste_simple import Liste
class File1:
""" File implémentée sur la base d'une liste chainée simple"""
def __init__(self):
"""Création d'une file vide."""
self.__liste = Liste()
def __len__(self):
"""Renvoie la longueur de la file."""
return len(self.__lis... |
5fc5396b4c900bc48b91d0372b80b273155ee93e | joseph-palermo/ICS3U-Unit3-02-Python | /number_game.py | 435 | 4.09375 | 4 | #!/usr/bin/env python3
# Created by: Joseph Palermo
# Created on: Sep 2019
# This program adds integers
import constants
def main():
# This function asks the user to guess the number
# Input
guess = int(input("Guess the number between 1 & 9 (integer): "))
print("")
# process
if guess == c... |
4a453b7afce6666eaab110004375ffed334e8884 | Chito-XD/proyectoCompiladores | /utils/queue.py | 794 | 4 | 4 | class Queue:
# FI FO
def __init__(self):
self.array = []
# Return true/false wheter the queue is empty or not
def isEmpty(self):
return len(self.array) == 0
# Look last first element of the queue
def peek(self):
if len(self.array) > 0:
return... |
3d317d2d7b0a09f26f99fdf1fd3e5f0e9043b4e4 | langzippkk/Machine_learning_algo | /CNN_hw5/HW5_yinian.py | 28,212 | 3.75 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data import sampler
from torch.utils import data
import torchvision.datasets as dset
import torchvision.transforms as T
import numpy as np
import pandas as pd... |
523c19dfab3772eb55e482e4ee10aca49ac8b337 | benjammin12/NBA_Sentiment_Analysis | /nba_sentiment/nba_game_data.py | 1,533 | 3.640625 | 4 | import requests
import nba_py
from nba_py import player
import json
# URL = http://stats.nba.com/stats/playergamelog?PlayerID=2544&LeagueID=00&Season=2017-18&SeasonType=Regular+Season
#data = requests.get('http://stats.nba.com/stats/playergamelog?PlayerID=2544&LeagueID=00&Season=2017-18&SeasonType=Regular+Season')
c... |
6c98981700265a8492db78e6f80b2cba170d743e | teslastine08/py_nielit | /programs/remove duplicasy.py | 258 | 3.5625 | 4 | from array import *
a=array('i',[])
n=int(input("enter array size: "))
for i in range (n):
a.append(int(input()))
for i in range(n):
for j in range(n):
if(a[j]==i+1):
a.remove(a[i])
a[j]=a[i-1]
n=n-1
print(a)
|
cfde2adc2b3c5feaf15a41efd3d0615d7ac5f5c5 | teslastine08/py_nielit | /programs/circle.py | 105 | 4.0625 | 4 | x=int(input("enter the radius"))
a=(3.14*(x**2))
c=(2*3.14*x)
print("area:",a)
print("circumference:",c)
|
8ded1fc0d57b5bfe9367b900fe64e384b43bdcd1 | qtov/fund_prog | /w4-6/UI/validate.py | 199 | 3.609375 | 4 | def is_in_range(_var, start, end):
if (_var < start or _var > end):
return (0)
else:
return (1)
def is_in_list(_var, _list):
for elem in _list:
if (elem == _var):
return (1)
return (0)
|
7b42f2e89c6f315f5f131d0fd5f4aa478b84815f | qtov/fund_prog | /w12-13/backtrack_recursiv.py | 480 | 3.65625 | 4 | lst = [5, 4, 1, 5, 1, 2, 7, 5, 3, 4, 5, 6]
def backtrack(lst, aux_list, pos, i):
if (pos < len(lst)):
if (len(aux_list) == 0):
aux_list.append(lst[pos])
print(aux_list)
else:
if (i < len(lst) and lst[i] > aux_list[len(aux_list) - 1]):
aux_list.append(lst[i])
print(aux_list)
else:
aux_list ... |
50c24380c83e830a71b055176134b985e8eb3c0a | qtov/fund_prog | /w12-13/quicksort.py | 655 | 3.8125 | 4 | # Worst case performance O(n^2)
# Best case performance O(n * log (n))
# Average case performance O(n * log(n))
unsorted_list = [5, 6, 7, 2, 3, 4, 1, 0, 23, 41, 21, 6, 5, 4, 2, 3, 3, 4, 1]
def quicksort(lst, lo, hi):
if (lo < hi):
p = partition(lst, lo, hi)
quicksort(lst, lo, p - 1)
quicksort(lst, p + 1, hi)
... |
10e021531d1b56e1375e898e7599422de0ce5c9a | RobStepanyan/OOP | /Random Exercises/ex5.py | 776 | 4.15625 | 4 | '''
An iterator
'''
class Iterator:
def __init__(self, start, end, step=1):
self.index = start
self.start = start
self.end = end
self.step = step
def __iter__(self):
# __iter__ is called before __next__ once
print(self) # <__main__.Iterator object at 0x0000014... |
689a07485583b46451ef2a6bea3a7b4d04c8f420 | UPB-FILS/sde | /tp/tp02/ex6.py | 360 | 3.796875 | 4 | bd = {
"Sara": "12345",
"Maria": "54321",
"Alexandra": "23415",
"Teodora": "34125"
}
name = input("Please enter a name: ")
while name != "stop":
try:
print (bd[name])
name = input("Please enter a name: ")
except KeyError:
print ("Je ne connais pas cette personne")
... |
a89029373c74700a61a122d0aaf6e72b23111f69 | ninja8173/pgame | /tic tac toe/ttt03.py | 735 | 3.671875 | 4 | #보드 출력 함수
def prn_board(tb):
for x in range(3):
print("{}|{}|{}".format(tb[x][0], tb[x][1], tb[x][2]))
print("-"*5)
#보드 초기화
turn = 'X'
board = [[' ', ' ',' '],
[' ', ' ',' '],
[' ', ' ',' ']]
#보드 출력
prn_board(board)
#9회 입력받기
for x in range(9):
# 입력 좌표가 동일하면 재입력받기
while Tru... |
d18f9b723d9b29d1e2c266561e7dc49b8787cbbf | cxc1357/PythonBasic | /deleteBSTNode.py | 3,068 | 3.703125 | 4 | # day60:删除二叉搜索树某节点
# 给定root和key,删除key对应的节点,保证二叉搜索树性质不变
# 时间复杂度为O(h),h为树高度
# 1.key小于root,在左子树中查找
# 2.key大于root,在右子树中查找
# 3.key等于root,分4种情况
# 1) root无子树,摘除root,返回None
# 2) root仅有左子树,删除root,返回root.left
# 3) root仅有右子树,删除root,返回node.right
# 4) root有左右子树,删除root,以右子树的最小节点[代替]被删除的节点
# 这里的[代替]指值代替,不破坏原先的左右节点关系
class So... |
8a2138e3a3fbdc53bcd279d41ccf54a9a9853d7e | cxc1357/PythonBasic | /numWaterBottles.py | 517 | 3.6875 | 4 | class Solution:
def numWaterBottles(self,numBottles,numExchange):
sumb = numBottles
empty = numBottles
# 只要还能换就继续
while empty // numExchange:
# 每轮兑换数
bottle = empty // numExchange
# 每轮空瓶数
empty = bottle + empty % numExchange
... |
21b288f0a1e0143f6eaa9369dbe90eb6c3a472b3 | cxc1357/PythonBasic | /findMaxLength.py | 741 | 3.53125 | 4 | # day50:连续数组
# 找到含有相同数量0和1的最长连续子数组
# i = 0 1 2 3 4 5
# [0,0,0,1,1,1]
# c = 1 2 3 2 1 0
# d = {c:i}
# maxlen = max(maxlen,i-d[count])
# i=1时c=2,而当i=3时c再次=2,说明中间经过的0、1抵消
class Solution:
def findMaxLength(self,nums):
count,maxlen=0,0
d = {0:-1}
for i,num in enumerate(nums):
if nu... |
996e4d1afeaabf0db255a9a5226587e537d515d5 | cxc1357/PythonBasic | /groupAnagrams.py | 723 | 3.859375 | 4 | # Day10:异位词分组(哈希表键的设计)
class Solution:
def groupAnagrams(self,strs):
dict={}
for s in strs:
# 将字符串排序后的元组作为哈希表的键
# >>> sorted("bca")
# ['a', 'b', 'c']
# >>> tuple(sorted("bca"))
# ('a', 'b', 'c')
key = tuple(sorted(s))
... |
f7f66675b5965074e14a6771a65a45c89df10e56 | OMEGA-Y/CodingTest-sol | /solution/2920(음계).py | 160 | 3.953125 | 4 | num = list(input().split())
if sorted(num) == num:
print('ascending')
elif sorted(num,reverse=True) == num:
print('descending')
else:
print('mixed') |
9587d4c9669d1f855e95f46fc2dbaf8bd365e454 | OMEGA-Y/CodingTest-sol | /solution/11653(소인수분해).py | 458 | 3.609375 | 4 | N = int(input())
num = N
for i in range(2,N+1):
while not num%i:
print(i)
num = int(num/i)
'''처음 풀이 - 시간이 너무 오래 걸림
nums = [False,False] + [True] * (N-1)
for i in range(2, int(N**0.5)+1):
if nums[i]: #True
nums[i*2::i] = [False] * ((N-i)//i)
prime = [idx for idx,val in enumerate(nums) ... |
bf84cbfbda23494b11247255207a3df440614cc2 | OMEGA-Y/CodingTest-sol | /solution/4153(직각삼각형).py | 290 | 3.71875 | 4 | import sys
input = sys.stdin.readline
def isRight(a,b,c):
if a == b+c or b == a+c or c == a+b:
return 'right'
return 'wrong'
while True:
a,b,c = map(int,input().split())
if a==0 and b==0 and c==0:
break
a,b,c = a**2,b**2,c**2
print(isRight(a,b,c)) |
7f825d0014700d5473fae1c2472a3d8ddd3e12a3 | OMEGA-Y/CodingTest-sol | /solution/1259(팰린드롬수).py | 255 | 3.609375 | 4 | import sys
def palindrome(num):
l = len(num)
for i in range(0,l//2):
if num[i] != num[l-i-1]:
return 'no'
return 'yes'
for line in sys.stdin:
if line.rstrip() == '0':
break
print(palindrome(line.rstrip())) |
ac5fc46db8b7a22d4a205aa475b521b8fc46c40c | derados/ucimo-algoritme | /racunanje/fibonaci.py | 245 | 3.875 | 4 | def fibo(n):
if n == 0:
result = 0 #Base case
elif n == 1:
result = 1 #Base case
else:
result = fibo(n-1) + fibo(n-2) #Feeding the 'output' right back into the input function
return result
print fibo(10)
|
a8bb0fe28b33c92c91491b0f90605dd9beb64a21 | iaroslav-ai/recurrent | /RecurrentNeuralNetworks/rnn_py.py | 1,624 | 3.609375 | 4 | '''
Created on Oct 16, 2015
@author: Iaroslav
'''
import numpy as np
# Simple RNN
class RNN:
training = False; # collect data for gradient computation when true
def __init__(self, xsz, ysz, neurons_per_block):
self.W = np.random.randn(neurons_per_block+xsz+ysz+1, neurons_per_block)*0.001
self.... |
022c9d704c064ed0332b7f1b185168325ee66a93 | Soalni/Python | /family_member.py | 955 | 4.0625 | 4 | my_family = []
my_family.append(input("What`s your name: ").title()) #Call name
select = input("Have you got family? (Y/N)").upper() #Select family
if select == "Y": #Start call name of family
my_family.append(input("OK. What is the first member`s name of your family: ").title())
select = input("Have you go... |
9de5002aa797d635547bb7ca1989a435d4a97256 | altvec/lpthw | /ex32_1.py | 571 | 4.46875 | 4 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count {0}".format(number)
# same as above
for fruit in fruits:
print "A fruit of type: {0... |
851f8d3ac4d4139b4873a4050e4ecbc0ba323a8a | bivanalhar/rec_problem | /generate_fake_test.py | 7,373 | 3.640625 | 4 | """
This code is purposed to generate the fake test data
that will be used to have their result shown, just to know how
good the network actually is in evaluating randomized data
"""
import csv
import random
import numpy as np
import scipy.stats as sp
num_users = 20000
#Step 1 : Extract the CSV file
#The objective h... |
2a68475d690917f955097217034944f257dab320 | AshKnight99/Leetcode-problems | /Prob912.py | 1,094 | 4.09375 | 4 | """
912. Sort an Array
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
"""
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return self.quicksort(nums... |
342ce6f3d5820f99a0ab3a5cea36c4e7a2e295f1 | PacktPublishing/Software-Architecture-with-Python | /Chapter06/print_employee.py | 687 | 3.953125 | 4 | # Code Listing #13
"""
Printing using %s vs printing using .format
"""
def display_safe(employee):
""" Display details of the employee instance """
print("Employee: {name}, Age: {age}, profession: {job}".format(**employee))
def display_unsafe(employee):
""" Display details of employee instance """
... |
118cbbeb2421a290e47b528be7257ce5e722644d | PacktPublishing/Software-Architecture-with-Python | /Chapter03/test_datetimehelper2.py | 1,752 | 3.796875 | 4 | # Code Listing #5
""" Module test_datetimehelper - Unit test module for testing datetimehelper module """
# Note - This is the second version of test_datetimehelper module so named as test_datetimehelper2.py
import unittest
import datetime
import datetimehelper
from unittest.mock import patch
class DateTimeHelper... |
617a457eb83e0f20ded4a75f6415e86c9f7b3870 | PacktPublishing/Software-Architecture-with-Python | /Chapter07/factory.py | 1,458 | 4.0625 | 4 | # Code Listing #6
"""
Implementation of the Factory/Factory Method Design Pattern
"""
from abc import ABCMeta, abstractmethod
class Employee(metaclass=ABCMeta):
""" An Employee class """
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
... |
efa61a7ba16fc2a9c3b863d814f63cead0b71927 | PacktPublishing/Software-Architecture-with-Python | /Chapter07/hasher.py | 976 | 3.609375 | 4 | # Code Listing - #3
"""
StreamHasher - Class providing hashing of data from an input stream
using pluggable algorithms
"""
# NOTE: This combines the two methods provided in the book into one class.
class StreamHasher(object):
""" Stream hasher class with configurable algorithm """
def __init__(self, a... |
6961d2c793f363692343d894c45ec12c6948197e | PacktPublishing/Software-Architecture-with-Python | /Chapter07/proxy.py | 2,558 | 3.890625 | 4 | # Code Listing #12
"""
Proxy design pattern - An example of an instance counting proxy
"""
from abc import ABCMeta, abstractmethod
class Employee(metaclass=ABCMeta):
""" An Employee class """
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gende... |
08087cefea1ebcb767e8cec2e4bcd3f4535b60de | PacktPublishing/Software-Architecture-with-Python | /Chapter04/rotate.py | 417 | 4.1875 | 4 | # Code Listing #6
"""
Example with collections.deque for rotating sequences
"""
from collections import deque
def rotate_seq1(seq1, n):
""" Rotate a sequence left by n """
# E.g: rotate([1,2,3,4,5], 2) => [4,5,1,2,3]
k = len(seq1) - n
return seq1[k:] + seq1[:k]
def rotate_seq2(seq1, n):
""" R... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.