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
145b7416b4f46ff8fa1b60cf57ac425cfc911fae
mohsinkazmi/Capture-Internet-Dynamics-using-Prediction
/Code/kNN/kNN.py
1,328
4.1875
4
from numpy import * from euclideanDistance import euclideanDistance def kNN(k, X, labels, y): # Assigns to the test instance the label of the majority of the labels of the k closest # training examples using the kNN with euclidean distance. # # Input: k: number of nearest neighbors # X: traini...
c23ad56c534d66a4e8854bd06b24327667befaab
idan0610/intro2cs-ex8
/asteroidsMain.py
16,821
4.1875
4
###################################################################### # FILE: asteroidsMain.py # WRITER: Idan Refaeli, idan0610, 305681132 # EXERCISE: intro2cs ex8 2014-2015 # DESCRIPTION: # Functions cares for the running of Asteroids game ####################################################################### from ...
588901780c1b0bbcad74d5805ecefc330a79301a
ayadij/practice-python
/substrings.py
787
3.90625
4
# kwyword in message = "I like cats and dogs." dog_present = 'dog' in message print(dog_present) # find method message = "I like cats and dogs." dog_index = message.find('dog') print(dog_index) # find the last instance of a substring message = "I like cats and dogs, but I'd much rather own a dog." last_dog_index = m...
372f200529fc0c2be7f3ebf4d6a2b2f5e6f076cd
rinatrosenbergkima/NN_example
/nn_main_rinat.py
2,651
3.65625
4
import numpy as np def nonlin(x, deriv=False): if (deriv == True): return x * (1 - x) return 1 / (1 + np.exp(-x)) X = np.array([[1.0, -1.0]]) y = np.array([[0.1]]) np.random.seed(1) n_hidden = 2 # randomly initialize our weights with mean 0 # w_ih = 2 * np.random.random((X[0].shape[0], n_hidden...
6122e404e29b3c97b7fe2bdd8705bfc7f7bb202f
Vinay795-rgb/code
/Calendar.py
496
4.3125
4
# Write a program to print the calendar of any given year import calendar y = int(input("Enter the year : ")) m = 1 print("\n***********CALENDAR*******") cal = calendar.TextCalendar(calendar.SUNDAY) # An instance of TextCalendar class is created and calendar. SUNDAY means that you want to start dis[playing t...
70d545486cb4824693532dd575978c89d935d47d
blacktrub/binary-search-example
/test_bs.py
493
3.625
4
from bs import EMPTY_VALUE from bs import recursive_binary_search, loop_binary_search def test_binary_search(): for implementation in (recursive_binary_search, loop_binary_search): assert implementation([], 1) == EMPTY_VALUE assert implementation([1, 2], 1) == 0 assert implementation([1, 2...
02d34bb1965973af056d4f9ff184d31a308bed6b
tiborsimon/cm-contest
/problem-3/test.py
5,765
3.75
4
from unittest import TestCase from p3 import parse_params, decision class ParameterParsing(TestCase): def test__parameters_can_be_parsed(self): data = [ '1\n', '3 3 1\n' ] expected = { 1: [3, 3, 1] } result = parse_params(data) sel...
7f82f38b94fd235b08c0840b3df1d518de649bde
DernierServo/MasterPython
/20-proyecto-python/notas/acciones.py
1,604
3.5625
4
import notas.nota as modelo class Acciones: def crear(self, usuario): print(f'\nOK {usuario[1]}!! Vamos a generar una nueva nota...') titulo = input('Título: ') descripcion = input('Contenido: ') nota = modelo.Nota(usuario[0], titulo, descripcion) nota_guardada = nota.gua...
deca621b4b1385085a2a3ad2843a49c5426a4017
beni55/gplab
/schlep/operators/stackOps.py
1,787
3.84375
4
""" Contains basic stack-manipulation operators. """ from schlep.instructionset import InstructionSet, operator instructionSet = InstructionSet(name=__name__) @operator(instructionSet) def pop(machine): """Removes (and discards) the top element from the stack.""" machine.dataStack.pop() return True @o...
d630cb62e7550ea308ef6a043ae88d3a4cd3d5e1
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithm on string/week4/suffix_array_long.py
1,762
3.84375
4
# python3 import sys def build_suffix_array(text): """ Build suffix array of the string text and return a list result of the same length as the text such that the value result[i] is the index (0-based) in text where the i-th lexicographically smallest suffix of text starts. """ order = [] # Implemen...
0fa5f57b1351604b6f1c7d8858d26909637ca57b
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithm on string/week4/kmp.py
827
4.125
4
# python3 import sys def find_pattern(pattern, text): """ Find all the occurrences of the pattern in the text and return a list of all positions in the text where the pattern starts in the text. """ result = [] # Implement this function yourself conc=pattern+'$'+text values=[0]*len(conc) last=0 ...
f8bcfdd05de44e9a6019753e8668d22163e55bdf
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithm on graphs/week1_graph_decomposition1/reachability.py
813
3.734375
4
#Uses python3 import sys def reach(adj, x, y): #write your code here result=0 isVisited = [False] * len(adj) def explore(vertex): if isVisited[vertex] == True: return False isVisited[vertex] = True for adjecent in adj[vertex]: if adjecent == y or explore...
d668b195f542abc077ef07c82a02ff78f87b9ac5
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithmic toolbox/week3_greedy_algorithms/change.py
202
3.71875
4
# Uses python3 import sys def get_change(m): no_coin=0 coins=[10, 5, 1] for coin in coins: while(m>=coin): m=m-coin no_coin=no_coin+1 return no_coin m = int(input()) print(get_change(m))
890d233799fd8feea79c8fa4c8490fe882c1f2d9
HanifanNahwi/Python-Projects-Protek
/Chapter 5/Praktikum 1/latihan02.py
434
3.734375
4
a = "Status Kelulusan :" print("Masukkan Nilai diantara 0 - 100") #input nilai indo = int(input("Bahasa Indonesia : ")) ipa = int(input("IPA : ")) mtk = int(input("Matematika : ")) if(indo > 100) or (indo < 0) or (ipa > 100) or (ipa < 0) or (mtk > 100) or (mtk < 0): print("Maaf, input ada yang t...
1a7d06e70b9f1f9633830c93aeb696341678e1f5
HanifanNahwi/Python-Projects-Protek
/Chapter 11/Project1.py
223
3.59375
4
from datetime import * def diffDate(x): x = datetime.strptime(x,'%Y-%m-%d').date() y = datetime.date(datetime.now()) z = y - x return z a = diffDate('2021-01-01') print('selisihnya adalah', a.days, 'hari')
38a8cd5a095324d7088fddb0f4ecf995e4a2267d
HanifanNahwi/Python-Projects-Protek
/Chapter 8/Project1.py
180
3.6875
4
n = int(input("Banyaknya Data: ")) data = [] for i in range(0, n): a = int(input("Masukkan data ke-%d: " % (i+1))) data.insert(1, a) data.sort(reverse=True) print(data)
8e5038899ed71dc0b23319c5fb711e584132683a
HanifanNahwi/Python-Projects-Protek
/Chapter 5/Praktikum 1/latihan03.py
704
3.65625
4
#variabel a = "Status Kelulusan :" b = "Sebab :" print("Masukkan Nilai diantara 0 - 100") #input nilai indo = int(input("Bahasa Indonesia : ")) ipa = int(input ("IPA : ")) mtk = int(input ("Matematika : ")) #status kelulusan if(indo > 100) or (indo < 0) or (ipa > 100) or (ipa < 0) or (mt...
c0d15e10d5338a7042564a8ee4a8d1de7acb515f
HanifanNahwi/Python-Projects-Protek
/MID/UTS1.py
527
3.671875
4
def bmi(BB,TB): global rbmi rbmi = BB/(TB**2/10000) print('===========Body Mass Index (BMI)===========') a = float(input('Masukkan Berat Badan(Kg) anda : ')) b = float(input('Masukkan Tinggi Badan(cm) anda : ')) bmi(a,b) print('') if(rbmi < 18): print('Status Anda : Kurus') elif(18 <= rbmi < 23): ...
1c8f49b8b10542ebc0f457f328badaa1d05aabbd
CrisExpo/EcuacionSegundoGrado
/ecuacionSegundoGrado.py
618
3.53125
4
from math import sqrt def raizEcuacionSegundoGrado(a, b, c): if b == c == 0: return 0 if c == 0: x = 0 y = -b / a return x, y if b == 0: x = sqrt(-c/a) y = -sqrt(-c/a) return x, y else: x = (-b + sqrt(-c / a)) / 2 ...
03d4e2602ef7625025172e28111ea51277927463
grommy/algorithmic_toolbox
/Dynamic Programming/Edit Distance/edit_distance.py
1,299
3.875
4
# python3 """ Given two strings of length at most 100, compute the minimum number of single symbol insertions, deletions, and substitutions to transform one string into the other one. short->hort->port->ports """ def print_matr(matr): for row in matr: print(row) def diff(a, b): return 0 if a == b e...
460718989f15219836d1e49037695445f6dfbd35
grommy/algorithmic_toolbox
/Divide-and-Conquer/Organizing a Lottery/organizing_lottery.py
3,028
3.59375
4
# python3 from sys import stdin """ You are organizing an online lottery. To participate, a person bets on a single integer. You then draw several segments of consecutive integers at random. A participant’s payoff is proportional to the number of segments that contain the participant’s number. You need an efficient...
a44fb9384ca70cfc7ea65c57a825efae379e1fc1
wickyou23/python_learning
/python3_learning/class_inheritance.py
1,429
4.34375
4
#####Python inheritance and polymorphism # class Vehicle: # def __init__(self, name, color): # self.__name = name # self.__color = color # def getColor(self): # return self.__color # def setColor(self, color): # self.__color = color # def getName(self): # ret...
23ab00fb5704520dc6bd99fabd951f3fdff77f8c
wickyou23/python_learning
/python3_learning/operators.py
251
4.15625
4
#####Python operators # x1 = 3/2 #float div # x2 = 3//2 #interger div # x3 = 3**2 # x4 = 6%2 # print(x1, x2, x3, x4) #####Operator Precedence # x5 = 1+3*2 # print(x5) #####Augmented Assignment Operator # x6 = 1 # x6 += 1 # print(x6)
f8efd34cd7f00b24b82430f55ca94fe26716c351
awrenn/StochasticKnapsack
/knapsack01.py
2,539
3.890625
4
import random class item: def __init__(self,min_v,max_v,min_w,max_w): self.max_v = max(max_v,min_v) self.min_v = min(max_v,min_v) self.max_w = max(max_w,min_w) self.min_w = min(max_w,min_w) self.exp_v = (max_v + min_v)/2 self.exp_w = (max_w + min_w)/2 def expect...
dc1c3c9940b18ea7144de72aa12b2813db2e692b
MarceloBD/redesneurais
/trab1/main2.py
568
3.515625
4
import numpy as np from mult_layer_percepton import mlp dataset = np.identity(3) learn_rate = 0.1 epochs = 10000 mlp = mlp(1, 3, 10, 1) if __name__ == '__main__': for epoch in range(epochs): error = [] for data in dataset: error.append(mlp.backpropagation(data, data, learn_rate)) ...
03273fc50964a132d6f7b6a9ed2e8dc5f02a030f
ShobhitRathi/python-ds
/data_structures/strings/palindromic string.py
126
4.125
4
x=input("enter a string:") y=x[::-1] if y==x: print("it is a palindrome") else: print("it is not a palindrome")
366ffad8460a65261f57e99b28789147a915e3d0
TimothyCGoens/Assignments
/fizz_buzz.py
613
4.21875
4
print("Welcome back everyone! It's now time for the lighting round of FIZZ or BUZZ!") print("""For those of you following at home, it's simple. Our contestants need to give us a number that is either divisible by 3, by 5, or by both!""") name = input("First up, why don't you tell us your name? ") print(f"""Well {name...
7c89dd51b594ce56ed5fee26537a4c05ade483a1
thedern/algorithms
/recursion/recursion_linked_list.py
541
3.984375
4
class Node: def __init__(self, data, next_item=None): self.data = data self.next_item = next_item # create instances def traverse_list(head): if head is None: return # recursive case print(head.data) return traverse_list(head.next_item) def main(): item1 = Node('d...
f2ce2ad7ad3703bb800c7fc2dfd79b6bab76d491
thedern/algorithms
/recursion/turtle_example.py
835
4.53125
5
import turtle max_length = 250 increment = 10 def draw_spiral(a_turtle, line_length): """ recursive call example: run the turtle in a spiral until the max line length is reached :param a_turtle: turtle object "charlie" :type a_turtle: object :param line_length: length of line to draw :t...
01cfdcb90198ec3a26e28b6c315571e52dedc094
thedern/algorithms
/recursion/memoization.py
617
3.9375
4
""" memoization is the caching of calls/values in order not to duplicate work. recursive calls have a lot of duplicate statements by definition. lru cache can reuse previous calls reducing expensive I/O bound computation. """ from functools import lru_cache @lru_cache def fin(n): """ 0, 1, 1, 2, 3, 5, 8, 1...
3cd4df2058254333b0a2e9cacb57159746c63dc0
Aprendiend/programa
/2 for.py
248
3.8125
4
numero=int(input("Ingrese un número entero: ")) primo=True for i in range(2,numero): if numero%i==0: primo=False if primo: print("El número", numero, "es primo") else: print("El número", numero, "NO es primo")
825152275f2f0052cbb12d5e76f778c33832c89b
aw84849/MAGIC19
/Project1/lambda_function.py
21,354
3.71875
4
""" Trivia quiz.. """ from __future__ import print_function import math import string import random GAME_STATE_TRIVIA = "TRIVIA" GAME_STATE_START = "START" GAME_STATE_HELP = "HELP" GAME_QUESTIONS_KEY = "gameQuestions" ANSWERTEXT_KEY = "correctAnswerText" SCORE = "score" CORRECTANSWERINDEX = "correctAnswerIndex" SPEEC...
a45f3991403736dfa218528dc0e40a6ea9736540
kongkiet007/Python
/week 4/4.1.py
3,244
3.703125
4
import os choice = 0 listcoffee = [0,0,0,0,0,] pick = 0 def menu(): global choice print('\tโปรแกรมร้านขายปืน\n','1.แสดงรายการสินค้า\n 2.หยิบสินค้าเข้าตะกร้า\n 3.แสดงรายจำนวนและราคาของสินค้าที่หยิบ\n 4.หยิบสินค้าออกจากตะกร้า\n 5.ปิดโปรแกรม') choice = input('กรุณาเลือกทำรายการ : ') screen_clear() def sho...
6e88b60e8ef7c0ad50f82d4442ca05d4b7dea139
mjmonarch/Tic-Tac-Toe
/Tic-Tac-Toe/task/tictactoe/tictactoe.py
5,201
3.65625
4
# ---------------------------1--------------------------- # print("""X O X # O X O # X X O""") # ---------------------------2--------------------------- # instructions = input() # output = "---------\n" # for i in range(0, 3): # output += f"| {instructions[i * 3]} {instructions[i * 3 + 1]} {instructions[i * 3 + 2]...
202c6868971d8a68d9516d3f773bf0b2da70f6d6
Saninoux/Dactylo
/apprendre.py
1,174
3.9375
4
""" Partie "jouer" du jeu dactylographique dernière modification faite le 14.05.2019 auteurs: JAWDEKAR Aarush et THAY San """ import time MOT = "anticonstitutionnellement" def apprendre(): erreur = 0 for lettre in range(10,len(MOT)+10): while True: print(MOT[0+lettre-10:lettre+1]) ...
c69bc55f8232b035c599b69d8d590a3ec13e2c71
mfthor/PersonalProjects
/GatchaSim.py
1,063
3.78125
4
import random box_num = random.randint(1,12) class Box: def __init__(self, num): self.num = num marb_count = 0 flag = False def make_box(num): box = Box(num) return box def trial(i): box_list = [] flag = True count = 0 for x in range(1,i+1): box = make_box(x) box_list.append...
d1f1f37fea4565d287222e2ec6563a8949de1572
ajstarna/SemaPhoR
/Src/annotateOutput.py
8,867
3.609375
4
#!/usr/bin/env python3 ''' this script will read in the output of proto sets and additions, and print out annotations for all words found in a set ''' from collections import defaultdict from GoldEvaluator import GoldEvaluator from DefSetsReader import DefSetsReader class OutputAnnotator(object): ''' this clas...
d0a271ef55e57f60196140606e642488bc12b78b
arenfuller/Learning
/afcats.py
565
4.0625
4
#working with a list of strings my_cats=["cameron", "Milo", "Elyshia"] print("cats in reverse order", my_cats[::1]) print("number of cats", len(my_cats)) print("sorted cats", sorted(my_cats)) print("reverse sorted cats", sorted (my_cats, reverse=True)) print ("1st cat", my_cats[0]) #Add a new cat and see i...
23500b56ea235873740d933e57073c94ba1ba731
NurdinovRost/ODS_AI_DL
/assignments/assignment2/model.py
3,067
3.71875
4
import numpy as np from layers import FullyConnectedLayer, ReLULayer, softmax_with_cross_entropy, l2_regularization, softmax class TwoLayerNet: """ Neural network with two fully connected layers """ def __init__(self, n_input, n_output, hidden_layer_size, reg): """ Initializes the neural net...
887104a0efda555380f45c850f939744e836f915
raw-at/python-3-testwork
/practise.py
1,201
4.0625
4
class Cars: #class variables hold by all the instances mileage = 12 def __init__(self,brand,model,price): self.brand = brand self.model = model self.price = price @classmethod def mileage_booster_fuel(cls,new_mileage): cls.mileage = new_mileage @...
d1b9064de3d78d8ef6e02f6b44d84bbe5b9d1aca
raw-at/python-3-testwork
/list_comprehension.py
1,008
3.921875
4
nums = [1,2,3,4,5,6,7,8,9,10] ''' my_list = [] for n in nums: my_list.append(n) print(my_list) ''' my_list = [n for n in nums] #list comprehension my_list = [n*n for n in nums] #list comprehension my_list = [n for n in nums if n%2==0] print(my_list) my_list = [(letter,number) for letter in 'abcd' for number in ...
bc87f755b34064cc614504c41092be4765251e03
njg89/codeBasics-Python
/importSyntax.py
1,007
4.15625
4
# Designate a custom syntax for a default function like th example 'statistics.mean()' below: ''' import statistics as stat exList = [5,3,2,9,7,4,3,1,8,9,10] print(stat.mean(exList)) ''' # Only utilize one function, like the 'mean' example below: ''' from statistics import mean exList2 = [3,2,3,5,6,1,0,3,8...
24c0922b07b81a943dc5ad9de569b9c4959fe81f
njg89/codeBasics-Python
/pythonGlobal_localVariables.py
566
4.0625
4
#a lot of python practitioners do not condone global variables x = 6 print("--BEGIN EXAMPLE FUNCTION--") def example(): print(x) example() #example2() considered best practice for assigning variables and returning it to a global variable print("---BEGIN EXAMPLE2 FUNCTION---") def example2(): z = ...
c2ad546a27b3b8872dcfa46ae1a8410f31cc24b8
iamish08/Py-Program
/filedict.py
355
3.703125
4
import string fname=input('Enter the filename:') try: fhand=open(fname) except: print('File cannot be opened',fname) exit() counts=dict() for line in fhand: line=line.rstrip() line=line.translate(line.maketrans(',',' ',string.punctuation)) line=line.lower() words=line.split() for word in words: counts[word]=...
41e48f6d866cafb099d44d67a785c78617332f30
75kuangren/ShiYanLou_code
/jump7/jump7.py
91
3.5625
4
for n in range(1,101): if n%7==0 or n%10==7 or int(n/10)==7: continue else: print(n)
66b5826912e87770d5e305e93f2faacba745ac7e
CleonPeaches/idtech2017
/example_02_input.py
499
4.15625
4
# Takes input from user and assigns it to string variable character_name character_name = input("What is your name, adventurer? ") print("Hello, " + character_name + ".") # Takes input from user and assigns it to int variable character_level character_level = (input("What is your level, " + character_name + "? ")) # ...
d0131a3a348569745753a835ae6878277846c38e
shadow0202/asr
/Utils/file_number.py
2,421
3.734375
4
# -*- coding: utf-8 -*- """ # @Author : huxw # @Update : 2018/11/2 14:13 # @Software: PyCharm 计算文件数量工具 """ import os from sys import argv totalSize = 0 fileNum = 0 dirNum = 0 fn_list = [] count = 0 def file_name(file_dir): for root, dirs, files in os.walk(file_dir): return dirs,files def visitDir...
28d7549be65a06aa959740e4ac0ad28bd6d1b223
jioda85/HW4_Colormap
/HW4_colormap.py
2,183
3.625
4
# ============================================================================== # HW4: function to call the RGB colomap data from http://geography.uoregon.edu, # and return the number of color (leng) & a colormap dictionary (cdict) # =======================================================================...
59a01fe835d799fb8ff5d1a1f1c7ec841869e387
ylester/Coding-Challenges
/CodeFiles/bank-acct-challenge.py
707
3.59375
4
""" Goldman Sachs CodeSprint Challenge Bank Accounts Challenge See textfiles/bank-acct-challenge for more details """ import sys def feeOrUpfront(n, k, x, d, p): feeCost = [] for values in p: if values * (x/100) < k: feeCost.append(k) else: feeCost.append(values*(x/100)...
9877127343debc86e7773c567e2d8a4f441006ae
LakshyaMalhotra/disaster-response-pipeline
/process_data.py
3,630
3.59375
4
import sys import os import numpy as np import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): """ Read the CSV files and load the data into pandas dataframe after merging the data from both files. Arguments: ========== :param messages...
9630e71c63edf2265519bf77137f6d5923c9315c
cristeoana/PersonalWork
/Obstruction/data/PlayGame.py
1,213
3.75
4
from lab10.data.Board import Board import random class Play: def __init__(self, i, j): ''' Initialize the board of the game. input: i- the number of rows j-the numbers of colums ''' self._play = Board(i, j) def __str__(self): ''' Overload...
89dbddd5c9c2ab4536862f59729fb466a4322888
EduS106/BrIW
/app/source/oldVersions/commandLineIntro2.py
577
3.859375
4
import sys arguments = sys.argv people = ["Eduardo", "Conner", "John", "Julio", "Nick", "Danny", "Billy", "Connor"] drinks = ["Coffee", "Beer", "Earl Gray Tea", "San Miguel", "Red Bull", "Protein Smoothies", "Milkshakes", "Water"] if len(arguments) == 2: command = arguments[1] if command == "get-people": ...
153100785020f4bbb92a661b55f9f187602abe19
andy1li/usaco-training
/Training/1.3 Complete Search/1.3.2-transform.py
909
3.875
4
''' ID: andy1li LANG: PYTHON3 TASK: transform ''' def reflect(square): return tuple(tuple(reversed(row)) for row in square) def rotate(square, n): for _ in range(n): square = reflect(zip(*square)) return square def get_D4(square): D4 = {square: 6} for i in range(3): D4[rotate(reflect(sq...
a34644db3327bc063a04458c63efd245c841ca88
GuillaumeOj/YodaPy
/app/bot.py
1,964
3.625
4
"""Choose random messages from the bot""" import json import os.path from random import choice CURRENT_DIT = os.path.abspath(os.path.dirname(__file__)) class Bot: """Used for generate text from the bot""" def __init__(self): json_path = os.path.join(CURRENT_DIT, "static/json/yoda.json") wit...
3c8743383d7db1598dc7f422bdde8242e5c24591
Bruces1998/problemSolving
/traversal.py
576
3.90625
4
class Node: def __init__(self,x): self.right = None self.left = None self.val = x class BinaryTree: def __init__(self, x): root = x n1 = Node(7) n2 = Node(96) n2.right = n1 n3 = Node(125) n3.right = n2 n3.left = Node(8) root = Node(100) root.left = n3 n4 = Node(15) n4.left...
b4c3f187116e08785499e72fae7d0ae6e60bb6c1
Bruces1998/problemSolving
/man_goat.py
4,245
4.09375
4
# Implementation of a depth-first search for a solution to the # cow-tiger-grass puzzle. # Problem: a man is transporting a cow, a tiger, and a grass. He # must cross a river and has a boat that can only carry 1 item # beside himself at a time. He cannot leave the cow alone on one # side of the river with the grass be...
7b5119077624a269d16e801c15a79203020b5821
cuongpianna/python
/python/app7.py
836
3.53125
4
import multiprocessing import os """" module using Lock obj quan ly truy cap du lieu """ def withdraw(balance,lock): for _ in range(10000): lock.acquire() balance.value= balance.value - 1 lock.release() def deposit(banalce,lock): for _ in range(10000): lock.acquire() ...
74ee668b7f2b243c5aedd899a44a0d466003ed18
kenextra/code_snippets
/LinkedList/linked_list.py
9,469
4.5
4
class LLNode: """A class that defines a linked list node Attributes ---------- data : Any Data element for the node prev : LLNode Previous node this node points to (default=None) next : LLNode next node this node points to (default=None) """ def __init__(self, d...
f0114b3df9bd36d8c87621a40a05759c3020d384
dusdn1702/algorithm_2020
/programmers/KNumber.py
228
3.578125
4
def solution(array, commands): answer = [] for i in commands: arr = [] for j in range(i[0]-1,i[1]): arr.append(array[j]) arr.sort() answer.append(arr[i[2]-1]) return answer
fb2c217523a7b6167954a2f03046f0ca90270c77
salmanbakal/python_project_files
/gui.py
886
3.9375
4
import PySimpleGUI as sg import wikipedia # Define the window's contents layout = [[sg.Text("Enter your command")], [sg.Input()], [sg.Text(size=(40,1), key='-OUTPUT-')], [sg.Button('Ok'), sg.Button('Quit')]] # Create the window window = sg.Window('Window Title', layout) # Disp...
e74f521363237c676fab6704ca2e075a99af6257
AdityaPokuri/python
/assidnment_2.py
607
3.8125
4
##question1 ##question2 for i in range(1,21): print(i, i+2) ##questin3 from collections import Counter x=Counter('hello&*$$world') print(x) ##question4 lower=int(input("Enter the lower limit for the range:")) upper=int(input("Enter the upper limit for the range:")) for i in range(lower,upper+...
2cd498d42ef535c582d083489e9a9fdc5d7c25f9
RockyDong/dream_plan
/download.py
3,624
3.671875
4
# 定义函数,将网址转化为html内容 # 使用requests模块,教程参见:http://www.python-requests.org/en/master/ import requests import re import os def url2html_requests(url,encoding='utf-8'): # 输入:网址 # 输出:网页内容 # 检查网址是否以http://开头,少数网站是以https://开头的 if not url.startswith('http://'): url = 'http://' + url try: ...
4e1096e3074fc70d3df6c564c655db0b1bbf8f7e
Julietarellanoo/Fundamentos-Python
/03-ejemplo-errores-no-reparados.py
243
4
4
#!/usr/bin/env python # Inicializar variables f = c = 0 # Fórmula de Conversión de Celsius a Fahrenheit f + 32 = 9/5 * c c = float(input('Introduzca la temperatura en °C (centígrados):') print "La temperatura equivalente en °F es", c
250a671dd80b9fd912ce6eb56e1ee2f9a6e803e9
Demons-wx/python_tec
/wx_iterator/anti_iterator.py
915
3.984375
4
# coding=utf-8 # 实现一个连续浮点数发生器FloatRange(和xrange类似),根据给定范围(start, end)和 # 进步值(step)产生一些连续浮点数,如迭代FloatRange(3.0, 4.0, 0.2)可产生序列: # 正向:3.0->3.2->3.4->3.6->3.8->4.0 # 反向:4.0->3.8->3.6->3.4->3.2->3.0 # 列表的反向迭代 # l = [1, 2, 3, 4, 5] # for x in reversed(l): # print x class FloatRange: def __init__(self, start, end,...
d95873d366ff99828ccf1d42af251db835716dbd
Demons-wx/python_tec
/wx_file/temp_file.py
740
3.5
4
# coding=utf-8 # 某项目中,我们从传感器采集数据,每收集到1g数据后,做数据分析,最终只保存分析结果 # 这样很大的临时数据如果常驻内存,将消耗很大内存资源,我们可以使用临时文件存储这些 # 临时数据(外部存储) # # 临时文件不用命名,且关闭后会自动被删除 # # 使用标准库中tempfile下的TemporaryFile, NamedTemporaryFile from tempfile import TemporaryFile, NamedTemporaryFile # 由TemporaryFile创建的文件在文件系统中是找不到的,只能由对象f来访问 f = TemporaryFile() f.writ...
c2ad3887cfe0ddca9411b4b6ab1fae47b524ec93
Demons-wx/python_tec
/wx_class_object/manage_memory.py
915
3.53125
4
# coding=utf-8 # 在python中,垃圾回收器通过引用计数来回收垃圾对象,但某些环状数据结构,存在对象之间的循环引用, # 比如树的父节点引用子节点,子节点也同时引用父节点,此时同时del掉引用父子节点,两个对象不能立即 # 回收。 # # 如何解决此类内存管理问题? # 使用标准库weakref, 它可以创建一种能访问对象但不增加引用计数的对象 import weakref class Data(object): def __init__(self, value, owner): self.owner = weakref.ref(owner) self.value =...
4e17d157d0abc7d7f36a454b3a3fe62887e98cc4
ian7aylor/Python
/Programiz/GlobKeyWrd.py
654
4.28125
4
#Changing Global Variable From Inside a Function using global c = 0 # global variable def add(): global c c = c + 2 # increment by 2 print("Inside add():", c) add() print("In main:", c) #For global variables across Python modules can create a config.py file and store global variables there #Using a Glo...
b220370ca9ffd82ea7189e0a5167c9bae233f223
ian7aylor/Python
/Programiz/For_Loop.py
1,260
4.28125
4
#For Loop ''' for val in sequence: Body of for ''' # Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list #iterates through list of numbers and sums them together for val in numbers: sum = ...
1c14df00fa1f6304216b8fd1d7a28186610c3182
rishabmehrotra/learn_python
/Strings and Text/ex6.py
879
4.625
5
#use of f and .format() """F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. f'some stuff here {avariable}'""" #.format() """ The format() method formats the specified value(s) and insert them inside the string's placeholder. txt1 = "My name is {fname}, I...
22dcc552429f2d6dfb0a05b85622528b8e01c4f0
rishabmehrotra/learn_python
/Variables and Names/ex5.py
301
3.5625
4
my_name = "Rishab Mehrotra" my_age = 24 my_mail_id = "rishabmehrotra19@gmail.com" my_nationality= "Indian" num1 = 454 num2 = 645 num3 = 64153 print("My name : %s" % my_name) print("My age : %d"% my_age) print("My nationality : %s"% my_nationality) print("If I add %d %d and %d I get %d."% (num1, num2, num3, num1 + num2...
806969204ed0adab1f751fc6c3aa6ac07eb4cf7d
DonaldButters/Module5
/input_while/input_while_exit.py
1,300
4.28125
4
""" Program: input_while_exit.py Author: Donald Butters Last date modified: 9/25/2020 The purpose of this program is prompt for inputs between 1-100 and save to list. Then the program out puts the list """ #input_while_exit.py user_numbers = [] stopvalue = 404 x = int(input("Please Enter a number between 1 and ...
7b16d1756f0b5d740afe7807dafbf0ad1066678d
themp731/MP_FooBar
/Breeding/solution_mp3.py
1,461
3.6875
4
rabbits = {0:1,1:1,2:2} ''' def breed2(n): if n in rabbits: return rabbits[n] x = n // 2 if x*2 == n: rabbits[n] = breed2(x) + breed2(x + 1) + (x) else: rabbits[n] = breed2(x - 1) + breed2(x) + 1 return rabbits[n] ''' def breed3(n): if n in rabbits: return rabbits[n...
8fe8605311210ea18e381eae1957c3b282f026f6
kzk-maeda/algorithm_and_data_structure
/python/sort/bubble_sort.py
495
4.3125
4
from typing import List # Listのソート範囲の最後尾が最大値となるよう、繰り返し比較処理を実行する def bubble_sort(numbers: List[int]) -> List[int]: len_numbers = len(numbers) for i in range(len_numbers): for j in range(len_numbers - 1 - i): if numbers[j] > numbers[j+1]: numbers[j], numbers[j+1] = numbers[j+1], numbers[j] re...
e62d66dff6681e6e3db9009dabb7a8adae47dcc8
xuchen666/PythonCookbook
/Cookbook_Chapter4.py
7,647
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 22 09:48:43 2017 @author: xuchenwang """ # 4.1. Manually Consuming an Iterator ''' You need to process items in an iterable, but for whatever reason, you can’t or don’t want to use a for loop. ''' # 4.2. Delegating Iteration ''' You have built a ...
6439b985a3c80e8a5eb26d174b1745a20b513951
mgmavely/pong
/ball.py
918
4
4
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.deg = 45 self.setheading(self.deg) self.color("white") self.penup() def move(self): self.forward(10) def hit_wall(self): return ...
b86882d01afe7a3278bc0aa8746e7a62b9d82457
q737645224/python3
/python基础/python笔记/day04/day03_exercise/string.py
874
3.75
4
# 1. 输入一个字符串用变量s绑定 # 1) 判断您输入的字符串有几个空格 # 2) 将原字符串的左右空白字符去掉, 打印出剩余的字 # 符个数 # 3)判断您输入的是否是数字 # 4) 如果是数字,判断这个数字是否大于100 # 1. 输入一个字符串用变量s绑定 s = input("请输入一个字符串: ") # 1) 判断您输入的字符串有几个空格 print("空格的个数是:", s.count(' ')) # 2) 将原字符串的左右空白字符去掉, 打印出剩余的字符个数 s2 = s.strip() # 云掉空白字符 print("去掉空白字符后的个数是: ", len(s2)) ...
5675f08936121de79d098da8f94d3971482aed4a
q737645224/python3
/python基础/python笔记/day15/day14_exercise/zhiyinshu.py
1,271
4
4
# 2. 分解质因数, 输入一个正整数,分解质因数, # 如: # 输入: 90 # 则打印: # '90=2*3*3*5' # (质因数是指最小能被原数整除的素数(不包括1)) def is_primes(x): if x <= 2: return False for i in range(2, x): if x % i == 0: return False return True # def get_zhiyishu(n): # '''用循环来实现''' # L = [] # # 如果n...
97e1e2f13c32df05868db151ccea6df0e4495cd8
q737645224/python3
/python基础/python笔记/day18/code/inherit.py
711
3.828125
4
# inherit.py # 此示例示意单继承的用法: class Human: # 人类的共性 def say(self, what): print("say:", what) def walk(self, distance): # 走路 print("走了", distance, '公里') class Student(Human): def study(self, subject): print("正在学习:", subject) class Teacher(Student): '''说话,行走,教学''' def tea...
7f330c060b987141c23e39702fa351a972957a98
q737645224/python3
/python基础/python笔记/day06/exercise/list1.py
941
4.0625
4
# 练习: # 1. 写程序,让用户输入一些整数,当输入-1时结束输入, # 将这些数存于列表L中 # 1) 打印用户共输入了几个数? # 2) 打印您输入的数的最大数是多少 # 3) 打印您输入的数的最小数是多少 # 4) 打印您输入的这些数的平均值是多少? # 1. 写程序,让用户输入一些整数,当输入-1时结束输入, # 将这些数存于列表L中 L = [] while True: x = int(input('请输入整数: ')) if x == -1: break # 结束循环输入 L += [x] # print("L="...
37c4a0ee7fe3b3992f30aa274617927ce47ba89d
q737645224/python3
/python基础/python笔记/day02/exercise/time.py
352
4.03125
4
# 3. 分三次输入当前的小时,分钟和秒数,在终端 # 打印时此距离凌晨0:0:0 秒过了多少秒 hour = input("请输入小时: ") hour = int(hour) # 转为整数 minute = int(input("请输入分钟:")) second = int(input("请输入秒:")) s = hour * 60 * 60 + minute * 60 + second print('从凌晨到现在经历了', s, '秒')
529bc9f78ef1aec9bb4bafb6f1b82583ec8ab1be
q737645224/python3
/python基础/python笔记/day14/student_project/main.py
780
3.6875
4
from menu import show_menu from student_info import * def main(): docs = [] # 用于存放学生信息的空列表 while True: show_menu() s = input("请选择: ") if s == '1': docs += input_student() elif s == '2': output_student(docs) elif s == '3': print("开始删...
962c4f67fd068b5e775f58e7a98a3843f8419da7
q737645224/python3
/python基础/python笔记/day07/day05_exercise/prime.py
645
3.890625
4
# 3. 写一个程序,任意输入一个整数,判断这个数是否是素数(prime) # 素数(也叫质数), 是只能被1和自身整除的正整数: # 如: 2 3 5 7 11 等 # 提示: # 用排除法: 当判断x是否是素数是,只要让x分别除以: # 2, 3, 4, 5, .... x-1, 只要整除了,那x不是素数,否则x是素数 x = int(input("请输入一个整数: ")) if x < 2: print(x, '不是素数') else: # x肯定是大于等于2 # 用排除法 for i in range(2, x): if x % i == 0:...
c54cbeb7fa6238af2922e6fa980064bc48699791
q737645224/python3
/python基础/python笔记/day04/exercise/right_align.py
1,283
4.25
4
# 练习: # 输入三行文字,让这三行文字依次以20个字符的宽度右对齐输出 # 如: # 请输入第1行: hello world # 请输入第2行: aaa # 请输入第3行: ABCDEFG # 输出结果如下: # hello world # aaa # ABCDEFG # 做完上面的题后思考: # 能否以最长的字符串的长度进行右对齐显示(左侧填充空格) a = input("请输入第1行: ") b = input("请输入第2行: ") c = input("请输入第3行: ") ...
519e636b9116102b67e19ded55e0680970f6f7f7
q737645224/python3
/python基础/python笔记/day05/code/range.py
188
3.703125
4
# range.py for x in range(4): print(x) # 0 1 2 3 print('-------------------') for x in range(3, 6): print(x) print('==============') for x in range(5, 0, -2): print(x)
7fc0019aadacc983436f8ff4b59644d1577fc5fe
q737645224/python3
/python基础/python笔记/day05/exercise/square.py
308
4
4
# 1. 输入一个数w代表正方形的宽度,打印如下正方形: # 如输入:5 # 1 2 3 4 5 # 1 2 3 4 5 # 1 2 3 4 5 # 1 2 3 4 5 # 1 2 3 4 5 w = int(input("请输入: ")) for line in range(1, w + 1): for x in range(1, w + 1): print(x, end=' ') print() # 打印完毕后换行
0429d0e321e22752b5b06df0e09e21f55ca69a9b
q737645224/python3
/python基础/python笔记/day11/day11/code/sorted.py
275
3.75
4
# sorted.py L = [5, -2, -4, 0, 3, 1] L2 = sorted(L) # L = [-4, -2, 0, 1, 3, 5] L3 = sorted(L, reverse=True) # 降序排序 L4 = sorted(L, key=abs) # L4 = [0, 1, -2, 3, -4, 5] print(L4) L5 = sorted(L, key=abs, reverse=True) # L5 = [5, -4, 3, -2, 1, 0] print("L5=", L5)
ec8d676308de59e6224af6a8eb1416e5c3978502
q737645224/python3
/python基础/python笔记/day09/exercise/print_odd.py
1,084
4.25
4
# 2. 写一个函数,print_odd, 此函数可以传递一个实参,也可以传递两个实参,当传递一个实参时代表结束值 # 当传递两个实参时,第一个实参代表起始值,第二个实参代表结束值 # 打印出以此区间内的全部奇数,不包含结束数: # print_odd(10) # 1 3 5 7 9 # print_odd(11, 20) # 11 13 15 17 19 # 方法1 def print_odd(a, b=0): if b == 0: for x in range(1, a, 2): print(x, end=' ') else: ...
90db359ca865a4a29a815f2c0d7a0fc8fbe0ad77
q737645224/python3
/python基础/python笔记/day15/exercise/iterator_set.py
519
4.15625
4
# 有一个集合: # s = {'唐僧', '悟空', '八戒', '沙僧'} # 用 for语句来遍历所有元素如下: # for x in s: # print(x) # else: # print('遍历结束') # 请将上面的for语句改写为 用while语句和迭代器实现 s = {'唐僧', '悟空', '八戒', '沙僧'} # for x in s: # print(x) # else: # print('遍历结束') it = iter(s) # 拿到迭代器 try: while True: x = next(i...
793d08fd36de8575500b176fd07a5883644523dd
q737645224/python3
/python基础/python笔记/day09/day08_exercise/student_info.py
1,678
4.0625
4
# 3. 改写之前的学生信息管理程序 # 改为两个函数: # 1. 写一个函数 input_student() 用于返回学生信息的字典的列表(以前格式一样) # 2. 写一个函数 output_student(lst) # 此函数传入一个列表lst,即字典的列表 # 此函数把lst的内容以表格形式打印出来 # def input_student(): # .... # def output_student(lst): # ... # L = input_student() # 获取学生信息的列表 # ou...
dc7ef8a26abcf8b466fbfdda721744f287a885e6
q737645224/python3
/python基础/python笔记/day03/day02_exercise/score.py
661
4.25
4
# 2. 输入一个学生的三科成绩(三个整数): # 打印出最高分是多少? # 打印出最低分是多少? # 打印出平均分是多少? a = int(input("请输入第一科成绩: ")) b = int(input("请输入第二科成绩: ")) c = int(input("请输入第三科成绩: ")) # if a > b: # if a > c: # print("最大数是:", a) # else: # print("最大数是:", c) # else: # if b > c: # print("最大数是:", b) # else: # ...
88bb47f7192e309855760683b86c3d3adcda3f44
q737645224/python3
/python基础/python笔记/day02/code/if2.py
235
3.515625
4
# if2.py # 输入一个数,用程序来判断这个数是正数,负数,还是零 n = int(input("请输入一个数: ")) if n > 0: print('正数') elif n < 0: print('负数') else: print('零') print("程序结束")
916b5dc789a400beacef837cc3cad57722e8fbe4
q737645224/python3
/python基础/python笔记/day09/exercise/mymax.py
789
3.78125
4
# 练习: # 写一个函数,mymax类似于 内键的函数max # 详见: # >>> help(max) # 仿造 max 写一信mymax函数,功能与max完全相同 # (要求不允许调用max函数) # print(mymax([6, 8, 3, 5])) # 8 # print(mymax(100, 200)) # 200 # print(mymax(1, 3, 5, 9, 7)) # 9 def mymax(a, *args): if len(args) == 0: # 实参个数等于1时 zhuida = a[0] fo...
3815e696f105445434e2bb13c3416d2301f97913
q737645224/python3
/python基础/python笔记/day17/code/attribute2.py
657
3.5625
4
# attribute.py # 此示例示意属性的用法 class Dog: def eat(self, food): # print("小狗正在吃:", food) print(self.color, '的', self.kinds, '正在吃', food) # 让调用此方法的对象添加一个last_food属性用来记住吃的信息 self.last_food = food dog1 = Dog() dog1.kinds = '京巴' # 为dog1对象添加kinds属性,绑定为'京巴' dog1.color = '白色' # dog1添加属性 为'白...
f4c98220a4789b723cdfe2d3b9d28fb8082499ca
q737645224/python3
/python基础/python笔记/day05/exercise/special_number.py
216
3.515625
4
# 练习: # 求 100以内有哪儿些整数与自身+1的乘积再对11求余的 # 结果等于8? # x * (x+1) % 11 == 8 x附合条件 for x in range(100): if x * (x + 1) % 11 == 8: print(x)
95a4171834f9d20c6ca28671a53b534f7ca8cdae
q737645224/python3
/python基础/python笔记/day14/exercise/get_age.py
1,152
3.734375
4
# 练习: # 写一个函数 get_age()用来获取一个人的年龄信息 # 此函数规定用户只能输入1~140之间的整数,如果用户输入其它的数则直接触发ValueError类型的错误通知 # 如果用户输入的年龄大于140,则触发 # ValueError("年龄超出了正常值") # 如果用户输入的年龄小于1,则触发 # ValueError("年龄太小...") # def get_age(): # ... # try: # age = get_age() # print("用户输入的年龄是:", age) # except Val...
48e07a7e322cb27b5f40eb8f9f29a2bac8d09894
q737645224/python3
/python基础/python笔记/day11/day11/exercise/filter_prime.py
334
3.84375
4
# 2. 写一个函数is_prime(x) 判断x是否是素数 # 用filter函数打印出: 20 ~ 30之间的全部素数 def is_prime(x): if x < 2: return False # 排序法 for i in range(2, x): if x % i == 0: return False return True for x in filter(is_prime, range(20, 30)): print(x)
f54884d90727dbdf64d47d284a2024a3a7cdda60
q737645224/python3
/python基础/python笔记/day11/day11/code/sorted2.py
163
3.546875
4
# sorted.py names = ['Tom', 'Jerry', 'Spike', 'Tyke'] L1 = sorted(names, key=len) print("L1=", L1) L2 = sorted(names, key=lambda x: len(x)) print("L2=", L2)
a484158b5f5de410326a5ae92f8bb43bea88e43f
q737645224/python3
/python基础/basepython/day503.py
145
3.6875
4
#day503.py i = 1 sum=0 while True: n = int(input("请输入一个数:")) sum +=n print("您刚才输入的这些数的和是:",sumr
118b77adcc6684a33ba88180add674772f3998c0
amajor/DatabaseAddressbookORM
/formatters.py
3,726
3.53125
4
import os import re from datetime import date ################################### # Clears the terminal screen # ################################### def clear_terminal_screen(): os.system('cls' if os.name == 'nt' else 'clear') ################################### # Prints the phone format # ########...
8abda8068278d4ceba6a2e60d5d76db6e2c02a86
DannyMcwaves/codebase
/pythons/stack/stack.py
1,526
4.125
4
__Author__ = "danny mcwaves" """ i learnt about stacks in the earlier version as a record activation container that holds the variables during the invocation of a function. so when the function is invoked the, the stack stores all the variables in the function and release them as long as their parent functions once the...