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
4fbb7f1164e0e80689ac64a1f3a34d7e5c6f2f5b
tcaserza/coding-practice
/daily_coding_problem_18.py
702
4.1875
4
# Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of # each subarray of length k. # # For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since: # # 10 = max(10, 5, 2) # 7 = max(5, 2, 7) # 8 = max(2, 7, 8) # 8 = max(7, 8, 7) ...
fef08201e0ceb39260d186701160ad3af227128d
tcaserza/coding-practice
/question1.py
965
3.78125
4
# # PROBLEM: You plan to listen to music on a bus ride. You are given an array of song durations, and a bus ride # duration, find a pair of songs that will end 30 seconds before you arrive. # def IDsOfSongs(rideDuration, songDurations): song_1_id = None song_2_id = None longest_song = 0 for ...
2c02137ddd6eff3167235d6f19df9b69577e8949
aslanzyx/ml-from-scratch
/src-py/a3/tmp.py
162
3.53125
4
import numpy as np X = np.array([1, 2, 3, 4]).reshape([2, 2]) print(X) print(sum(X)) # X = np.append(X, X**2, axis=1) X = X != 1 print(X) print(len(X))
ab4648f665f41e497ba78a2de1b268a21e0b53a8
DanhelMerVe/Mision_06
/misionimposible.py
1,538
3.578125
4
#Danhel Alejandro Mercado Velasco import pygame from math import * VERDE_BANDERA = (27, 94, 32) NARANJA = (239,169,119) NEGRO = (0,0,0) BLANCO = (255,255,255) ANCHO = 800 ALTO = 800 def dibujar(R,r,l,cafe): # Inicializa el motor de pygame pygame.init() # Crea una ventana de ANCHO x ALTO ...
ca3a6a5b78d907f7dfd5d4a5c7121fece736c9b9
billywood8/Python
/Activity135/billywood135.py
318
3.5625
4
def how_eligible(essay): punctuation= 0 if '?' in str(essay): punctuation= punctuation+ 1 if '"' in str(essay): punctuation= punctuation + 1 if ',' in str(essay): punctuation= punctuation + 1 if '!' in str(essay): punctuation= punctuation+ 1 print (punctuation)
b382dcb77d04d582e55496adf33f22fc19f29259
hendrykosasih/HendryA1
/hendryA1.py
8,243
4.5
4
""" This program is to load all of the items for the csv file and will show to the user how many items are loaded. Next, user can choose either to list all of the items, hire an item, return an item, or add new item to stock. All of the user's input are error-checked and error messages are shown if user enters the wron...
1f76f9b05ec4a73c36583154bc431bd3746f659e
cseharshit/Registration_Form_Tkinter
/registration_form.py
2,786
4.28125
4
''' This program demonstrates the use of Tkinter library. This is a simple registration form that stores the entries in an sqlite3 database Author: Harshit Jain ''' from tkinter import * import sqlite3 #root is the root of the Tkinter widget root = Tk() #geometry is used to set the dimensions of the window root.geom...
a8c63a9326c0552944754b1c77e08b5197565670
xivitazo/prueba-nivel
/Harvester/Level3.py
3,790
3.765625
4
def getPos (n_rows, n_cols, row, col) : return n_cols*(row-1)+col def getTrajectory (n_rows, n_cols, row, col, i_dir) : act_col=col act_row=row output='' if i_col==1 : col_avance=1 else : col_avance = -1 if i_row==1 : row_avance=1 else : row_avance=-1 ...
37ac391ad1a3d849813a5d1768915c79a3b2fe96
CiraciNicolo/AdvancedPython
/magic/main.py
1,309
3.5625
4
from magic import * @magic(Empty) class Person: def __init__(self, name, gross, netp): self.gross_salary = gross self.netpercentage = netp self.name = name def who(self): return self.name def salary(self): return self.gross_salary*self.netpercentage/12 @magic(Empty) class Exam: def __init__(self, title, n, ...
ef792b4e7200039c96d42d11bd6d71543ca206b1
Nirland/HHAPI
/singleton.py
282
3.671875
4
""" Decorator singleton implementation """ def singleton(klass): instances = {} def get_instance(*arg, **kwarg): if (instances.get(klass, None) is None): instances[klass] = klass(*arg, **kwarg) return instances[klass] return get_instance
12d9ce39cf287b4b22a6686e2ea77d41e8fde907
gmatuska/hackerrank
/python/stacks-balanced-brackets/test_main.py
728
3.90625
4
from unittest import TestCase class TestMain(TestCase): def test_main(self): i = '{{{}}}' """self.assertEqual(['{', '{', '{', '}', '}', '}'], list(i))""" """reversedStack = sorted(stack, reverse=True)""" self.assertTrue(self.is_balanced(i)) def is_balanced(self,brackets): ...
60c7ccbde245d18a304bf5ca78dc0689ac5517ab
gmatuska/hackerrank
/python/find_a_sub_word/test_find_sub_word.py
336
3.65625
4
from unittest import TestCase from find_a_sub_word import SubWordFinder class TestFind_Sub_Word(TestCase): def test_find_sub_word(self): sentence = 'existing pessimist optimist this is' wordFinder = SubWordFinder() subword = 'is' self.assertEqual(wordFinder.get_match_count(sentenc...
a4473220576897ec83ea68fd2e262956f2afac8a
nnminh199914/python-3
/4.py
685
3.953125
4
listt = ['ember', 'qop','storm'] print("welcome to our shop: ") print (listt) while True: a= input("here are the command list: crud: ") if a == "c": c=input("what do you want to create:") listt.append(c) print(listt) elif a=="r": print("this is the list in better vi...
15c115cc857f0ee9a627f88450fcb733b5b7e8ed
patrycjapraczyk/mcu-test-app
/model/StaticClasses/DataStructFunctions.py
451
3.546875
4
class DataStructFunctions: @staticmethod def chunk(lst: list, n: int): """ chunks a list into slices of length n, returns a list of chunks """ for i in range(0, len(lst), n): yield lst[i:i + n] @staticmethod def get_key(my_dict: dict, value): ...
ff00cd98a60cb8a44ac18d6410c076b6d13146d1
timmygee/podcastify
/soupify.py
3,230
3.5625
4
# Tools to turn internet resources into BeautifulSoup soup objects import urllib2 try: from bs4 import BeautifulSoup except ImportError: from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup class Soupify: """ Class to define soupify common functionality """ soup = None data = None ...
c3012e45d00a12646232fa63c7eaa43cae9c565f
alex-gehrig/geoextractor
/geoextractor.py
1,803
3.515625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import glob import csv """Grab the country-codes out of already existing txt-files which contain the results of 'whois' and write them in a csv-file ordered descending by occurance""" # define an empty list to store the temporary results country_list = [] # assuming that ev...
d55ccfcc528e3a67b9d180b1d739df8b431807f7
Windman/AlgorithminThinking
/GraphTheory/GraphTheory.py
1,912
3.625
4
"""Graph theory p1 m1""" EX_GRAPH0 = {0: set([1,2]), 1: set([]), 2: set([])}; EX_GRAPH1 = {0: set([1,4,5]), 1: set([2,6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}; EX_GRAPH2 = {0: set([1,4,5]), 1: set([2,6]), 2: set([3,7]), 3: set([7]), 4: set([1]), 5: set([2]), 6: set([]), 7: set([3]), 8: set(...
3745716c4acaf91b74960d7079e93f0359e71364
ribbitfix/go-fish-CLI
/mastergame.py
1,520
3.65625
4
import random import player class MasterGame: def __init__(self, number_of_players=2, cards_per_hand=7): self.number_of_players = number_of_players self.cards_per_hand = cards_per_hand self.deck = [] self.discard_pile = [] self.players = [] self.player_names = {} ...
feb6766a6b33bbd6b56ccc477de059ceaffda85e
step305/Xavier_FaceDetector
/Bbox.py
2,425
3.53125
4
import collections Object = collections.namedtuple('Object', ['id', 'score', 'bbox']) class BBox(collections.namedtuple('BBox', ['xmin', 'ymin', 'xmax', 'ymax'])): """Bounding box. Represents a rectangle which sides are either vertical or horizontal, parallel to the x or y axis. """ __slots__ = (...
6321f7bef43c5a401601b9aba47e8a943ed7fd24
qcldn/coin-changer-kata-python
/cc.py
226
3.859375
4
denominations = [200, 100, 50, 20, 10, 5, 2, 1] def change(amount): coins = [] for coin in denominations: while amount >= coin: coins.append(coin) amount -= coin return coins[::-1]
8151ea5b77ccf9a8ad173f22ca601623eb8d2f6d
munyeenC/munyeen-kl-oct18
/oops1.py
1,188
3.828125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 8 10:29:03 2018 @author: munyeen.chong """ class Puppy: name = "" color = "" def __init__(self, name, color): self.name = name self.color = color def bark(self): print("I am", self.color, self.name) def __st...
c0a22ef79888ffc82d1b564a435c64fbd96ea7d7
munyeenC/munyeen-kl-oct18
/moduleadder.py
412
3.734375
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 14 10:36:34 2018 @author: munyeen.chong """ #def add_item(item, item_list = []): # item_list.append(item) # print(item_list) def add_item(item, item_list = None): if item_list == None: item_list = [] item_list.append(item) print(item_list) def...
55ec32ee50f359c1d2981e73c327fb440b1332da
noozip2241993/basic-python
/task34.py
128
3.8125
4
def sum_two_integers(n1,n2): if 15<n1+n2 <20: return 20 else: return n1+n2 print(sum_two_integers(7,20))
64932ef6aa772e1fb74bc1976f4424fdae7bbe78
noozip2241993/basic-python
/task25.py
161
3.90625
4
numbers = [1,5,8,3] def check_specific_value(n1,n2): if n2 in n1: return True else: return False print(check_specific_value(numbers,3))
41a8373f95b5b61905102bbd87f7d793f42bfca3
noozip2241993/basic-python
/task31.py
299
3.75
4
def gcd(x,y): """Write a Python program to compute the greatest common divisor (GCD) of two positive integers""" gcd = 1 if x%y ==0: return y for k in range(int(y/2),0,-1): if x%k == 0 and y%k ==0: gcd = k break return gcd print(gcd(336,360))
f26a133ab74806fa888ff5e287229ad368de5918
Boyzmsc/numerical-analysis
/momentum_project/testTM_#2.py
1,650
3.5
4
from tensorflow_momentum import TensorflowMomentum import numpy as np import matplotlib.pyplot as plt import tensorflow.compat.v1 as tf tf.disable_v2_behavior() # tensorflow로 구현한 momentum이 잘 동작되는지 테스트 t_m = TensorflowMomentum(0.001,0.7) num_points = 50 vectors_set = [] for i in np.arange(num_points): x = np.rand...
0a121ab2cf53f4696a7ec57311ff0017549023ea
khushboo2243/Object-Oriented-Python
/Python_OOP_1.py
1,850
4.46875
4
#classes aallows logially grouping of data and functions in a way that's easy to resue #and also to build upon if need be. #data and functions asscoaited with a specific class are called attributes and methods #mathods-> a function associated with class class Employee: #each employee will have specific attributes...
1a20d8333e3ff1853e0a375265dea8e47aefb9c6
mjt-21/Tkinter-Calculator
/main.py
3,913
4.0625
4
import tkinter as tk root = tk.Tk() root.geometry("510x700") root.resizable(0, 0) # Top Input Label InputLabel = tk.Label(root, text="", font=("Courier", 15), width=42, height=5, borderwidth=2, relief="solid") equation = "" operatorOnly = False numOnly = False answer = False # inputLogic function evaluates problems...
2a9d55eeb720f8d99012e408a5a625de024bdd3b
usrnm242/algorithms
/brackets.py
1,795
3.90625
4
def brackets_generator(left, right, string): lst = [] if left == right == 0: lst.append(string) if left != 0: L = brackets_generator(left - 1, right, string + '(') lst.extend(L) if left < right: R = brackets_generator(left, right - 1, string + ')') lst.extend(R...
57d41b2f43fe3576fb41355fa9c3e90db14e5c00
usrnm242/algorithms
/graph/bfs.py
505
4.09375
4
#!/usr/bin/env python3 def bfs(graph, start): visited = [start] queue = [start] while queue: v = queue.pop(0) for w in graph[v]: if w not in visited: visited.append(w) queue.append(w) return visited if __name__ == "__main__": graph = {...
e42d4f49f2f0cc19432a798ebacfd1c1a4ca76b0
aronminn/max-int
/max_int.py
463
4.15625
4
num_int = int(input("Input a number: ")) # Do not change this line # Fill in the missing code # Ef num int er stærri heldur en seinasta tala þá geymum við hana. # Þegar num int er ekki negative þá hættum við að spurja um input og prentum stærstu töluna. max_int = 0 while num_int > 0: if num_int > max_int: ...
77c75d6f4194652bbf948ed3df59a2f7e83299ac
BboyZander/CodeWars
/[6kyu]/[6kyu] Kebabize.py
445
3.734375
4
def kebabize(string): res = '' for i in string: if i.isdigit(): continue elif i == i.upper(): res += '-' + i.lower() else: res += i #your code here return res.lstrip('-') def kebabize2(s): return ''.join(c if c.islower() else '-' + c.low...
cad9e9a822a1eb1fdcd9bf4ad03f16715e1a68e6
BboyZander/CodeWars
/[6kyu]/[6kyu] divisors.py
281
3.90625
4
def IsPrime(n): d = 2 while n % d != 0: d += 1 return d == n def divisors(integer): if IsPrime(integer): return '{} is prime'.format(integer) else: return [i for i in range(1, int(integer/2)+1) if integer%i == 0][1:] print(divisors(122))
69cd085aa1ce4b1a3ec817fb1dae8ab3127a5195
BboyZander/CodeWars
/[6kyu]/[6kyu] find_missing_letter.py
542
3.921875
4
import string import numpy as np def find_missing_letter(chars): chars_ = [x.lower() for x in chars] if chars == chars_: d = {ch: n + 1 for n, ch in enumerate(string.ascii_lowercase)} else: d = {ch: n + 1 for n, ch in enumerate(string.ascii_uppercase)} inv_d = {v: k for k, v in d.items...
844eab75dccc2127bc032a356dec6e4acc6a295f
razak17/ds-algos
/positionalList.py
4,195
3.96875
4
from linkedLists import _DoublyLinkedBase """ The Positional List ADT Used to access nodes by their positon """ # Positional Class List based on a doubly linked list class PositionalList(_DoublyLinkedBase): class Position: # An abstraction representing the location of a single ele def _...
bab46a02c837f0dbc10273beeccb7a12a4be55a6
razak17/ds-algos
/sortedMap.py
13,746
3.609375
4
from trees import LinkedBinaryTree from maps import MapBase class TreeMap(LinkedBinaryTree, MapBase): # sorted map imple using a binary search tree #------------------------------ override Position class ------------------------------- class Position(LinkedBinaryTree.Position): def key(self): ...
bba69b0ee5109c3789eb94c4c13b6199daacbf77
DuaneNielsen/CartPoleQ
/scratches/dicts.py
161
3.859375
4
dict = {} def increment(): if 'key' not in dict: dict['key'] = 1 else: dict['key'] += 1 print(dict['key']) increment() increment()
f033d269d6afe51ae3b6119bc140b670ecc71f0d
Bosco971020/lesson4
/有厚度的星星塔.py
141
3.890625
4
x=int(input('請問你要多厚的星星塔?')) for i in range(x+1): print('*'*i) for i in range(x): print('*'*((x-1)-i))
fa63806d8dc5673037c2c7ac03a32ddddab93cb4
potirar/CodigoPythonDSI
/Atividades_Python/atividades_repetição/atividade3.py
477
3.671875
4
import time import os pessoas = int(input('Quantas pessoas querem se hospedar: ')) h = 0 m = 0 for i in range(0, pessoas): nome = input('Qual seu nome?') sexo = input('Qual o seu sexo? m/f:') if sexo == 'm': print(f'Bem vindo Sr. {nome}') h += 1 else: print(f'Bem vindo Sra. {n...
4b09758ee7ff84a0254256f17a5820a0d437fccc
potirar/CodigoPythonDSI
/Atividades_Python/função/texto.py
256
3.84375
4
def verifica(texto, letra): return texto.count(letra) texto = str(input("Informe um texto qualquer: ")).lower() letra = str(input("Informe um letra qualquer: ")).lower() print(f"A letra {letra} aparece {verifica(texto,letra)} vezes no texto \n\n")
6a01e8888f6969c6549a1a81d79aec26261fefb6
potirar/CodigoPythonDSI
/Programação Orientação Objeto - POO/aula1/pessoa.py
475
3.78125
4
from datetime import date class Pessoa: # Atributos nome = "José" idade = 45 altura = 1.78 # Métodos def falar(self, texto): #self: diz a respeito a classe a qual está inserido. print("Hello World!") #primeiro parâmetro com self print(texto) def ouvir(self, som): ...
5dd9cc2c0b01728fe82a65c79263a78125412240
potirar/CodigoPythonDSI
/Atividades_Python/função/sorteio.py
525
4.0625
4
from random import randint def loteria(valor): aleatorio = randint(1,100) palpite = 1 #contador while valor != aleatorio: if valor > aleatorio: print("Informe um valor menor") elif valor < aleatorio: print("Informe um valor maior") palpite += 1 ...
27eb445ad4194079a4f09c3684583b33e11ea3f2
potirar/CodigoPythonDSI
/Comandos/exemplo6(repetição while).py
601
3.90625
4
'''from os import system system('cls') print('*'*10,'EXEMPLO 1','*'*10) valor = 1 while valor <= 10: print(valor) valor += 1 print('\n\n') print('*'*10,'EXEMPLO 2','*'*10) while True: num = int(input('Informe um valor qualquer:')) if num == 0: break #termina o programa''' pessoas = [] fo...
7852688d5d4902cf11695c72bcfb527088ee0811
ematheson/Projects
/Markov Chains/Markov_Chains.py
6,042
3.6875
4
# markov_chains.py import numpy as np import scipy as sp from scipy import linalg as la from numpy import linalg as nla def random_markov(n): """Create and return a transition matrix for a random Markov chain with 'n' states, stored as an nxn NumPy array. """ A = np.random.random((n,n)) #normali...
cc8677cc19b6a77bebc3095cc4cc8499ba9042f6
thomasstryb/Recursive-text
/recursivetext.py
504
3.859375
4
def find_text (string, substring): #no_text = 0 #error= "mistake in string" while len(string)> 0: x= string.find(substring, no_text) if len(string) == -1: print("mistake in the string") #return error print("found text in:", x) #def find_text (string, substring): #string_index = 0 #while str...
bdabcfa9637cae527536ec5494d73f5191afe09c
itsvinayak/labs
/python_algo_lab/insertion_sort.py
347
4.25
4
def insertion_sort(array): for i in range(len(array)): cursor = array[i] pos = i while pos > 0 and array[pos - 1] > cursor: array[pos] = array[pos - 1] pos = pos - 1 array[pos] = cursor return array if __name__ == "__main__": print(insertion_sort(...
7bf50338be49755f9babae0c82b4d2427596e68c
Kcheung42/GeeksforGeeks
/Dynamic_Programming/04.Longest_Common_Subsequence.py
2,099
3.59375
4
# **************************************************************************** # # # # ::: :::::::: # # 04.Longest_Common_Subsequence.py :+: :+: :+: ...
bb6733f247b547030ca9b875f6bac85d118fa7a8
n6g7/euler
/solutions/level1/problem14.py
315
3.59375
4
from tools.collatz import collatz_length def longest_collatz_sequence(n): max = 1 result = 1 for i in range(1, n+1): length = collatz_length(i) if length > max: max = length result = i return result def run(): return longest_collatz_sequence(1000000)
7146df00fce0c63ebc13939d76ef05f4ccb36a64
n6g7/euler
/tools/primes.py
953
4.03125
4
import math def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False root = math.floor(math.sqrt(n)) for x in range(3, root + 1, 2): if n % x == 0: return False return True def prime_factors(n, reverse=False): ...
3b878a6cf4d699672b11d8460ef9e75ccfecdb33
n6g7/euler
/tools/collatz.py
285
3.765625
4
def collatz_next(n): if n % 2 == 0: return int(n/2) else: return 3 * n + 1 collatz_lengths = { 1: 1 } def collatz_length(n): if n not in collatz_lengths: collatz_lengths[n] = 1 + collatz_length(collatz_next(n)) return collatz_lengths[n]
e60afa4bf335f74944ccd3cb17abc6f9209a1094
om-sonawane/The-Perfect-Guess
/The Perfect Guess.py
500
3.984375
4
import random randNumber = random.randint(1, 100) userGuess = None guesses = 0 while (userGuess != randNumber): userGuess = int(input("enter your guess: ")) guesses += 1 if (userGuess == randNumber): print("you guessed it right!") else: if (userGuess > randNumber): print("yo...
908fa7f60cf6e4a895072229ab65c39051d06b76
aintit/hours-tracker
/hours.py
669
3.5625
4
from datetime import date import os if not os.path.exists("hours.txt"): open("hours.txt", "w").close() hoursfile = open("hours.txt") hourstext = hoursfile.read() hoursfile.close() hoursnow = raw_input("How many hours did you work today? ") hoursarray = hourstext.splitlines() today = date.today() todaystr = today...
727052e6d002ed1b2563df6293be70263668d779
GrayKS3248/DQN_Airfoil_Design
/NN.py
2,804
3.5625
4
""" Created on Tue Sep 22 14:34:46 CST 2020 @author: GKSch """ import torch import torch.nn as nn # Dynamically coded class definition for Q learning neural network # It was dynamically coded to allow user to select number of neurons and layers class Neural_Network(nn.Module): # Initialization function ...
284afdb36cd993d6b7b3dbfd7090d9506a94a3a2
luizmariz/cripto
/AL08.3/AL8.3.py
1,141
3.578125
4
#atividade de lab 8.3 n = input() for x in range(n): def impar(x): #funcao que ve se E e impar if (x%2 != 0): return True else: return False numero,base = input() k = 0 q = numero -1 while impar(q) is False:#acha a forma num = 2 elevado a k vezes...
be7b2b43ccde2b715a0bfd04cf4f28097030a3e7
luizmariz/cripto
/AL06.1/AL6.1.py
346
3.796875
4
#atividade de lab 6.1 n = input() for x in range(n): a,b,c = input() #onde c e o modulo forma_reduzida_a = a%c forma_reduzida_b = b%c soma_modulo = (a+b)%c diferenca_modulo = (a-b)%c multiplicacao_modulo = (a*b)%c print forma_reduzida_a,forma_reduzida_b,soma_modulo,diferenca_modulo,mu...
03a57548dbf64f24b0cab910b5d18f2c038f2b89
luizmariz/cripto
/AL02.2/AL2.2.py
224
3.8125
4
#atividade de lab 2.2 n = input() for x in range(n): a,b = input() print a print b r=1 while(r>0): r = a%b print r a = b b = r print "---"
f005aacb268a9f5c56e4dd567c5c39d4173a7552
jpbburns/git-practice
/atomtest.py
274
3.96875
4
# Iteration # Enumerate function string = "Abracadabra" for index, element in enumerate(string): print(index, element) # Dummy variable for __ in string: print(__) # For-else for i in range(50): print(i) if i == 51: break else: print("Done.")
cb5a4206cb906a8ba94f1b1527962cc629dffdaa
MurphysL/Introduction-to-Algorithms
/src/C02/code/s2.1-2.py
322
3.828125
4
import numpy as np def des_insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while arr[j] < key and j >= 0: arr[j+1] = arr[j] j -= 1 arr[j + 1] = key array = np.random.randint(1, 100, 10).tolist() des_insertion_sort(array) print(arra...
ac7eddaf3c873af9808f929576bf39b2db97642c
hoyeongkwak/workspace
/python/pythonProject/day2_2/pythonPart/pEx2.py
142
3.765625
4
data = [1,2,3] data.append(4) print(data) data2 = [1,2,3] data2.extend([4,5]) print(data2) data3 = [1,2,3] data3.append([4,5]) print(data3)
a9d2a9c380f41a4b5c2317c4eb6e9b504308d7e7
hoyeongkwak/workspace
/python/pythonProject/day2_2/pythonPart/pEx7.py
515
3.640625
4
def print_info(name, address='seoul', age=20): print('name:{} addres:{} age:{}'.format(name, address, age)) print_info('kim', 'suwon', 30) print_info('lee','daegu') print_info(address='busan', name='choi') print() def add(*data): result = 0 for d in data: result += d return result print(add(...
eac8dadba99e51df25d45a2a66659bdeb62ec473
whung1/PythonExercises
/fibonacci.py
1,570
4.1875
4
# Need to increase recursion limit even when memoization is used if n is too large # e.g. sys.setrecursionlimit(100000) def fibonacci_recursive_memo(n, fib_cache={0: 0, 1: 1}): """Top-down implementation (recursive) with memoization, O(n^2)""" if n < 0: return -1 if n not in fib_cache: f...
5626b235635adacaff4585835ffca30d62ed315b
whung1/PythonExercises
/BlackjackExample/deck.py
991
3.578125
4
import random class Deck: def __init__(self): self.cards = list() for card_face in range(1, len(Card.card_faces)): for suites in range(0, 4): curr_card = Card(Card.card_faces[card_face], Card.card_values[card_face]) self.cards.append(curr_card) def ...
dadcf696cbda82f519eb6e66a5037bb08712c534
whung1/PythonExercises
/Leetcode/Algorithms/383_ransom_note.py
924
3.828125
4
""" https://leetcode.com/problems/ransom-note Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can on...
a65d712e18531b2789d1b6c210dca5f6db8b8435
whung1/PythonExercises
/Leetcode/Algorithms/561_array_partition_i.py
868
4.0625
4
""" Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in ...
2d3218ee532ce3da0f0382f082bcf0b9d6b529fa
whung1/PythonExercises
/str_compression.py
749
3.921875
4
""" Given a string, compress it based on how many instances of it reoccurs """ def str_compress(cur_str): if not cur_str: return "" current_char = "" current_count = 0 compressed_str = "" for i in range(len(cur_str)): if current_char != cur_str[i]: compressed_str += curr...
93ef926c3ebafaf36e991d7d381f9b189e70bfea
whung1/PythonExercises
/Leetcode/Algorithms/453_minimum_moves_to_equal_array_elements.py
1,424
4.15625
4
""" https://leetcode.com/problems/minimum-moves-to-equal-array-elements Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Input: [1,2,3] Output: 3 Explanation:...
6bfe23e3a7fcf274a55908f72a2b4ac91d504326
kiyomizuhi/tiny_games
/Checker.py
14,749
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 23 16:06:59 2017 @author: hiroyukiinoue """ class Player: """ Handles the state of the player. Attributes: idx (int) : player ID. either 1 or 2. num_soldiers (int) : number of remaining soldiers. coordi...
aaa967a891cb9efdc2e5c80ad6a16c5f4790e7aa
lyongsoon/python_dev
/week-01-python/1_7_function.py
387
3.5
4
# 합수 function # 입력값 parameters, 변환갑 return def hello_friends(name): print("hi, {}".format(name)) name1 = "lyongsoon" name2 = "IU" name3 = "John" name4 = "Kim" print('hi, {}'.format(name1)) print('hi, {}'.format(name2)) print('hi, {}'.format(name3)) print('hi, {}'.format(name4)) hello_friends(name1) hello_friend...
d0412477c8437ff36f940d8656eb967f08554ca4
cvgoncalves/100Daysofcode
/003/compact2.py
468
3.75
4
class Compact: """"Gets an input and compacts the input in an iterator""" def __init__(self, number_list): self.res = set(number_list) self.r = [] for i in self.res: self.r.append(i) def __iter__(self): yield self.r x = [1, 1, 2, 2, 3, 3] y = [1, 2, 2, 3,...
0fe354cb21928d0aebc186e074b6483b8aa2d00b
trinadasgupta/BASIC-PROGRAMS-OF-PYTHON
/diamond using numbers.py
841
4.3125
4
# Python3 program to print diamond pattern def display(n): # sp stands for space # st stands for number sp = n // 2 st = 1 # Outer for loop for number of lines for i in range(1, n + 1): # Inner for loop for printing space for j in range(1, sp + 1): print (" ", end = ' ') #...
151d55f32a2c27f9262217269624275322ed08c3
rohan-singhvi/digit-recognizer-ML
/train_data.py
3,267
3.6875
4
import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.utils import np_utils import matplotlib.pyplot as plt # loa...
3dd367f7786180d92576fc328d58e8b40d4a6f08
toanh/JMSSGraphics
/Demos/Galaxies/JMSS.py
19,705
4.40625
4
import pygame import math """ A simple turtle class that uses PyGame. Implements instantaneous rendering, ie. no animated drawing or turning """ class Turtle: """ DO NOT instantiate directly. Always use the createTurtle() function in the Graphics class """ def __init__(self, graphics): self...
3adf1cb7b1fbd64f863b85f7bd5b9944b18b94ca
Lycurgus1/File_handling
/main.py
1,213
4.0625
4
from text_file import Text_file_handling # Reading from and writing to files # Exception handling # CSV # Assignments # Stating methods to get class object and file path sorted file_path = "order.txt" text_file_object = Text_file_handling(file_path) # Calling/testing read text function print(text_file_object.read_te...
bcbbd61cf79d120f7751722c23dcd5dd94d98a0a
raylanDev/Proyectos_Python
/xd.py
268
3.890625
4
def insertar(lista,elemento): for i in range(len(lista)): if elemento < len(lista): lista.insert(i-1,elemento) if elemento > len(lista): lista.insert(i-1,elemento) print lista listax=[2,3,4,5,7,8,9] insertar(listax,50)
0f56c9fc6529ca45d2ca139f56cbc2cf1fc63a03
dongkunchen/python
/TextTest.py
1,084
3.59375
4
import tkinter win = tkinter.Tk() win.title("dongkun") win.geometry("400x400+200+20") ''' 文本控件,用於顯示多行文本 ''' #創建滾動條 scroll = tkinter.Scrollbar() #創建文本框 text = tkinter.Text(win, width=30, height=4) #side滾動條放那一側 fill填充 scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y) text.pack(side=tkinter.LEFT, fill=t...
784f4d396cb0191404cadac8b1f5ddf5a7d161f7
dongkunchen/python
/RadiobuttonTest.py
572
3.625
4
import tkinter win = tkinter.Tk() win.title("dongkun") win.geometry("400x400+200+20") def update(): print(r.get()) #一組單選框綁定同一變量才能有單選效果 #r = tkinter.StringVar() 看value類型選擇 r = tkinter.IntVar() radio1 = tkinter.Radiobutton(win, text="one", value=1, variable=r, command=update) radio1.pack() radio2 = t...
2b17946b2953c47783a18a136c3a5d8fde9b8b9b
dongkunchen/python
/map&reduce.py
1,549
3.859375
4
from functools import reduce #python內置了map()和reduce函數() #map() #原型 map(fn, lsd) #參數1是函數 #參數2是序列 #功能:將傳入的函數一次作用在序列中的每一個元素,並把結果做為新的Iterator返回 #將單各字符轉成對應的字面量整數 def char2int(chr): return {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}[chr] list1 = ["2","1","6","5"] res = map(char2int, l...
527a8c09776bfdfec251d712a09005eb1cf55516
dongkunchen/python
/CheckbuttonTest.py
905
3.515625
4
import tkinter win = tkinter.Tk() win.title("dongkun") win.geometry("400x400+200+20") ''' 多選框 ''' def update(): message = "" if hobby1.get() == True: message += "money\n" if hobby2.get() == True: message += "power\n" if hobby3.get() == True: message += "people...
2b0519aca47435d071e568c17f4138fd7e941ee2
dongkunchen/python
/responseSpecialClick.py
453
3.53125
4
import tkinter win = tkinter.Tk() win.title("dongkun") win.geometry("400x400+200+20") label = tkinter.Label(win, text="dongkun is a handsome man", bg="red") #設置焦點 label.focus_set() label.pack() #<Shift_L> 左shift #<Shift_R> 右shift #<F5> #<Return> 回車 #<BackSpace> 退格 def func(event): print("event.c...
be4656e837e37f53b06ba2ab89701926afcaa8e1
dejikadri/comprehensions
/dict_comp.py
410
4.25
4
""" This program uses a dictionary comprehension to turn 2 lists of countries and captials into a dictionary with countries as keys and the capitals as values """ list_country = ['Nigeria', 'Ghana', 'Cameroun', 'Togo', 'Egypt', 'Kenya'] list_capital = ['Abuja', 'Akra','Yaunde', 'Lome', 'Cairo', 'Nairobi'] def countr...
a0227d95579b7d30da23b0ef1af276ae9a24de17
kamabulletone/python-practice
/BonusTasks/pract1/naive_mul/task21.py
344
4
4
# Ошибки, которые были: # Проверка на оба нуля. r=1 -> r=x , иначе бы к числу просто прибавлялось по единице def naive_mul(x, y): if x == 0 or y == 0: return 0 r = x for i in range(0, y - 1): x = x + r return x print(naive_mul(10, 15))
59a2c8d4cd1e6c619d8906546af9bc25bb6e6141
fominykhgreg/Python-DZ4
/dz4.6.py
1,476
4.21875
4
""" Реализовать два небольших скрипта: а) итератор, генерирующий целые числа, начиная с указанного, б) итератор, повторяющий элементы некоторого списка, определенного заранее. Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл не должен быть бесконечным. Не...
f8e752d413c350eb5bd2634b7ad4a03bd5c35d1e
StefanSpieker/52Stunden
/algorithmik/Schaltjahr/schaltjahr_schleife.py
1,051
3.671875
4
def jahreszahl_einlesen(): eingabe = input() jahr = int(eingabe) # Berechnung mit dem Wert jahr if jahr < 0: print("Es sind Nur positive Jahreszahlen erlaubt") exit(1) return jahr def ist_schaltjahr(jahreszahl): schaltjahr = False if jahreszahl % 4 == 0: if jahresza...
7451ed0530e31e5ddac543a85a47ab998b6ebbcb
IsamuYun/sim_plan
/test.py
346
3.71875
4
def change_list(list_1, list_2): list_1.append("four") #list_2 = ["and", "we", "do", "not", "lie"] list_3 = ["and", "we", "do", "not", "fail"] list_2 = list_2 + list_3 out_list_1 = ["one", "two", "three"] out_list_2 = ["we", "like", "porper", "English"] change_list(out_list_1, out_list_2) print(out_l...
a74e1b0117319af55c10e7c7952a07228664481b
S-EmreCat/GlobalAIHubPythonHomework
/HomeWork2.py
500
4.125
4
# -*- coding: utf-8 -*- first_name=input("Please enter your FirstName: ") last_name=input("Please enter your last name: ") age=int(input("Please enter your age: ")) date_of_birth=int(input("Please enter date of birth year: ")) User_Info=[first_name,last_name,age,date_of_birth] if User_Info[2]<18: print("You cant ...
55af193549efa1c3d372db5ed5ef271127909704
kingofyeti/leetcode-py
/list_templete.py
922
3.890625
4
class ListNode: def __init__(self,x): self.val = x self.next = None class LinkedList: def __init__(self): self.head = None def __init__(self,node): self.head = node def add_node(self,data): node = ListNode(data) node.next = self.head self.head = node def print_list(self): i...
583bf9a9ad35395db102e774a241d6f2d32f942f
kingofyeti/leetcode-py
/319_bulb_switcher.py
231
3.53125
4
class Solution(object): def bulbSwitch(self,n): # sqrt(n) if n == 0: return 0; res,i = 0,1 while(i * i <= n): res += 1; i += 1 return res n = 16 solution = Solution() print solution.bulbSwitch(n)
fb3a4dc897938946aa5387a27c0d568248ca2d67
kingofyeti/leetcode-py
/357_count_num_with_unique_digits.py
447
3.578125
4
import sys class Solution(object): def countNumbersWithUniqueDigits(self,n): if n == 0: return 1 if n == 1: return 10 if n > 10: return self.countNumbersWithUniqueDigits(10) i = n res = 9 # res(n) = res(n-1) + 9 * 9 * 8 ...(11-n) while i > 1: res *= 11 - i i -= 1 r...
243a2eca71c3306e5078bdc151c501729e1fe885
kingofyeti/leetcode-py
/268_missing_number.py
223
3.5
4
import sys class Solution(object): def missingNumber(self,nums): return ((len(nums) * (len(nums) + 1)) >> 1) - sum(nums) nums = map(int,raw_input().split()) solution = Solution() print solution.missingNumber(nums)
629a0137bd924fb4e96d21db8e50b69e031e3cfe
kingofyeti/leetcode-py
/324_wiggle_sort.py
343
3.65625
4
class Solution(object): def wiggleSort(self,nums): nu = sorted(nums) half = len(nums[::2]) # both two side has to be [::1], because the concatenate part may have problem nums[::2],nums[1::2] = nums[:half][::-1],nums[half:][::-1] nums = map(int,raw_input().split()) solution = Solution() print sol...
33cd38c311bb5dba896c277d08500cac2c435e38
wmaterna/Python-Zestawy
/Zestaw3/zadanie3.6.py
505
4.125
4
x = input("Enter length: ") y = input("Enter hight: ") horizontal = '+---' wholeString = '' for i in range(0,int(y)): for i in range(0, int(x)): wholeString = wholeString + horizontal wholeString = wholeString + '+' + '\n' for i in range(0, int(x)): wholeString = wholeString + '|' + ''.ljus...
3e17d74428e2e74030ac6a5b8e4e2f455a90431c
wmaterna/Python-Zestawy
/Zestaw3/zadanie3.5.py
377
3.953125
4
unit = '....|' x = input("Enter length of measure: ") rangeOfMeasure = range(0, int(x)) measure = '|' for i in rangeOfMeasure: measure = measure + unit measure = measure + "\n" unitNum = '' txt = '' for i in rangeOfMeasure: length = txt.ljust(len(unit) - len(str(i+1))) unitNum = unitNum + str(i) + length ho...
2f900a450d6fa51acfc98ce6fc2db524119068ab
wmaterna/Python-Zestawy
/Zestaw8/zadanie8.1.py
1,217
3.796875
4
# SPECYFIKACJA PROBELMU: # Znajdywania rozwiązań równania liniowego ax+by+c = 0 # DANE WEJŚCIOWE: # Trzy liczby a,b,c stanowiące o równianiu # DANE WYJŚCIOWE: # Rozwiązanie w postaci komunikatu # Lista kroków: # K01: Wczytaj a, b, c # K02: Sprawdź, które elemety są równe zero, jeżeli: # a,b,c = 0 wypisz brak rozwiazan...
aff8ed023341983b59ed54da1fbcb54e4ea6eeb2
tarynash/hackbright-intro-tuples-strings
/02-strings/guess_number.py
308
3.984375
4
from random import randint random_variable = randint(1,10) print random_variable guess = int(raw_input("Guess a number from 1 to 10: ")) while(guess != random_variable): if(guess > random_variable): print "too high!" else: print "too low!" guess = int(raw_input("Guess again: ")) print "You win!"
c688d0e0fd9e00ea15124fb043cf622657724f51
ivanelisandro/PythonStudiesJobAgency
/Topics/Loop control statements/The mean/main.py
269
3.96875
4
current_entry = -1 total = 0 quantity = 0 while current_entry != '.': current_entry = input() try: number = int(current_entry) total += number quantity += 1 except ValueError: pass average = total / quantity print(average)
004d7e7459f43bf5ac8f37d56342df192e1a862e
Susaposa/Homwork_game-
/solutions/2_functions.py
1,202
4.125
4
# REMINDER: Only do one challenge at a time! Save and test after every one. print('Challenge 1 -------------') # Challenge 1: # Write the code to "invoke" the function named challenge_1 def challenge_1(): print('Hello Functional World!') challenge_1() print('Challenge 2 -------------') # Challenge 3: # Uncommen...
1849afeceb4070855ab82a01177bbbc96b8b18da
Susaposa/Homwork_game-
/activities/2_functions.py
4,996
4.3125
4
# REMINDER: Only do one challenge at a time! Save and test after every one. # Challenge 0: Remember: Do the first thing for any Python activity. print('Challenge 1 -------------') # Challenge 1: # Write the code to "invoke" the function named challenge_1 def challenge_1(): print('Hello Functional World!') chall...
9552c37d72d72b2d3149efc3ebe3b0be22692ac7
SaJa-ai/Nancho_ai
/chatbot.py
1,210
3.625
4
import random greetings = ['hello', 'hola', 'hi', 'Hi', 'hey!','hey'] random_greeting = random.choice(greetings) question = ['How are you?','How are you doing?'] responses = ['Okay',"I'm fine"] random_response = random.choice(responses) question = ['good Morning','good night'] responses = ['You 2.',"Thank'...
14544b0b47b7eeb2888dfa7533f5dc7f509d82b9
kszabova/lyrics-analysis
/lyrics_analysis/lyrics_tagging/lyrics_tagging.py
799
3.625
4
import lyrics_analysis def tag_rhymes(lyrics, cls): """ Wraps rhyming words of lyrics inside a class tag. :param lyrics: Lyrics where lines are separated by newlines :param cls: Class name that rhyming words should be wrapped in. :return: Lyrics separated by newlines with appropriately tagg...
1c677685c0ac7588a22f03eb6e22a9e00255b9b6
kszabova/lyrics-analysis
/lyrics_analysis/sampler/sample.py
1,977
4
4
import random def sample_n_songs_from_generator(n, file_line_generator, total_n=None, filter=(lambda _: True)): """ Selects n random examples from src_stream. The result will be returned as a generator. :param n: How many examples to take :param file_line_generator: Function that creates a genera...