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
fca39622fb190442396b4eb7cf245a69a793ffbb
mxjstone/actual-10-homework
/01/fuliwei/fuliwei.py
476
3.71875
4
#!/usr/bin/python #_*_ coding:utf-8 _*_ #version1 : 利用两次遍历,第一次遍历找到最大值,第二次找到除了最大值以外的第二个值即为第二大的数 list = [1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,65555,45,33,45,5000] max1 = int(0) for i in list : # print i if int(i) > max1 : max1 = int(i) max2 = int(0) for j in list : if int(j) > max2 and int(j) < ma...
5a40511d4075245764552ea85871cda5c9538d33
se2313se/Ya.algorithms_training
/3/B.py
250
3.578125
4
with open('input.txt', 'r', encoding='UTF8') as f: line1 = set(map(int, f.readline().split())) line2 = set(map(int, f.readline().split())) ans = [a for a in line1 if a in line2] print(' '.join([str(a) for a in line1 if a in line2]))
9b20237fd05e85b1289d8ce675483edbcec583a9
jvictor42/IntroPython
/aula_6_turttle.py
430
3.8125
4
import turtle # nos permite usar as tartarugas (turtles) jn = turtle.Screen() # Abre uma janela onde as tartarugas vão caminhar jn.bgcolor(input('Coloque a cor da janela ''\n')) # Definir a cor de fundo da janela joana = turtle.Turtle() # Cria uma tartaruga, atribui a joana cores= ['yellow','...
4bab7e75fa2d6789fffee8a85becbba3350e41ef
bordenmike518/algorithms
/python/staircaseProblem.py
361
3.5
4
def staircasePermCount(N, K): if (N in {0,1}): return 1 if (N < K): return staircasePermCount(N, N); if (N >= K): permCount = 0 for i in range(1, K+1): permCount += staircasePermCount(N-i, K) return permCount def main(): print(staircasePermCount(5, 2)...
5648a1152089376c4523c36b221fb1da89172484
hjh0808/MSE_Python
/ex110.py
286
3.703125
4
if True: # ̹Ƿ ܰ Ѿ. if False: # ̹Ƿ else Ѿ. print("1") print("2") else: print("3") # 3 Ѵ. else: print("4") # ó ̾ ʿ. print("5") # 5 Ѵ.
bdf1ee6a318d9b02ad75688e4e2a2f5d6af82855
mehdiezz21/projets
/Projet jeux Pygame/projectile.py
1,050
3.515625
4
import pygame from game import * #classe qui gere le projectile #class qui herite de sprite class Projectile(pygame.sprite.Sprite): #definir le constructeur de cette class def __init__(self, player): super().__init__() self.velocity=5 self.player= player self.image = pygame.ima...
9636040ee23fd59137cb912bacce76c35aafad97
xuyang7952/algo
/python_study/09queue/array_queue.py
1,683
4.03125
4
""" Queue based upon array 用数组实现的队列 Author: Xuyang """ from typing import Optional class ArrayQueue: def __init__(self, capacity: int): self._items = [] self._capacity = capacity self._head = 0 self._tail = 0 def enqueue(self, item: str) -> bool: # tail 已经...
3c0103a87b0a618bf87206df75a000326e736888
xuyang7952/algo
/python_study/31_bfs_dfs/bfs_dfs.py
3,103
3.65625
4
"""广度优先和深度优先搜索""" from typing import List, Optional, Generator, IO from collections import deque class Graph: """无向图""" def __init__(self, num_vertices): self.v_num = num_vertices self.adj_tbl = [] for i in range(self.v_num + 1): self.adj_tbl.append([]) def add_edge(...
b654cd6bdae61379fed0808a33f68ce8bf4054ce
ssmita98/store-management-software
/storems/source code/add_to_db.py
4,432
3.6875
4
from tkinter import * import sqlite3 import tkinter.messagebox conn=sqlite3.connect(r"C:\Users\Smita Sharma\Desktop\genstore\storems\database\store.db") c=conn.cursor() result = c.execute("SELECT Max(id) from inventory") for r in result: id=r[0] class Database: def __init__(self, master, *args, **kwargs): ...
0b2a6bca77f144f021de9853df1fb62a2d86d563
ivanrodriguez-lpsr/class-samples
/drawTriangleFigure.py
673
3.765625
4
import turtle def makeTriangle(myTurtle): myTurtle.forward(10) myTurtle.left(120) myTurtle.forward(10) myTurtle.left(120) myTurtle.forward(10) myTurtle.right(240) def makeRow(myTurtle): count = 0 while count < 4: makeTriangle(myTurtle) myTurtle.penup() myTurtle.forward(20) myTurtle.pendown() count ...
936af44341c6bac3e222833fb711babd89d73957
ivanrodriguez-lpsr/class-samples
/convertStuff.py
139
3.859375
4
name = "Ivan" age = "14" print (name +": " + age) name = "Zachary" age = 14 age_as_string = str(age) print (name + ": " + age_as_string)
6b62e82a3188a69a5c99114768683de3ff2e10ea
shanwenhao1/Machine-Learning
/MachineLearingInAction/Code/Chapter3_Random_Forest/trees.py
6,178
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/9/9 # @Author : Wenhao Shan # Dsc : Random Forest learning from math import log def shannon_entropy(data_set: list): """ shannon entropy function, return shannon entropy of data set :param data_set: :return: """ num_entrie...
093d03594680b6eb5a702c5e97aa35ca1b7a48b8
shanwenhao1/Machine-Learning
/PythonMachineLearning/Code/Chapter10/k_means_pp.py
3,393
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/8 # @Author : Wenhao Shan # @Dsc : K-Means Clustering ++ import numpy as np import random from PythonMachineLearning import functionUtils as FTool from PythonMachineLearning.Code.Chapter10.k_means import distance, k_means_function FLOAT_MAX = 1e10...
edf1bf590ee3cd785bdaa3e761db91785b6c16b3
markab4/There-Is-No-Spoon
/RREF.py
2,490
3.90625
4
# Tests if a matrix is in Row Echelon Form / Reduced Row Echelon Form # Mark Abramov def isAll0s(matrixRow): for i in matrixRow: if i != 0: return False return True def hasLeading1(matrixRow): for i in matrixRow: if i == 0: continue elif i == 1: ...
d263842867ff1a214776a70f04c2006acb9b0000
emmaunel/CSCI_141-LabWorks
/Lab 6/select_median.py
3,102
4.3125
4
""" File: select_median.py Assignment: Lab Language: Python 3 Author: Ayobami Adewale<aea8506@rit.edu> Purpose: Calculate and print the optimal location for a store and the sum of the distances that people would have to travel to reach the store from each given location using quick select. """ import time de...
1fc0e567b1d58fe2a360daf51a2c5ac1deda01f9
Hower/NCSS-2013
/Week 3/Graph_N00de.py
907
3.65625
4
class Node: def __init__(self, id, label): self.id = id self.label = label self.neighbours = [] def __str__(self): return "({}: {})".format(self.id, self.label) def add_neighbour(self, neighbour, label): self.neighbours.append((neighbour, label)) def get_neighbours(self, label): if no...
eaf0032a86631226617e023d49950d7632e004dc
Hower/NCSS-2013
/Week 2/You,_Me_and_the_TLA.py
456
3.5625
4
import re fin = open('sentences.txt', 'r').read().split("\n") numOfLines = len(fin) total = 0 mid = re.compile(r"[^A-Z][A-Z]{3}[^A-Z]") start = re.compile(r"^[A-Z]{3}[^A-Z]") only = re.compile(r"^[A-Z]{3}$") end = re.compile(r"[^A-Z][A-Z]{3}$") for line in fin: if mid.search(line) or start.search(line) or only.sear...
b0b06163c5ab927f3271fd5da9208235575a1d10
xxEoD2242/arduino_control_files
/control_mac.py
1,398
3.5
4
# This file contains the code to write the collected data to a text file. # This data will then be processed into JSON and sent via TCP to the # Driver Training Portal API. # Run "pip install pyserial" from serial import Serial # There should be a function that loads the Arduino using arduino-mv # so that there is c...
7a67fc4deae50e0b3d026c97e6ae9ef1f6e3cc26
darienjh/Chapter_5
/2.py
1,322
3.765625
4
stats = {"Strength": "", "Health": "", "Wisdom": "", "Dexterity" : ""} stre = [] heal = [] wis = [] dex = [] while choice != "0": print( """ Welcome to CharacterCreator 0 - quit 1 - strength 2 - health 3 - wisdom 4 - dexterity """) print("You ha...
a3f1844686bda0cc3745122159c678d24f9515ff
MieleSantos/CursoExtencaoPython
/CursoExtencaoPython/Aula05/exemploRecursividade.py
252
3.734375
4
def ImprimeSequencia(a,b) : for x in range(a,b+1) : print(x,end=" ") ImprimeSequencia(14,22) def imprimeSequencia(a,b) : if a==b: print(b) else: print(a,end=" ") imprimeSequencia(a+1,b) imprimeSequencia(14,22)
53b6f07462a0db6daa4d577198c4240a1bf8ca52
MieleSantos/CursoExtencaoPython
/CursoExtencaoPython/aula08/exercicioConta.py
1,000
3.859375
4
class Conta(): def __init__(self,numero,saldo): self.__numero=numero self.__saldo=saldo def getNumero(self): return self.__numero def setNumero(self): self.__numero = numero def getSaldo(self): return self.__saldo def setSaldo(self): ...
9ce1bcf8f40137e40434bd49d1f0536393c53086
MieleSantos/CursoExtencaoPython
/CursoExtencaoPython/aula08/exemplo4.py
750
3.640625
4
class Gato: #construtor def __init__(self,nome,cor): self.nome=nome self.cor=cor self.valor=10 #funcao str def __str__(self): return "gato:" + self.nome + "" + self.cor def __repr__(self): return "gato:" + self.nome + "" + self.cor + "" + sel...
f6e359dea03ed314b5b3714bb169ddacebdc7519
MieleSantos/CursoExtencaoPython
/CursoExtencaoPython/aula4/Exercicio01.py
243
3.828125
4
def linha(n) : if n == 20 : for i in range(n): print(end= "_") else : n = 20 for i in range(n): print(end="_") linha(20)
2e9f4f2ea6306c224c931ea59f421a24cd9b3c3a
MieleSantos/CursoExtencaoPython
/CursoExtencaoPython/aula4/exercicio8.py
98
3.515625
4
def lista(d): l=[] for i in range(d): l.append(i) return l print(lista(10))
e80784d8735d8bd79b7d1a71b94406abbbf50793
jamesread/advent-of-code-2016
/day6/part2.py
556
3.671875
4
#!/usr/bin/python2 password = "" contents = open('input', 'r').read().strip() for index in range(0, 8): charFrequency = {} for line in contents.split("\n"): c = line[index] if c not in charFrequency: charFrequency[c] = 0 charFrequency[c] = charFrequency[c] + 1 sma...
c8b50d14d110ffa73b951dfac86ad42faf351711
8H33W00/piro13
/piro13/Programming_coding_test.py
1,736
3.71875
4
import random class hero: def __init__(self, name, atk, dfs, hp): self.name = name self.atk = atk self.dfs = dfs self.hp = hp def attack(self, enemy): enemy.hp -= self.atk - enemy.dfs def character_info(self): print("이름:", self.name) print("공격력:", s...
1dd9f703bae389007830e1c585892fc1e95d6326
chusehwan/python
/Part1/Chapter_8-14.py
290
3.515625
4
#Cars def make_car(manufacturer, model,**moreinfo): car_lists={} car_lists['manufacturer']=manufacturer car_lists['model']=model for k,v in moreinfo.items(): car_lists[k]=v return car_lists car = make_car('subaru','outback',color='blue',tow='True') print(car)
3f6a8bd72687348e01453ee407eb82ec64cedad9
chusehwan/python
/Part1/chapter_10_6.py
349
4
4
#Addition while True: try: number = int(input('put some number')) except ValueError: print("you put wrong value[first number]") print("Pls try put again") try: number_2=int(input('put some second number')) except ValueError: print("you put wrong value[second number]") result = ...
97d3bf4ea26f3fcc02d8bb495041961a583f0d9f
chusehwan/python
/time_test/time_test.py
537
3.578125
4
import schedule import time from datetime import datetime def job(): print("I'm working...") now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) schedule.every(1).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) sc...
cfff772791e26629c0efddb2e8afcf86de33fe65
chusehwan/python
/Part1/Chapter_7-10.py
490
4.09375
4
#Dream Vacation dream_vacation = {} active_flag= True print('If you could visit one place in the world' ' where would you go?') print('if you want to stop, pls type "quit".') while active_flag: name = input('your name : ') place = input('dream place :') flagp = input('if you want to stop, type "q...
177b87c1c6be3a282024709ce4174dd23e7e38ec
chusehwan/python
/Part1/Chapter_3-9.py
2,040
3.6875
4
from typing import List guest_list=['guest1','guset2','guest3','guest4','guset5'] message = 'Dear ' + guest_list[0] + '! I invite you on my dinner Party!' print(message) message = 'Dear ' + guest_list[1] + '! I invite you on my dinner Party!' print(message) message = 'Dear ' + guest_list[2] + '! I invite you on my di...
5d9fe6c1bafeaea1bdf8e18e926442d6aba80e3f
chusehwan/python
/Part1/Chapter_7-3.py
155
4.09375
4
#Multiples of Ten number = input('say any number : ') if int(number)%10 == 0: print('10 multiple number') else : print('10 not multiple number')
0d9ffda3c216ad8e20137c394dfc9f2c62f8ee7e
chusehwan/python
/baek_jun/while/더하기 사이클.py
559
3.546875
4
def str_convert(data): num = int(data) if num<10: return int(0), num else: return int(data[0]), int(data[1]) str_data = input() init_data = int(str_data) count = 0 while True: # 주어진숫자를 2개로 쪼갬 a, b = str_convert(str_data) # 쪼갠 숫자를 더함 sum_data = a+b # 더해진 숫자를 다시 쪼갬 c, ...
9d46a219e8b2441665ac1eb2684a881c7a15b61c
chusehwan/python
/Part1/Chapter_4-11.py
393
4.0625
4
#pizzas pizza_list = ['pizza_a','pizza_B','pizza_C'] for pizza in pizza_list: print('you like '+ pizza +'!') print('you like pizza very much!') print('Thanks you!') pizza_list.append('added_pizza') print(pizza_list) friend_pizza = pizza_list[:] friend_pizza.append('second_added_pizza') print('my favorite pi...
0877a3d74c3f027402d40cb10a4680d44d2c598d
chusehwan/python
/baek_jun/실습 1/별 찍기 - 9.py
345
3.5625
4
a = int(input()) # 토탈 별수 = a iter_num = a*2-1 st_num = iter_num v_num = 0 for i in range(iter_num): vacant = ' '*v_num star = '*'*st_num p = vacant+star print(p) # 입력받은 수치만큼 별표 줄이기 if i < a-1: st_num -=2 v_num += 1 else: st_num +=2 v_num -= 1
f91eeede6faf3869302b06c32406db1c3e815a59
chusehwan/python
/Part1/Chapter_5-9.py
203
3.796875
4
user_name = ['a','b','c','d','e','admin'] for user in user_name: if user == 'admin': print('Hello special ' + user + ' would~~') else: print('welcome '+ user +' to invite site!')
48f323a82cebbf37c3536bda57d8be2b09bcd3d5
FlavioYgr/LISTA-2-estrutura-de-decisao
/ATV2-7.py
342
3.859375
4
n1 = int(input("primeiro valor: ")) n2 = int(input("segundo valor: ")) n3 = int(input(" terceiro valor: ")) MAIOR = n1 if (n2 > MAIOR ): MAIOR = n2 if (n3 > MAIOR ): MAIOR = n3 print ("MAIOR: ", MAIOR) MENOR = n1 if (n2 < MENOR ): MENOR = n2 if (n3 < MENOR ): MENOR = n3 pr...
5fe9fb0432f49a12c126ac6becfa3f73afa20e4b
xmysdmv/model
/cn/mahang/genetic/NextSpecies.py
361
3.578125
4
# _*_ coding: utf-8 _*_ # 选择过后的10个下一代父本 def nextspecies(newpopulation, selectednumber): # newpopulation 为待选种群,selectednumber为选出的染色体标号 nextspecies_result = [[]] for i in range(len(selectednumber)): nextspecies_result.append(newpopulation[selectednumber[i]]) return nextspecies_result[1:]
ea9471de778308a17a7a553ab37b9aaf40695b31
bradszalach/pythonbeginnerscripts
/CurrencyConverter.py
2,960
4.28125
4
#Currency Converter.py #Scripted by Brad Szalach #Converts USD to Euro or other way around #1 USD = .81 Euro #1 USD = .71 GBP #1 USD = 106.28 JPY #1 Euro = 1.23 USD #1 Euro = .88 GBP #1 Euro = 131.02 JPY #1 GBP = 1.40 USD #1 GBP = 1.14 Euro #1 GBP = 149.08 JPY #1 JPY = .0094 USD #1 JPY = .0076 Euro #1 JPY = .0067 GBP ...
7d83011c0fcc45f60f18eb55e0d442033fbfc478
iambirdpeng/DataBase
/sha1Helper.py
447
3.515625
4
from hashlib import sha1 # 第一步创建sha1对象, # 第二步用对象.update加密pwd ,注意用encode转码, # 第三部用对象.hexdigest()拿到加密后的码 def trans_sha1_pwd(orignal_pwd): s1 = sha1() s1.update(orignal_pwd.encode('utf-8')) #注意要用encode转码 return s1.hexdigest() if __name__ == '__main__': orignal_pwd = input("请输入要加密的密码:") print(tra...
ca849b28919bf3fccafbf5ab0640410db84ab83e
garrett4311/Python-Hashing-Project
/Hashing/Project1_Hashing/Morris_RNG.py
791
4.0625
4
# Garrett Morris # Project 1: Hashing # CMPS 5243: Advanced Algorithm Analysis # March 26, 2020 #This program generates a file and stores random numbers to that file from random import seed from random import randint seed(1) # seed the random number generator randomNums = open("RandomNumberFile1.txt", "w+") nums = []...
39517c7ed941be91dc0438200ff057f88ef1b8e3
rishabh-var123/smartcalculator
/alexa smart claculator.py
2,090
3.734375
4
response=['Welcome to Smart Calculator Made by-:Rishabh Varshney', 'My name is Alexa(Daugter of Google)', 'sorry this is my beyond limit',' Thanks for Enjoy me' ] def extract_from_text(text): l=[] for t in text.split(' '): try: l.append(float(t)) excep...
aa9b7bd421235d55eb0b9f8d3dc5a1250423293d
farazlfc/CP
/Diamond_aka_cherry_pickup.py
3,591
3.859375
4
'''Task Description: Diamond Mine is your new favorite game . Its map is represented as a square matrix. The board is filled with cells, and each cell will have an initial value as follows: • A value ≥ 0 represents a path. • A value of 1 represents a diamond. • A value of −1 represents an obstruction. The basic rules ...
c4cc72485c8205ea502c2e7d7df0009650fd7487
farazlfc/CP
/Sum_of_bit_diff_among_all_pairs.py
607
3.65625
4
def func(arr,n): ans = 0 # Initialize result # traverse over all poss. bit positions for i in range(0, 32): # count number of elements with the i'th bit set count = 0 for j in range(0,n): if ( (arr[j] & (1 << i)) ): #left shift bit to check if that bi...
73cdeadb0220dc1917c47b2e78eacc772f48cb6e
rwedema/BFVP3INF2
/fixme2.py
846
4.25
4
#!/usr/env python3 """ Draw a tree using turtle """ __author__ = "Fenna Feenstra" import sys def tree(branchLen): """ function that draws the tree with stem and branches upwards""" if branchLen > 5: t.backward(branchLen) t.right(20) tree(branchLen-16,t) t.left(40) tr...
1829a214ac72fa9c629a0b6a79a1c2f9d2198d28
rwedema/BFVP3INF2
/_book/printsome.py
304
3.609375
4
#!/usr/bin/env python3 """this programme prints the filename""" __author__ = "fennaf" import sys def main(args): filenames = args[1:] for file in filenames: print('filename: {}'.format(file)) return 0 if __name__ == '__main__': exitcode= main(sys.argv) sys.exit(exitcode)
f959f24da8f580662dbb3d689f29f8f382e4d7f3
Priya2120/list
/que 6.py
476
3.640625
4
# Aao Jodein # Ek code likho jo kissi bhi list ke liye uss list ke do sum ka output karta hai, # ki uss list mei odd numbers ka sum aur even numbers ka sum kitna hai. elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] b=[] c=[] i=1 sum=0 s=0 while i<len(elements): if elements[i]%2==0: sum=sum+element...
8c566149158ea37a7da76313be0701c8b435a6d0
cebeery/SoftwareDesign
/hw3/gene_finder.py
10,074
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 11:24:42 2014 @author: Claire E Beery """ # you may find it useful to import these variables (although you are not required to use them) from amino_acids import aa, codons import random def collapse(L): """ Converts a list of strings to a string by concatenating ...
a0126dcc45b40cf08cd552ba3bd14a0e8b704d40
roushzac/Leetcode
/Convert Sorted Array to Binary Search Tree/Convert Sorted Array to Binary Search Tree.py
1,508
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import math class Solution: def sortedArrayToBST(self, nums): def FillNode(parent, array,side): ''' if side=="le...
75f4ccba0c6eb40548410c0e9088db69d00c197c
roushzac/Leetcode
/Find Mode in Binary Search Tree/Find Mode in Binary Search Tree.py
2,097
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findMode(self, root): """ :type root: TreeNode :rtype: List[int] """ def BFS(node,mode_dict, ...
d7a79046ecf428620994078ab1f04f6a6eedb93b
roushzac/Leetcode
/Minimum Depth of Binary Tree/Minimum Depth of Binary Tree.py
1,311
3.953125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ # if tree is empty, min depth ...
6a1ef289405629462233b35bd5e761330250ee71
ishimko/continuous-queuing-system
/simulator/reader.py
591
3.71875
4
def read_non_negative_float(name): return read_from_keyboard(name, float, lambda x: x >= 0) def read_from_keyboard(name, type_constructor, validator=lambda x: True): result = None valid = False while not valid: result = _try_convert(input('{}: '.format(name)), type_constructor) valid = ...
3ae480e6238e31c63441189d6c9133eb8f4f9075
ayrtondenner/ARP-2017-1
/Lista 1 - Regressão/Respostas - Ayrton Denner/exercicio_dois.py
2,491
3.609375
4
import matplotlib.pyplot as plt import numpy as np # Método para desenhar a grid e deixar ela atrás dos pontos e das retas def prepara_grid(): figure = plt.figure() axis = figure.gca() axis.set_axisbelow(True) plt.grid(linestyle = ":") return # Método para colocar os labels do gráfico def seta...
19313a9a213c1c22cecf9bcf35bd500d04194b4b
Sparrownor1/snake-math
/golomb.py
460
4.0625
4
# Generate the Golomb Sequence using Python # Input how many numbers we want to generate def golomb(limit): sequence = [1, 2, 2] i = 2 while i < limit: # sequence[index] = how many times the number index + 1 shows up in the array count = sequence[i] for _ in range(count): ...
ede7ca1b9c86a7a61e8b99c921ead45aad65002e
Xkdash/Coding-Basics
/Divide and Conquer/BinarySearch.py
1,000
4
4
def _binarySearchConfirm(arr,item): mid=len(arr)//2 if arr[mid]==item: print("Item found: ",item) elif item<arr[mid]: _binarySearchConfirm(arr[:mid],item) elif item>arr[mid]: _binarySearchConfirm(arr[mid+1:],item) else :return def _binarySearchIndex(arr,item,l,r): if r>=l...
fa329ac7357e92d066025855834ee4f31b37ad7f
maliaditya/Python-code-snippets
/Inheritance/inheritanceConst.py
438
3.8125
4
class Animal: def __init__(self, name, color): self.name = name self.color = color class Dog(Animal): def __init__(self,sound,name,color): super().__init__(name,color) self.sound = sound def animal(self): print("DOG") print("Name: ",self.name) ...
9f875f8804bfe229ea0e40ac909049fb41bd1232
maliaditya/Python-code-snippets
/Classes/classVariables.py
645
3.59375
4
class Shopping: #Class Variable declared GST = 0.18 def __init__(self,amount,total_items): self.amount = amount self.total_items = total_items def apply_GST(self): # the class variable can be accessed using class_name or the class instance total_amount = self.amount + sel...
c9c14e388e2f2f54bdad66d2faa49f3f1eeada44
maliaditya/Python-code-snippets
/DailyFlash/August/24_August_2020/prog5.py
378
4.09375
4
meals = {'Panner':'Veg','Mutton Korma':'Non-Veg','Chicken malai':'Non-Veg','Tandoori roti':'Veg','Drumsticks':'Non Veg'} weekday =int(input("enter weekday: ")) if weekday %2 != 0: print("My friend can eat ",len(meals)," dishes.") else: count =0 for a in meals: if meals[a] == 'Veg': cou...
eb8660e94172698cc16c601a60ebfb038d4ad1cd
maliaditya/Python-code-snippets
/DailyFlash/Septmeber/3 sept 2020/prog2.py
107
3.953125
4
def sqrt(num): for a in range(1, int(num/2)+1): if a*a == num: print(a) sqrt(100)
4b011b718351766bc7be3e72d5090375308f673a
maliaditya/Python-code-snippets
/Polymorphism/methodOverloading.py
250
3.8125
4
class Addition: def addnum(self,a1=None, a2=None, a3=None): if a3==None and a2 == None: return a1 elif a3 == None: return a1 + a2 else: return a1+a2+a3 print(Addition().addnum(12,12))
54e0ba8d9d58f636e25bc6dc2da1011a14455eea
maliaditya/Python-code-snippets
/Data Structures/TREE/a.py
181
3.875
4
for a in range(100): if a%15 == 0: print("fizzz buzzz") elif a%3 == 0: print("Fizzz") elif a%5 ==0: print("buzz") else: print(a)
fb7512ed6162e479f0e8b2a669af7d9115171355
maliaditya/Python-code-snippets
/Algorithms/Sorting/insertionsort.py
238
4.21875
4
def insertion_sort(arr): for i in range(1,len(arr)): for j in range(i): if arr[j]>arr[i]: arr[i],arr[j] = arr[j],arr[i] return arr arr = [2,1,5,4,3,9,8] print(arr) sorted_array = insertion_sort(arr) print(sorted_array)
fb68e6a4a665dfe27e60d26ab95b15fac11b069b
maliaditya/Python-code-snippets
/Logical Programs/prime_number.py
174
3.96875
4
n=10 prime = False for a in range(2,n): if n%a == 0: prime = True if prime == False: print("number is a prime number") else: print("not a prime number")
2dfe507ce3096cc15e3c04458dd1a9b2d13ae751
maliaditya/Python-code-snippets
/Data Structures/LinkList/allOperationsOfLinkList.py
3,085
3.734375
4
import time class Node: def __init__(self,data): self.data = data self.link = None class LinkList: def __init__(self): self.start = None def insertInList(self,newNode): if self.start == None: self.start = newNode else: lastNode = self.star...
e5f93334a6c938bf5ab4ed5ea84e3ae02027634f
maliaditya/Python-code-snippets
/DailyFlash/August/20_August_2020/prog5.py
152
3.578125
4
movies ={"The last Samurai":"Tom Cruise","Justice League":"Cavil,Gadot","MI":"Tom Cruise"} tomMovies=[x for x in movies if movies[x]!="Tom Cruise"] print(tomMovies)
8179912075bf8e7ebfec323840b5f67b41a4f16c
maliaditya/Python-code-snippets
/DailyFlash/August/27_August_2020/prog5.py
429
4.0625
4
def isPrime(n): count = 0 for i in range(2,int(n/2)): if n%i ==0: count+=1 return False if count == 0: return True def reverse(s): str = "" for i in s: str = i + str return str n = 23 p = isPrime(n) if p == True: r = reverse(str(n))...
a0a509072780ed7903c29c07540ff26ffc05e7e7
maliaditya/Python-code-snippets
/DailyFlash/August/25_August_2020/prog3.py
392
3.671875
4
names = ['aditya','aadesh','nayan'] f = 0 b =-1 for a in names: c = list(ord(x) for x in a) b = list(ord(x) for x in a) b.reverse() for x in range(len(c)): if c[x] == b[x]: if x == len(c)-1: print(a,"will get the discount") continue else: ...
389f76064fd7a904a2a8ec6a5751a3f31f8f180c
xiaotiankeyi/PythonBase
/python_Base/func/func_iter.py
328
4.0625
4
# 列表具备迭代性,但不是迭代器 # iter函数可以把具备迭代性的对象转变为迭代器 l = ['a', 'b', 'c', 'd', 'e'] def add(): return l.pop() x = iter(add, 'b') # 迭代器迭代碰到"b"时就停止迭代......... print(x.__next__()) print(x.__next__()) print(x.__next__()) # print(x.__next__())
3789314a11863d71f8c86964fc095e64604b4702
xiaotiankeyi/PythonBase
/python_module/turtle_module.py
2,251
3.8125
4
import turtle from time import sleep class MyRectangle(object): def __init__(self, x=0, y=0, width=100, height=100): self.x = x self.y = y self.width = width self.height = height def getArea(self): """计算矩形面积""" return self.width * self.height @property ...
0a60e5ee4d8de31b573585bca3d6aa9cc78cd2ad
xiaotiankeyi/PythonBase
/python_Base/func/func_yield.py
475
3.921875
4
# Generator 与控制流 关键yield的使用 def generator(): print('before') yield # break 1 print('middle') yield # break 2 print('after') x = generator() # next(x) # ==>before # next(x) # ==>middle # next(x) # ==>after # send的使用 def result(): print('开始执行....') val = yield 44 print(...
f242c42283041c713a93409b382018f257f304be
xiaotiankeyi/PythonBase
/python_oo/reflection/reflection.py
1,810
3.703125
4
# 反射只getattr和delattr的应用 class BlackMedium(object): feature = 'Ugly' def __init__(self, name, addr): self.name = name self.addr = addr def __getattr__(self, item): return '你查询的属性%s不存在,运行自定义的getattr' % item def __delattr__(self, item): if item in self.__dict__: ...
388defc207af3c298a9d1b65e6747b9918b8abc7
xiaotiankeyi/PythonBase
/python_oo/oo_object.py
1,719
3.796875
4
# __init__实例属性 """初始化构建函数""" class PePole(object): """类说明定义一个中国人的类""" status = '特征' def __init__(self, name, age, sex, height, weight): self.user = name self.height = height self.weight = weight self.sex = sex self.age = age def Features(self): # retur...
fcd29d47fa69a038c0cb991f41194839a861cb9f
xiaotiankeyi/PythonBase
/python_Base/exercise/exercise_func.py
3,931
3.75
4
"""写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数""" def count(accept): num = list(accept) sum = 0 for total in range(len(num)): sum += total return sum """写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于10,,,并计算出个数""" def extent(accept): string = accept if len(string) > 10: sum = 0 for total ...
d8e9124430e8d00df512614fb61d1275470e6dff
xiaotiankeyi/PythonBase
/python_processThreading/asynico_oo/coroutines_asyncio.py
727
3.515625
4
# 概念:asyncio是3.4以后的协程模块,是python实现并发重要的包,使用事件循环驱动实现并发,实现异步io import asyncio async def aunt(): for i in range(10): print(f'{i}婶婶说,python是世界上最好的语言') await asyncio.sleep(1) # 释放cpu避免阻塞 async def uncle(): for i in range(10): print(f'{i}叔叔说,python是世界上最好的语言') await asyncio.sleep(...
a8e3eb3af9a978fb49becbe35d76ce5b3459ad15
xiaotiankeyi/PythonBase
/python_Base/gather/gather_handle.py
825
3.90625
4
num = {3, 4, 5, 7, 1, 9, 0, "request", "response"} number = {3, 4, 5, 7, 4, 5, 65, 32, 12} # ___set___集合的去重操作 paras = set(num) # ___intersection___求交集,,,,两个变量都存在 num.intersection(number) print(set(num) & set(number)) # ___union___求并集,,,,,把两个变量的元素相加,,,,去重复 num.union(number) print(number | number) # ___difference___差...
fcea59f387eeb4e28a225c10ce4a88a12450faa8
xiaotiankeyi/PythonBase
/python_Base/string/str_formatting.py
826
3.8125
4
''' 字符串格式化.....(%s%d)....... ''' print('\t\t\t\t__%s__代表字符串(str)也能代表数字(int)的格式化') print('\t\t\t\t__%d__只能代表数字(int)的格式化') print('\t\t\t\t__%f__表示接受小数类型......') while True: name = input('name:') # print('名字是%s' % name) age = input('age:') # print('年龄是%d' % age) sex = input('sex:') # print('性别是%s' ...
502dc7ba12b5e2506a8f6a1d52211bc50ad23acb
xiaotiankeyi/PythonBase
/python_Base/func/func_decorator/fun_decorator_authentication.py
1,534
3.921875
4
# 装饰器实现认证机制 user_list = [ {'name': 'alex', 'passwd': '123'}, {'name': 'linhaifeng', 'passwd': '123'}, {'name': 'wupeiqi', 'passwd': '123'}, {'name': 'yuanhao', 'passwd': '123'}, ] current_dic = {'username': None, 'login': False} def welcome(func): # func现在是index def login(*args, **kwargs): ...
ae46706ecef5e38a75dd62889830e44f28169703
xiaotiankeyi/PythonBase
/python_Base/exercise/exercise_game.py
1,611
3.75
4
# 猜大小游戏 import random def call(count=0): asset = 1000 while count < 3: print("\t\t猜大小游戏") print(">>>请输入你竞猜的数字") num = int(input(">>>>>>> ")) robot = random.randint(1, 100) if num > robot: asset = asset + 10 print( "robot出的是{}, 你出的...
ab13af31936dbad80ccfed153bba0edbcdf3ad34
xiaotiankeyi/PythonBase
/python_Base/dic/dict_for.py
748
4.03125
4
""" dict循环操作 """ def handle(): my_dict = {'name': "jack", 'age': "22", 'sex': '男'} # ___keys___获取key值.....默认是获取key for item in my_dict.keys(): print(item) collection = {item for item in my_dict.keys()} print(collection) # __values___获取values值,,, for item in my_dict.values(): ...
be555f1ea9bc7109bdfaaa88ef4d7b2a9554d96c
xiaotiankeyi/PythonBase
/python_processThreading/threading/threading_RLock.py
1,282
3.875
4
# 递归锁 import threading import time '''递归锁是解决死锁的问题.......''' class MyThread(threading.Thread): def actionA(self): R_Lock.acquire() print(self.name, "gotA", time.ctime()) time.sleep(2) R_Lock.acquire() print(self.name, "gotB", time.ctime()) time.sleep(1) R...
a7788c63ab4f6d139dc1959b142a3976a5379d4e
xiaotiankeyi/PythonBase
/python_Base/func/func_built-in_function.py
5,140
4.03125
4
# 内置函数built-in function # _______abs()______返回数字的绝对值 import math print(abs(23)) # _______enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 # for 循环当中, seasons = ['Spring', 'Summer', 'Fall', 'Winter'] for total, i in enumerate(seasons): print(total, i) # ______eval() 函数用来执行一个字符串表达式,并返回表达式的值,(把字符串中的数...
57cc28aff06e12ba071e2e41040bbae3da8e8d59
tnagasaivijayram/lab
/Daa/10.py
663
3.65625
4
# method 2 import numpy as np def floyd(graph ,v): for k in range(v): for i in range(v): for j in range(v): graph[i][j] = min(graph[i][j],graph[i][k]+graph[k][j]) print("After Step",k+1,"Matrix A: ") printsol(graph,v) def printsol(graph,v): for i in r...
0a9c2b2e0e7a4fd8c1c8320faa96bca8dbfa635d
Manogel/padroes-projetos
/facade-decorator-iterator/Interfaces/Iterator.py
267
3.75
4
# -*- coding: utf-8 -*- from abc import ABC, abstractmethod class Iterator(ABC): def remove(self): pass def nextt(self): pass def previous(self): pass def count(self): pass def key(self): pass def rewind(self): pass
c9b8904ce752a6b4f77c8897e68a66cbb9b313ab
Manogel/padroes-projetos
/semana2/Memento/Game.py
1,660
3.671875
4
# -*- coding: utf-8 -*- from Memento import Memento import math class Game(object): def __init__(self, perguntas): self.pontos = 0 self.perguntas = perguntas self.memento = [] self.startGame() pass def setState(self, item, x): # print(f'ORIGINATOR: Mudando o estado para {self.state}')...
6ffa8266ea17f0ec267ef38230600322ed51a80b
ntuan1411t3/SI
/test 2.py
629
3.78125
4
from classifier import keyword_detection, sentence_classifier TARGET_KEYWORDS = ['SHIPPER','CONSIGNEE', 'NOTIFY', 'ALSO_NOTIFY', 'POR', 'POL', 'POD', 'DEL', 'VESSEL'] # Test keyword sentence = 'shipper/exporter' keyword = keyword_detection(sentence) print('keyword --->', keyword) sentence = 'pre-carriage by *' keywor...
bd7bc573c026309a11b5fb6e10c81dd62aebc3cb
ed-austin/working
/knight.55.py
2,257
3.9375
4
#! /usr/bin/python3.3 # # Description: # script to print out allowable moves of a knight # which is on a specified square. # Number the squares as below, then # calculate each possible value # for the next move # # 5 * 5 Square: # 0 1 2 3 4 # 5 6 7 8 9 #10 11 x 13 14 #15 16 17 18 19 #20 21 22 23 24 # # allo...
6637da1989561403dc514653ce67f407ee14e914
shirleyChou/LeetCodeUsingPython
/code/valid_palindrome.py
1,106
4
4
#!/usr/bin/env python # encoding: utf-8 # https://oj.leetcode.com/problems/valid-palindrome/ # Difficulty: Easy # Tags: Two Pointers, String """ Question 125: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a cana...
d6c2e4cd83fad508f71c0d21857f82b266813fea
shirleyChou/LeetCodeUsingPython
/code/roman_to_integer.py
788
3.765625
4
#!/usr/bin/env python # encoding: utf-8 # https://oj.leetcode.com/problems/roman-to-integer/ # Difficulty: Easy # Tags: Math, String """ Question 13: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. """ class Solution: # @return an integer def romanT...
e9ba71695f47d9d4970ce15bb662ba974ca21731
jmaletto1/Techdegree-Project-3
/phrasehunter/phrase.py
873
3.75
4
# Create your Phrase class logic here. from .character import Character class Phrase: def __init__(self, phrase): self.phrase = phrase self.letters = [] for i in phrase: self.letters.append(Character(i)) def display_phrase(self): for x in self.letters: ...
330143dc7e2f020e02b16fd7de5d724d0171e7b4
martin-bjork/return-of-the-spheres
/rots/physics_engine/broadphase.py
3,062
3.84375
4
# Broadphase collision detection algorithms import shapes def shape_surface(shape, surface): ''' A broadphase collision detection algorithm for collisions between shapes and surfaces. Uses the shapes' bounding spheres and checks whether this sphere is close to the infinite plane coinciding with th...
f41aac3ec46348ebf32a29fca79175e13cace938
martin-bjork/return-of-the-spheres
/rots/physics_engine/simplices.py
1,437
3.71875
4
# Simplex class class Simplex: def __init__(self): self._points = [] def add(self, item): ## # TODO: Should be something like this in order ## # to not try add points that already are in the simplex. ## # Must edit GJK to handle this scenario to to add this. # if item i...
0be9b03e91d3a830fc63b04caa47e29444d2c3db
MatthewDCantor/Simulations-
/grocery_store_sim.py
5,485
4.21875
4
import simpy import random import statistics import matplotlib.pyplot as plt """ Purpose -- Compare the average wait time for a customer at a grocery store between having them wait in one line vs. a line for each cash register. """ """ Below is the code for simulating a grocery store with individiual lines for each...
da1ecf2b84e448b2594f8c48f5e02df51f015a51
Artem-Vorobiov/Tic-Tac-Toe
/ttt_3.py
3,241
3.921875
4
import os import time import random # Define the board board = ['',' ',' ',' ',' ',' ',' ',' ',' ',' '] def print_the_header(): print('\n\n\t\t\t\t_______ TIC--TAC--TOE _______\n\n\n') def print_board(): print(' | | ') print(' '+board[1]+' | '+board[2]+' | '+board[3]+' ') print(' | | ') prin...
2cfe959579cedd6b2a7f917a19bc4ec6032c8276
DarisaSupriya/python-assignment-12
/keyexist.py
215
3.9375
4
d={1:1,2:4,3:9,4:16,5:25} def is_key_present(x): if x in d: print("key is present in dictionary") else: print("key is not present in dictionary") is_key_present(4) is_key_present(23)
3bdfd7e766698e4ea949b05fa21b64dae14700f6
vaibshukla/Python
/Stack/deciBin.py
321
3.546875
4
import myStack def divideBy2(num , base): digits = "0123456789ABCDEF" s = myStack.Stack() while num > 0 : rem = num % base s.push(rem) num = num // base binaryStr = "" while not s.isEmpty(): binaryStr = binaryStr + digits[s.pop()] return binaryStr print(divideBy2(26 , 26)...
6460ad209c985b8d00943f3bc28edfd0f11f2951
sunnybio/Object_detection_yolo_v3
/Model/test.py
281
3.71875
4
def Repeat(x): s = len(x) repeat = [] for i in range(s): k = i + 1 for j in range(k, s): if x[i] == x[j] and x[i] not in repeat: repeat.append(x[i]) return repeat l= [1,2,3,4,4,5,5,6] a=list(set(l)) print (a)
dad637d8b9966070f7a1dfe5abe7314d4554ff8e
cwang25/-Shakespeare-in-Motion-Senior-Design-Project-
/packages/custom/demo/PythonScripts/RestCall.py
2,924
3.515625
4
""" Created on Sep 21, 2015 @author: hans wang @author: Anna Dubovitskaya """ import requests # import json class RestCaller: mean_news_article_url = "http://localhost:3000/api/demo/newsarticles" connect_url = None def __init__(self, url=mean_news_article_url): self.connect_url = url pr...
f87df7bacd5a412dcff28fa0bfc297bfb35621b3
saptwa/numpy_stack
/numpy_basics.py
5,997
4.65625
5
import numpy as np from datetime import datetime ######### numpy basics ######### # python list L = [1, 2, 3] # equivalent numpy array A = np.array([1, 2, 3]) # loop through the list for e in L: print("element of list L: {}".format(e)) # loop through the numpy array for e in A: print("element of numpy arr...
2fae6de3cc45cae76936c8253f9951cfad720848
tinadotmoardots/learning
/python/RPSv3.py
1,223
4.375
4
# This is a version of rock, paper, scissors that you can plan against a computer opponent import random player_wins = 0 computer_wins = 0 print("Rock...") print("Paper...") print("Scissors...") while player_wins < 2 and computer_wins < 2: print(f"Player Score: {player_wins} Computer Score: {computer_wins}") play...
16570da1dfa1c24e6b69f75998c62dbb788d3ace
spiolynn/keras_learning_
/temp/keras_tensorboard.py
1,004
3.71875
4
''' keras模型可视化 ''' # keras learning from keras.layers import Input, Dense from keras.models import Model import numpy as np from keras.callbacks import TensorBoard ###################### data data = np.ones((100,784)) labels = np.zeros((100,10)) ###################### ################################## model # 这部分返回...