blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fbee40adb066a74cfbe3db56013a1f6dc02ba6e8
ppg003/Tiku
/Meituan/3.py
1,430
3.53125
4
""" http://cv.qiaobutang.com/post/55c483380cf2b4db80726f3d 给定N个磁盘,每个磁盘大小为D[i],i=0...N-1,现在要在这N个磁盘上"顺序分配"M个分区,每个分区大小为P[j],j=0....M-1。 顺序分配的意思是:分配一个分区P[j]时,如果当前磁盘剩余空间足够,则在当前磁盘分配; 如果不够,则尝试下一个磁盘,直到找到一个磁盘D[i+k]可以容纳该分区; 分配下一个分区P[j+1]时,则从当前磁盘D[i+k]的剩余空间开始分配,不在使用D[i+k]之前磁盘末分配的空间; 如果这M个分区不能在这N个磁盘完全分配,则认为分配失败,请实现函数,is_allocable判...
e8278e64263352c641d5b0d76588c055cee6b294
mhejl/howto
/python_lessons/examples/example_02.py
1,016
3.59375
4
# magic methods # Typy class Point2: def __init__(self, x=0.0, y=0.0): self._x = x self._y = y @property def x(self): return self._x @x.setter def x(self, value): self._x = value @property def y(self): return self._y #override ...
790fcdd7026304cddc50dc13d69de109ddfa7554
JulyKikuAkita/PythonPrac
/cs15211/SentenceScreenFitting.py
4,121
4
4
__source__ = 'https://leetcode.com/problems/sentence-screen-fitting/' # Time: O(r + n * c) # Space: O(n) # # Description: 418. Sentence Screen Fitting # # Given a rows x cols screen and a sentence represented by a list of non-empty words, # find how many times the given sentence can be fitted on the screen. # # Note: ...
15c638e41aa61e84a8eba2d1b00bb6451095ff6c
marcelogabrielcn/ExerciciosPython
/exe062 - Super progressão aritmética v3-0.py
477
3.921875
4
print('Gerador de PA') print('-=-' * 10) primeiro = int(input('Qual o primeiro termo da PA? ')) razao = int(input('Digite a razão da PA: ')) termo = primeiro cont = 1 total = 0 mais = 10 while mais != 0: total += mais while cont <= total: print('{} > '.format(termo), end='') termo += razao ...
ec3d5e79c1eb7c7a02935e2465e5c0854e130b44
SoniaPuri1/FST-M1
/Python/Activities/Activity 7.py
186
3.890625
4
# List Sum Calculator numbers = list(input("Enter the numbers seperated by commas:").split (",")) #numbers = [3,4,5] sum = 0 for i in numbers: sum += int(i) print (sum)
1f3bcda2373388f6cb9072a6acc4e764e2ffc057
ataylor1184/cse231
/Proj04/proj04.py
2,352
4.09375
4
#============================================================================== # This program is used to determine if you are laughing or not # It does so by checking for patterns in the charectors entered # Any combination of H followed by A or O followed by H again # and ending in !, is considered laughing #===...
762e774b05b606950e767b836602a5caa2cee608
tibetsam/learning
/hashlogin.py
609
3.640625
4
import hashlib db={} def register(): username=input('Username:') password=input('Password:') #global db h_password=password+username+'the-Salt' db[username]=hashlib.md5(h_password.encode('utf-8')).hexdigest() print ('Done!') return def login(): username=input('Username:') passw...
6d3ff0db4352d992bbdebdfd957bc069e9f62b8c
BerezinAlexander/edge_op
/edge_op/primitives.py
2,775
3.984375
4
# Примитивы from math import sqrt class Point(object): x = 0 y = 0 def __init__(self, crd=[0, 0]): self.x = crd[0] self.y = crd[1] def crd(self, crd): self.x = crd[0] self.y = crd[1] def getList(self): return [self.x, self.y] class Line(object): ...
d8bfcd767d37e8f97c5ea68272467c6ad2e4214a
sheikh210/LearnPython
/program_control_flow/forLoops.py
861
4.09375
4
parrot = "Norwegian Blue" # Similar for for-each loop in Java - Define the variable (character) contained within the iterable object (parrot) # for character in parrot: # print(character) # value = "9,342;534,029 134-390]619" # separators = "" # # for char in value: # if not char.isnumeric(): # separa...
32f961efcf6ca43b127757ff24e613a8d9bb6406
SaidNM/Teoria-Computacional
/AutomataNoDet/AND.py
1,030
3.8125
4
def automata(cadena): estados=[] trayectoria=[] estado=0 for elemento in cadena: if (estado==0): estado=estadoCero(elemento,trayectoria) estados.append(trayectoria) print elif(estado==1): estado=estadoUno(elemento,trayectoria) estados.append(trayectoria) elif(estado==2): estado=estadoDOs(ele...
3b63da543d2c5644c343e685a1c487a3adcfb0dc
cwhsu023/pbc_project
/mousedrawline.py
570
3.703125
4
from tkinter import * def main(): root = Tk() w = Canvas(root, width=200, height=200, background="white") w.pack() def _paint(event): # event.x 鼠標左鍵的橫坐標 # event.y 鼠標左鍵的縱坐標 x1, y1 = (event.x - 1), (event.y - 1) x2, y2 = (event.x + 1), (event.y + 1) w.create_oval...
3d7781bd3539eb1aef91e797867eafd8a6ac21d5
candyer/leetcode
/2020 September LeetCoding Challenge/21_carPooling.py
2,304
4.1875
4
# https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3467/ # Car Pooling # You are driving a vehicle that has capacity empty seats initially available for passengers. # The vehicle only drives east (ie. it cannot turn around and drive west.) # Given...
1e7c0ddb3d83bb26eebd6b60b4b06a18c1789fa9
andiainunnajib/basic-python-b7-b
/if_else.py
192
3.875
4
a = int(input("Masukkan a: ")) b = int(input("Masukkan b: ")) if a > b: print("a lebih besar dari b") elif a == b: print("a sama besar dari b") else: print("a lebih kecil dari b")
4242b7b75a6d54426ba38b7fc3c4dfe4fc599df0
kamaalpalmer/StockPredictionML
/p2data/quartiles.py
891
3.6875
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np file_name = "dow_jones_index.data.csv" #f = open(file_name) #data = pd.loadtxt(fname=f, delimiter = ',') # these come from reading the names file; could be first line in some datasets cols = ['quarter', 'open', 'high', 'low', 'close', 'volume', ...
13d608787bebef1f66a9dd9c9b313fbf072be824
gabriellaec/desoft-analise-exercicios
/backup/user_084/ch59_2020_03_17_22_52_16_143390.py
105
3.703125
4
def asteriscos(n): n=int(input('escolha um numero positivo: ') y='*' print (y*n) return n
feeb8440c5d9d636922f153694a2aeab6a4ce988
Nimor111/101-v5
/week6/stack.py
986
3.90625
4
class Node: def __init__(self, value=None, link=None): self.value = value self.link = link class Stack: def __init__(self): self.start = None def empty(self): return self.start is None def push(self, el): if self.empty(): self.start = Node(el) ...
100a059e463491f97c8508893bdbc5a54a210346
nbonham/507project1
/gradecalc.py
6,323
4.03125
4
#import csv ## Part 1: [8 pts] Create a dictionary of the student that is organized as shown [note that the dictionary is “pretty printed” here for readability--you don’t need to do this. Just calling print(my_dict) is OK] : - DONE ## {'Julie': {‘Assn 1’:'9', ‘Assn 2’: '19', ‘Assn 3’: '9', ‘Final Exam’: '22'}, ## ...
36f1357972f91991d331161536171d44ecbc0972
diego-garcia-martin/PythonIntroCourse
/Ejemplo.py
609
3.578125
4
import turtle import random import player turtle.bgcolor("black") turtle.screensize(800, 400) # de -400 a 400 en x y de -200 a 200 en y bob = player.Player("Bob", "blue", -400, -200) joe = player.Player("Joe", "red", -400, 0) susan = player.Player("Susan", "pink", -400, 200) for i in range(1000): bob.move() ...
c760117b6f3ea8b0cb7479606fac216d744d739a
xuanziwenzi/pythonzixue
/haohaoxuexi/ceshi.py
470
4.1875
4
##print('hello,',end = ' ') ##print('world.') #5.4.2 ##name = input('what is your name? ') ##if name.endswith(name): ## print("hello,Mr.{}".format(name)) ## #5.4.5 name = input('what is your name?') if name.endswith('gumby'): if name.startswith("mr."): print('hello,mr.gumby') elif name.startswi...
cbc0add73868064ff808641b3315463cbfa1185b
EricPoehlsen/Echo
/irc_socket.py
4,369
3.703125
4
import socket import datetime import platform import os class IRC: irc = socket.socket() def __init__(self): self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def send(self, msg): """ sends a raw message to the server Note: Commands are implemented...
97632073e77fa86f4de1b82e6a193c51ee0e9fd5
ASHISH-KUMAR-PANDEY/python
/Sum_of_GP.py
439
3.765625
4
# Python Program to find Sum of Geometric Progression Series import math def sumofGP(a, n, r): total = (a * (1 - math.pow(r, n ))) / (1- r) return total a = int(input("Please Enter First Number of an G.P Series: : ")) n = int(input("Please Enter the Total Numbers in this G.P Series: : ")) r = int(input("Pleas...
23b412ba192528b76a5d1b8b6623a77ec238b19a
sukanta-27/DSA_prep
/Stack/ExpressionConversion.py
2,207
3.71875
4
class Conversion: def __init__(self): self.stack = [] self.precedence = { '(': 0, '+': 1, '-': 1, '*': 2, '/': 2 } def greaterThanOrEqualToTop(self, operator): # Checks if the operator in greater in terms of precedence...
2ad2919a717ce6810501d0695f22768bd01f5f86
Naveen479/python
/test_input2.py
267
4
4
#!/usr/bin/python name = raw_input('what is your name::') age = int(raw_input('what is your age::')) income = float(raw_input('what is your income::')) print ('Here is the data you entered::') print ('Name:', name) print ('age:',age) print ('income:',income)
6849fbe05f25e8a5bb05e493feee3598b098099a
bnow0806/sparta_algorithm
/week3/08_queue.py
1,282
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.tail = None def enqueue(self, value): # 어떻게 하면 될까요? #head tail #[3] -> [4] -> [5] new_node = Node(value) ...
163aca2f8d5d5bc47c6947e0a38897af7a21ef09
MrCellenge/kodeklubben
/steg 8.py
430
3.875
4
from turtle import* from random import randrange,choice colors=['red','blue','green','purple','yellow','lime'] def poly(sides,length): angle=360/sides for n in range(sides): forward(length) right(angle) for count in range(10): pencolor(choice(colors)) right(randrange(0,...
4f0c05ef624fc4639114b676b38d5979990ee934
tubaDude99/Old-Python-Exercises
/Unit 1/3Practice3a.py
4,042
4.40625
4
#!/usr/bin/env python # coding: utf-8 # # Lab 3a # ## Conditionals Practice # # ----- # # ### Student will be able to # - **Control code flow with `if`... `else` conditional logic** # - Using Boolean string methods (`.isupper(), .isalpha(), startswith()...`) # - Using comparision (`>, <, >=, <=, ==, !=`) #...
96b732d47eaecd42a72402443f121b7cfe089fc9
pratheep123/guvi222
/sumofdigits.py
140
4
4
a=int(input("Enter the digits:")) sum=0 while (a>0): remainder=a%10 a=a//10 sum=sum+remainder print("The sum of a:",sum)
89e238c6b24747beb8955a61673a4e1ee706ebc5
yichong-sabrina/learn-python
/Chap1 Basis/1_2 List Tuple.py
1,245
4.5625
5
# List MyClass = ['Alice', 'Bob', 'Cindy', 'David', 'Edgar', 'Frida'] print(MyClass[0]) # Subscript begins from 0 print(MyClass[-1]) # Subscript -1 represents the last element length = len(MyClass); print(length) ...
160215f284f94194c83a13433cbffd0f118c1572
GabrielJar/Python
/1a semana/fatura.py
342
3.8125
4
name = input("Digite o nome do cliente: ") expirationDay = input("Digite o dia do vencimento: ") expirationMonth = input("Digite o mês do vencimento: ") value = input("Digite o valor da fatura: ") print("Olá, ", name) print("A sua fatura com vencimento em", expirationDay, "de", expirationMonth, "no valor de R$", value...
7eca02ae0bd62b82085d35368a661b327d0063df
to-yuki/pythonLab-v3
/sample/4/Other_Function.py
379
3.625
4
# デフォルト引数 def funcDefArg(x=0,y=0): print(x) print(y) funcDefArg() # 任意引数 def funcMultiArg(*n): print(n) print(n[2]) funcMultiArg(10,20,30,40) def funcKeyArg(id='null',name='null'): print(id) print(name) # キーワード引数を使用した呼び出し funcKeyArg(name='Yamada',id='001') # ラムダ式 f = lambda x: x + 1 ans = f(5) print(ans)
162bf9c2b95fb5a7b13cf9c577fc71bf1eabaa17
victorh800/sfcurves
/tests/hilbert_outline.py
1,097
3.625
4
#!/usr/bin/env python3 import sys import random from sfcurves.hilbert import forward, reverse, Algorithm from sfcurves.outline import wall_follower def assert_equals(actual, expected): if actual != expected: print(' actual:', actual) print('expected:', expected) assert False if __name__ == '__main__': # or...
4242c50449055d0f86fbafc64be56e995d722709
KPHippe/AccelerometerApplication
/pythonEchoServer/echoServer.py
1,080
3.71875
4
import socket #Creates a TCP Socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #We bind the socket to port 9999 s.bind(('', 9999)) #We allow 5 connections to be in the queue, we are waiting for 1 or more (up to 5) connections s.listen(5) while True: #We accept the incoming connection, wait for a connec...
96add58225e669eadd157d80f432fa6b94715d58
rblack42/math-magik-lpp
/mmdesigner/ArcAirfoil.py
1,009
3.734375
4
# -*- coding: utf8 -*- """ ArcAirfoil ~~~~~~~~~~ height function for circular arc airfoil """ import math class ArcAirfoil(object): """manage circular arc airfoil""" def __init__(self,chord, camber, spar_size): self.chord = chord c = chord - 2 * spar_size self.camber = ca...
f9cf1703c0ef53c675f66995ed0a5ad16e4c747a
keionbis/SmartMouse_2018
/docs/ipynb_gen_py/DC Motor Simulation.py
5,417
3.796875
4
# coding: utf-8 # # DC Motor Simulation # Look at the dynamics_model.pdf for the explanation behind this code. # In[1]: import numpy as np import matplotlib.pyplot as plt # In[2]: def simulate(V, J, C, K, R, L, theta_dot=0, i=0): # simulate T seconds T = 5 dt = 0.01 ts = np.arange(0, T, dt) ...
7976e479fb3da78d5d730b99fdbde61152b4a0be
chenxy3791/leetcode
/array-and-string/removeElement.py
3,723
3.53125
4
""" 让我们从另一个经典问题开始: 给定一个数组和一个值,原地删除该值的所有实例并返回新的长度。 如果我们没有空间复杂度上的限制,那就更容易了。我们可以初始化一个新的数组来存储答案。如果元素不等于给定的目标值,则迭代原始数组并将元素添加到新的数组中。 实际上,它相当于使用了两个指针,一个用于原始数组的迭代,另一个总是指向新数组的最后一个位置。 重新考虑空间限制 现在让我们重新考虑空间受到限制的情况。 我们可以采用类似的策略,我们继续使用两个指针:一个仍然用于迭代,而第二个指针总是指向下一次添加的位置。 总结二 这是你需要使用双指针技巧的一种非常常见的情况:同时有一个慢指针和一个快指针。 解决这类问题的关键是:确...
d3c3c96930096eeb9dbcecbcd58c3c1a7434a916
Dong-Ni/PythonDemo
/eg97.py
298
3.75
4
#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == "__main__": filename = input("输入一个文件名字:\n") fp = open(filename, "w") ch = input("输入一个字符:") while ch!="#": fp.write(ch) print(ch, end=" ") ch = input("") fp.close()
d30e421050f8d9b28da2626d1eb51929d0baca53
jayala-29/python-challenges
/advCalc2.py
2,832
4.15625
4
# function descriptor: advCalc2() # advanced calculator that supports addition, subtraction, multiplication, and division # note: input from user does NOT use spaces # part 2 of building PEMDAS-based calculator # this represents parsing an expression as an algorithm # for operations in general, we go ...
5735977951318e2fead7a5ee65f3ab6689ea86bc
brianchiang-tw/UD1110_Intro_to_Python_Programming
/L7_Advanced Topics/Quiz_Iterators and Generators.py
1,930
4.28125
4
# Q1: # Quiz: Implement my_enumerate # Write your own generator function that works like the built-in function enumerate. # Calling the function like this: ''' lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"] for i, lesson in my_enumerate(lessons, 1): pr...
329a13e26a26fcfc62c707ae1e40971aa85d7f7a
mherna42/initials
/initials.py
153
3.890625
4
def get_initials(fullname): """ Given a person's name, returns the person's initials (uppercase) """ # TODO your code here print("Hello World")
b4ff6e7fdf170afc504b5cddbda73a5599cb9742
lujamaharjan/IWAssignmentPython1
/DataType/Question35.py
399
4.53125
5
# 35.​ Write a Python program to iterate over dictionaries using for loops. our_dic = {'apple':1, 'banana':4, 'coconut':7} #gives key only for key in our_dic: print(key, '=', our_dic[key]) #iteraties as tuple for item in our_dic.items(): print(item) for key, value in our_dic.items(): print(key, '=>', value) for...
46fa89ce156eefdbc722a35b122663b089d6c655
YuYong0408/Python-Crash-Course
/cars.py
912
4.375
4
# coding=UTF-8 # sort ĸ˳иģ ͨreverse = True ĸ cars = ['bmw', 'adui', 'benz','toyota','subaru'] cars.sort() print(cars) cars.sort(reverse = True) print(cars) # sorted бʱ cars = ['bmw', 'adui', 'benz','toyota','subaru'] print(sorted(cars)) print(sorted(cars,reverse = True)) # ԭб˳򲻱 print(cars) # бת ...
7f5459e37150d9703cc1afcc5968317895c9e68f
ay701/Coding_Challenges
/tree/leftNodesBST.py
1,231
4.375
4
# Print Left Nodes of a Binary Tree # Given a binary tree, return the left-most node of each level in the tree. # https://www.geeksforgeeks.org/print-left-view-binary-tree/ # Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n). # # Input : # 1 # /...
67b9929db7253fd3aba531db8d17bc96dea1cd37
lincky1103/GitCode
/ex15.py
281
3.734375
4
from sys import argv script, filename = argv txt = open(filename) print('Here is your file: %r.' %(filename)) print(txt.read()) print('Also ask u to type it again:') file_again = input('> ') txt_again = open(file_again) print(txt_again.read()) txt.close() txt_again.close()
e116caa19e722677a436a8f1a623d9a2bb7eb6f2
kitagawa-hr/Project_Euler
/python/042.py
1,205
3.84375
4
""" Project Euler Problem 42 ======================== The n-th term of the sequence of triangle numbers is given by, t[n] = 1/2n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical pos...
257dc3a7f3249c16feca736677b6720f1b91b681
gabriellaec/desoft-analise-exercicios
/backup/user_014/ch16_2020_04_03_23_57_22_226057.py
157
3.59375
4
conta_inicial = float(input('Qual foi o valor da conta? ')) conta_final = conta_inicial * 1.1 print('Valor da conta com 10%: R$ {0:.2f}'.format(conta_final))
61e6a13ae6d35e08c6eba924bd8480061fa171d1
TrainingByPackt/Python-Fundamentals-eLearning
/Lesson03/3_stringIndexSlice.py
174
3.53125
4
colour = input('Please enter hex colour value:') r = colour[0:2] g = colour[2:4] b = colour[4:6] print(r, g, b) r = int(r, 16) g = int(g, 16) b = int(b, 16) print(r, g, b)
48c81f2851622ab5e42d14b11e68728bc98dcd15
koonerts/algo
/py-algo/grokk-tci/dual-heaps.py
7,796
3.734375
4
import heapq from heapq import * class MedianOfAStream: def __init__(self): self.min_heap = [] self.max_heap = [] def insert_num(self, num): if not self.max_heap: heappush(self.max_heap, -num) else: if num < -self.max_heap[0]: heappush(s...
adbd9ac199ca78604a8c2a260309b1c0a8fac0ea
Sohone-Guo/The-Unversity-of-Sydney
/NoSQL 2016/Neo4j/neo4j_query.py
5,029
3.625
4
from py2neo import Graph graph = Graph(password = 'neo4jneo4j') print('Simple query:') print('1: Given a user id, find all artists the user\'s friends listen.') print('2: Given an artist name, find the most recent 10 recent 10 tags that have been assigned to it.') print('3: Given an artist name, find the top 10 user...
9fd298321bf13377201d1b755eee5ecb15fd0151
elad-rubinstein/threads-python
/threads task two.py
1,755
4
4
""" Threads_competition """ import constant from queue import Queue import threading import time lst_names = [] def get_score(threads_name: str, event: threading.Event, queue: Queue): """ According to the event, the func take a score from a global list and put a name in another global list :param t...
0135db039501fcc411c8f1e63b2d61afe9f55090
masontmorrow/Intro-Python
/src/dicts.py
643
4.40625
4
# Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. a = { "lat": 35.4675602, "lon": -97.5164276, "name": "OKC" } b = { "lat": 37.7749295, "lon": -122.4194155, "name": ...
98aa1bff99659189195066b6855c965c5e9c8457
jeancre11/PYTHON-2020
/CLASE 2/codigo10 lista par e impar.py
488
3.625
4
lista=[100, 20, 21, 23, 24] #lista_impar 21 23 #lista_para 10 20 24 cond=23 in lista lista_par=[] lista_impar=[] #devuelve true o false para el elemento print(cond) print(lista) for val in lista: #print(val, end=" ") if val%2!=0: break print(val, end=" ") print("") #print("AHORA TENEMOS") #list...
62c3e9cd9d412f4f32fef6ee86fb944d69f5e6e3
hyunjun/practice
/python/problem-string/uncommon_words_from_two_sentences.py
949
3.578125
4
# https://leetcode.com/problems/uncommon-words-from-two-sentences # https://leetcode.com/problems/uncommon-words-from-two-sentences/solution class Solution: # 63.44% def uncommonFromSentences(self, A, B): if (A is None or 0 == len(A)) and (B is None or 0 == len(B)): return [] ...
a9e664c7ded3abd88f4ae034989edcd8cc9f1378
hellohano/my_leetcode
/Path Sum/Path Sum.py
628
3.828125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean def hasPathSum(self, root, sum): return self.dfs...
5b9c5069fee35e8678ba1c1ef8c1ae99c78e9cf9
akyare/Python-Students-IoT
/2-data-structures/4-comprehensions/DictionaryComprehension.py
678
4.46875
4
# Look at ListComprehension if you have forgotten the comprehension theory. # Lets do an example of dictionary comprehension: random_chars = {x: chr(x * 50) for x in range(11)} # Using the built-in function chr() to convert integers to chars. # Lets see what we got here using the unpacking technique: for key, value...
027884b3bbea959a692e31e4454b4b63f56b32f0
harrislapiroff/aoc-2018
/d1_2.py
793
3.796875
4
from typing import List def first_frequency_reached_twice( changes: List[str], initial_value: int = 0 ) -> int: value = initial_value frequencies_reached = () num_changes = len(changes) change_ints = [int(n) for n in changes] i = 0 while value not in frequencies_reached: # Add...
59bb75d9bea8dd055544ea08414f6d430a7f4e42
rohitkottamasu/Tictactoe
/tic2.py
1,579
3.71875
4
#tic-tac-toe import sys board=[] board1 = [['00','01','02'],['10','11','12'],['20','21','22']] p=0 def print1(): for i in range(3): for j in range(3): sys.stdout.write("%s | " % board[i][j]) print "\n-------------" def positions(): board1 = [['00','01','02'],['10','11','12'],['20','2...
b293389a91c98dd5d4421a2d3728ed55b06ae68b
emcraciu/PEP21G02
/modul6/app1.py
1,385
4.34375
4
# Create an object for a shop that when iterated will return all of the products in the shop class Shop: # constructor receive list of products in shop def __init__(self, products: list): self.products = products # iter method must return an object that is an iterator or generator def __iter__...
461123885e4d456fa9b47b7387f51e504a7fe7fb
MacHu-GWU/pyrabbit-python-advance-guide-project
/pyguide/p3_stdlib/c10_functional_programming/functools/lru_cache.py
2,321
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ LRU (least recently used) cache这种缓存能将函数最近N次被调用的输入参数和返回值 缓存起来, 每次有新的访问时, 会首先到缓存保存过的输入参数中查找, 如果找不到再真正 执行函数。 LRU缓存的典型作用就是新闻客户端, 例如缓存保存最新的20篇文章。用户每次登陆, 服务 器就不需要去读取数据库, 而可以直接把缓存中的内容推送给用户。 注: 此模块在Python3.2之后才出现 Reference: https://docs.python.org/3.3/library/functools.html...
fa0ed3fdb0858ad68ab90fd291d2b397b8436051
SergioO21/intermediate_python
/power_in_dictionaries.py
469
3.90625
4
def run(): power_3_dict = {} # 1000 sqrt challenge sqrt_1000_dict = {i: i ** 0.5 for i in range(1, 1001)} # Dictionary comprehension form power_dict = {i: i ** 3 for i in range(1, 101) if i % 3 != 0} # Common form for i in range(1, 101): if i % 3 != 0: power_3_dict[i] ...
90a55ef8f89321593ebaa1fd95068f18677945dc
thivatm/Hello-world
/Python/CurrentDirDetails.py
627
3.828125
4
import os import csv import io # os.walk returns three tuples- dirpath, dirname, filenames. # We can use them and get the list of the files and folders of the current directory. filenames = [] for root, dirs, files in os.walk(".",topdown = False): for name in files: print(os.path.join(root,name)) filenames.ap...
6c54ab805d54c4824511e565058e25a09c9d6682
Niatruc/tf_test
/rnn_test.py
2,874
3.828125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 数据 mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # 超参 lr = 0.001 # 学习率 training_iters = 100000 batch_size = 128 # display_step = 10 n_inputs = 28 # 图片28×28 n_steps = 28 # 时间步,28步 n_hidden_units = 128 # 隐藏层神经元数目 n_cl...
02926f4a00ca4cff46f864ce927616e0d8c1e42d
lidianxiang/leetcode_in_python
/堆/347-前K个高频元素.py
2,476
3.796875
4
""" 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], k = 1 输出: [1] """ import heapq import collections class Solutions: """ 1、首先建立一个元素值对应的出现频率的哈希表,在python中有个collections库中的Counter方法可以构建我们需要的哈希表 2、建立堆。在python中可以使用heapq库中的nlargest方法。堆中添加一个元素的复杂度是O(log(K...
600d5a9aa33cb125820305e2fbe12cfa08dca41f
x-jeff/Tensorflow_Code_Demo
/Demo5/5.1.tensorboard_network_structure.py
2,139
3.546875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 #该语句会自动创建名为MNIST_data的文件夹,并下载MNIST数据集 #如果已存在,则直接读取数据集 mnist=input_data.read_data_sets("../Demo3/MNIST_data",one_hot=True) #mini-batch size batch_size=100 #训练集的数目 #print(mnist.train.num_examples)#55000 #一个epoch内包含的mini-batch个数 n...
61b96a38bf1e6a364e026c80a6217d9698e3995e
JahazielGuzman/python_practice
/mergesort.py
791
3.8125
4
def mergesort(a,p,r): if p < r: q = int((p+r)/2) mergesort(a,p,q) mergesort(a,q+1,r) merge(a,p,q,r) def merge(a,p,q,r): n1 = q - p + 1 n2 = r - q L = [] R = [] for i in range(0,n1): L.append(a[p+i]) for j in range(0,n2): R.appen...
d847c93c7487ab48a22fab717d5a670a5b279119
is2soccer/class_projects
/python/1.py
1,414
4.03125
4
# Project: Discussion # Name: Khanh Tran # Date: 02/26/14 # Description: This program will create a graphic window that # draws 5 dice on the screen from graphics import * # define 'dots' function def blackDot(center,win): blackdot=Circle(center,10) blackdot.dra...
24e288d2df8dd236870909c918b00507f7febe9b
CodingInterview2018Gazua/coding_interview
/coding_interview/lansun/chapter3/3.4_hanoi_towers.py
692
3.59375
4
# /usr/bin/python # -*- coding: utf-8 -*- # 3.4 하노이탑 문제에는 3개의 탑과 N개의 원판이 등장하는데 각 원판은 어느 탑으로도 옮길 수 있다 # 하노이 탑 퍼즐은 세 개의 탑 가운데 하나에 이 N개의 원판을 쌓아두고 시작한다 # 이때 원판들은 지름이 작은 원판이 위쪽에 오도록 배열된다. 하노이 탑 퍼즐에는 다음과 같은 제약조건들이 있다 def hanoi(n, start, by, dest): if n == 1: print '{} -> {}'.format(start, dest) else: ...
c7d68dca2b098ef151f272c157db4ae0888ac262
nojhan/atelierscientifique-graph
/graphdisplayer.py
2,481
3.515625
4
import turtle import time # TODO: Optimiser def DrawGraph(G, path=0, scale=100, animationspeed=0, linethickness=5, nodesize=10, bgcolor="black", graphcolor="white", pathcolor="red", startcolor="cyan", finishcolor="lime"): # paramétrage de l'écran wn = turtle.Screen() wn.bgcolor(bgcolor) #...
6e21c1eb0baa2a88e3855c90ca21ef64b9057938
miguelgfierro/pybase
/plot_base/plot_confusion_matrix.py
1,695
3.78125
4
import itertools import numpy as np import matplotlib.pyplot as plt def plot_confusion_matrix( cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues ): """Plots a confusion matrix. Args: cm (np.array): The confusion matrix array. classes (list): List wit the classe...
8053045835240b92902ae0ad6ca65defcadf73a3
NikitaKirin/Linear-equation-solver-calculator
/main.py
1,212
3.78125
4
import core.method_of_Cramer as calc matrix_of_variables = [] matrix_of_free = [] count_line = 0 count_free_line = 0 while True: line = input( 'Вводите коэффициенты при неизвестных построчно через пробел! - для остановки ввода введите Stop' + '\n') if line == "Stop": break else: lin...
7c49e8644fb479e2c017c80673c37c6de9c7ce61
AdamZhouSE/pythonHomework
/Code/CodeRecords/2506/61406/303936.py
281
3.515625
4
source = input().split(',') result = [] for i in range(0,len(source)): source[i] = int(source[i]) result.append(1) for b in range(1,len(source)): for a in range(0,b): if source[b]>source[a]: result[b] = max(result[b],result[a]+1) print(max(result))
bb27ca33aa1acc7c4227ae43246cbae976580f38
shadibdair/MyProjects
/Python Projects/Build Calculator/04_Step.py
860
4.0625
4
# Building a calculator import re print("Our Magical Calculator") print(" S H A D I\n") print("Type 'quit' to exit\n") previous = 0 run = True def performMath(): global run global previous equation = "" if previous == 0: equation = input("Enter equation: ") else: ...
90c56ce5fab92ee8846ed5fdd6a67090e84d9606
ekorkut/python
/data_structures/tree/traversals.py
1,144
3.734375
4
from node import Node from collections import deque one = Node(1, None, None) four = Node(4, None, None) six = Node(6, None, None) five = Node(5, one, four) two = Node(2, six, None) three = Node(3, five, two) def pre_order(n): print n.data if n.left is not None: pre_order(n.left) if n.right is...
3b64094d650c426b7a4c74c0d9d4eaf78b3c2310
indurkhya/Python_PES_Training
/Ques32.py
3,063
4.53125
5
# Write a program to perform following operations on List. Create three lists as List1, List2 and List3 having 5 # city names each list. # a. Find the length city of each list element and print city and length # b. Find the maximum and minimum string length element of each list # c. Compare each list and determine ...
80fcfc3f7b2db04a7712693f74b05cef146524fb
srikanthpragada/PYTHON_03_JULY_2018_DEMO
/sqlite/change_loc.py
439
3.6875
4
import sqlite3 con = sqlite3.connect(r"e:\classroom\python\july3\hr.db") # Connection cur = con.cursor() # Cursor id = input("Enter department id :") loc = input("Enter new location :") cur.execute("update departments set location = ? where deptid = ?", (loc,id)) if cur...
5bce59a4f343f43c3ef9592731e4d2a837231698
lyonva/ScheduleBot
/src/event_type.py
2,609
3.953125
4
class event_type: def __init__(self, event_name, start_time, end_time): """ Function: __init__ Description: Creates a new event_type object instance Input: self - The current type object instance name - String r...
ce233ac0f4383921685b36c753c8c8a08fe15e3e
AnatolyDomrachev/karantin
/is28/beresnev28/beresnev_lr/zadanie_2-9.py
377
3.5625
4
a=[[0],[0],[0],[0]] for w in range(4): for e in range(4): a[w][e]=int(input("Введите элемент массива = ")) print(a[0]) print(a[1]) print(a[2]) print(a[3]) s=a[1][1] for k in range(4): for u in range(4): if a[k][u] >= s: s=a[k][u] str=k sto=u print("наибольшее число = ", s,"строка = ",str+1,"столбец = "...
883625c65b5915ad0eb3a312bea4a46e5d67463f
jeffn12/advent2020
/Day_1/Day_1.py
687
3.609375
4
entries = [] f = open("Day_1/Day_1.txt", "r") for line in f: entries.append(int(line)) f.close() def getProductOfTwo(entrylist): for first in entrylist: for second in entrylist[entrylist.index(first):]: if (second + first == 2020): return first * second return None de...
d8b035a10a86e3f8e963f52db7fb34077e935684
qq854051086/46-Simple-Python-Exercises-Solutions
/problem_27.py
1,141
4.46875
4
''' Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map() 3) using list comprehensions ''' def map_word_with_length_using_for(word_list): map_w...
9c241cca1ac186fe88a648216b67f42c4cd4ec5e
renol767/python_Dasar
/Dicoding/Dasar/Penanganan Kesalahan/test.py
551
3.75
4
d = {'ratarata': '10.0'} try: print('rata-rata: {}'.format(d['rata_rata'])) except KeyError:\ print('kunci tidak ditemukan di dictionary') except ValueError:\ print('nilai tidak sesuai') try: print('rata-rata: {}'.format(d['ratarata'] / 3)) except KeyError: print('kunci tidak ditemukan di dictionar...
e8c881291c4021e2bb4bb6bb9bd556e1f4512cac
dtingg/Fall2018-PY210A
/students/Vincent_Aquila/session03/list_lab.py
5,725
4.375
4
""" Python210A Vincent Aquila Fall2018 using Python 3.7.0 assignment objective: List Lab Note - I am using many/extra print statements in the code for the purpose of testing. Comment and Doc Strings might be explaining the obvious to experienced developers; if they seem redundant, it is for my learning purposes. Th...
5d61213715a8982cf881ad82c7a957182d5dacc0
PJTURP/Python-Practice
/main.py
195
3.84375
4
def function(): count = 1 potato = 1 while potato <= 10: while count <= 10: print(count) count = count + 1 potato = potato + 1 count = 1 function()
cae7c438f8a60585284997848cfff427112223d3
sanjay100192/Autosearch
/main.py
1,006
3.515625
4
import os import re from threading import Thread def run_threads(filename,module_name, c): obj = re.split(r'[\\]', filename)[-1:] with open(filename, "r") as f: for line in f.readlines(): if module_name in line: c += 1 if c == 1: print "Found in {} \n".format(fil...
8f639d3874556d61d9ced7c4d751a3e917e0fce8
cyf1981/algoPrac
/Arrays/decompressRLElist.py
709
3.515625
4
''' https://leetcode.com/problems/decompress-run-length-encoded-list/ Orginally implemented the below solution but then converted it into a list comprehension solution Time complexity O(n*m) where m is the freq of a number n Space complexity O(n*m) ''' class Solution: def decompressRLElist(self, nums: List[in...
f0ca1ee428b27beb25363bcd3118bcb236ff95a4
jaehyunan11/leetcode_Practice
/TOP_QUESTIONS/240.Search_a_2D_Matrix_II.py
1,190
3.8125
4
class Solution: def searchMatrix(self, matrix, target): print(len(matrix)) print(len(matrix[0])) for row in matrix: if target in row: return True return False # Bruce Force # TIME : O(n*m) since n * m search in the matrix # Space : O(1) def searchMatr...
73038e322a51be5411d5badf3fbbf472ad14d4ca
ddenizakpinar/Practices
/Simple Array Sum.py
223
3.6875
4
# https://www.hackerrank.com/challenges/simple-array-sum/problem # 26.07.2020 def simpleArraySum(ar): return sum(ar) ar_count = int(input()) ar = list(map(int, input().rstrip().split())) print(simpleArraySum(ar))
376d7bafa7b7c633757d051604394ae822b0dc50
evanraalte/AdventOfCode2019
/day6.py
1,482
3.59375
4
def findDeps(orbit,relations,lst): for r in relations: if orbit in relations: lst.append((orbit,relations[orbit])) return 1 + findDeps(relations[orbit],relations,lst) return 0 f = open("day6.input","r") orbits = f.readlines() orbit_relations = [ orbit.strip().split(")") for or...
ffdc65e79bf63c670f6f7df3b411198c8e45d9b9
gqjuly/hipython
/helloword/2020_7_days/ten/c2.py
287
3.875
4
import re #判断字符串中是否有Python a = 'C|C++|Java|C#|Python|JavaScript' r = re.findall('Python', a) if len(r) != 0: print('字符串中包含Python') else: print('NO') # print(r) #方法一 var = a.index('Python') > -1 print(var) #方法二 print('Python' in a)
feed37b36f0a67bf60370dfb48226a80d0c082b4
CRomanIA/Python_Undemy
/Seccion_20_Librerias_Panda/Secc20_cap77_Eliminar_Elementos.py
709
3.84375
4
#Eliminar elementos en series y dataframes import pandas as pd import numpy as np np.arange(4) serie = pd.Series(np.arange(4), index=['a','b','c','d']) print(serie) #Si queremos eliminar un elemento (c) print(serie.drop('c')) #reshape = que la lista de valores se divide en 3 filas y 3 columnas print(np.arange(9).resh...
7978c3db80ec89104a3ed545a5f01a51a3fd9a6c
onlykumarabhishek/Algos-P1-Python
/Week2/Assignment2.py
1,976
4
4
tally = 0 def get_list(): """ Create list of integers using QuickSort.txt :return: list of integers """ with open('QuickSort.txt') as f: lon = [] for line in f: lon.append([int(x) for x in line.split()][0]) return lon def quick_sort(unsorted_list, question_num): ...
6fd658b940a1f216053dd972c44c9533a31bae8b
Rebeljah/Alien_Invasion
/bullet.py
1,772
4.03125
4
import pygame as pg from pygame.sprite import Sprite class Bullet(Sprite): """A class that represents a travelling bullet. This class uses code from Python Crash Course""" def __init__(self, game): """Create a bullet object at the ship's current position""" super().__init__() sel...
f1b2aa351cda874b70ef2ee914d6bcd3a56ea1e7
j0nah/rosalind
/dna/count_dna_nucleotides.py
601
3.828125
4
import collections # A string is simply an ordered collection of symbols selected from some alphabet # and formed into a word; the length of a string is the number of symbols that it contains. class CountDnaNucleotides: def __init__ (self, dnaString): self.dnaString = dnaString self.count_a = 0 ...
a04e781282d8bdc3b7d886cd39d98662aa4de488
MinKyeong031/Python_Study
/WS/set_study.py
411
3.640625
4
# 순서 X # 중복으로 저장 X # 합집합, 교집합, 차집합같은 집합 연산 가능 s1 = {1, 2, 3} s2 = {2, 3, 4, 4} # s3 = {} # 타입? => 딕셔너리 s3 = set() # print(s1[0]) print(s1) print(s2) # 중복 저장 불가 s2.add(4) s2.add(5) s2.add(5) s1 = {1, 2, 3} s2 = {2, 3, 4, 4} # 합집합 print(s1.union(s2)) # 교집합 print(s1.intersection(s2)) # 차집합 print(s1.difference(s2))
cd7fd204ec00b6d65ab37f011d1801609a2da0b7
sakakazu2468/AtCoder_py
/abc/026/a.py
79
3.625
4
a = int(input()) if a%2: print((a//2)*(a//2+1)) else: print((a//2)**2)
7cf9eed5656f9375a5876821a443586da6027565
Glightman/BlueEdTech_exercicios
/dict02.py
316
4
4
""" 2. Exercício Treino - Crie um dicionário em que suas chaves correspondem a números inteiros entre [1, 10] e cada valor associado é o número ao quadrado. {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} """ numeros = {} for num in range(0,10): numeros [num] = num**2 print(numeros)
805bf2beea9fe2aa7e7dfc29278e6d877f108a3b
tariqueameer7/course-python
/Labs/Lab01/Lab01-02_sum.py
123
4.03125
4
str_N = input("Please enter a number to find summation of 1..N: ") N = int(str_N) + 1 total = sum(range(1,N)) print(total)
2d766d56f1cd4b95a9800c01efb5dce214d393c9
darcangelomauro/rng_new
/script/commtxt.py
641
3.515625
4
nH = int(input('nH\n')) nL = int(input('nL\n')) print('COMM1') for i in range(nH): for j in range(i+1, nH): for k in range(nH, nH+nL): print('[H' + str(i+1) + ',H' + str(j+1) + ']L' + str(k-nH+1), end=' ') print('') print('COMM2') for i in range(nH, nH+nL): for j in range(i+1, nH+nL): ...
d7e5bdbc9fe6baef34506a72a3115d2cce7bf159
dhlee49/MapReducePr
/tmapper.py
901
3.90625
4
#!/usr/bin/env python3 #sys for output import sys def gen_input(input_file): """ in: input file out: generator object for that input file """ for line in input_file: yield line.split() def trigrammap(lyric): """ in: tuple of all words in lyrics prints all triigrams to sys.stdout...
203083351f1f2a0388e5f6c642dc02c141a6bf20
jonathanssaldanha/CursoPython
/104 Exercicios Python/ex048.py
487
3.796875
4
# FAÇA UM PROGRAMA QUE CALCULE A SOMA ENTRE TODOS OS NUMEROS IMPARES QUE SAO MULTIPLUS DE # TRES E QUE SE ENCONTRAM NO INTERVALO DE 1 ATE 500 soma = 0 cont = 0 for c in range(1, 501, 2): if c% 3 == 0: cont += 1 #cont = cont + 1 soma += c ...
61954413ccb3f6be30e906dfbaa9f5dd2ef12f7c
cholidek/python
/Day4/Homework3.py
294
3.796875
4
# Narysuj piramidę Mario - jako input - wysokość piramidy # np. piramida wysokości 3 ma wyglądać: # # # # ### # ##### wysokosc = input('Podaj wysokość piramidy: ') wysokosc = int(wysokosc) for i in range(wysokosc): print(" " * (wysokosc - 1 * i) + ("#") + ("#" * (1 * i)))
65c69c2f1b04aec517e64db1abe56eef84922458
Harry-2014/pythoncookbook
/chapter1/112.py
1,260
4.15625
4
''' 1.12 序列中出现次数最多的元素 问题 怎样找出一个序列中出现次数最多的元素呢? 解决方案 collections.Counter 类就是专门为这类问题而设计的,它甚至有一个有用的 most_common() 方法直接给了你答案。 ''' words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look'...