blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
db8928441267551ec01087e01bcde08756589c0c
davidadamojr/diary_of_programming_puzzles
/sorting_and_searching/binary_search_recursive.py
564
3.96875
4
def binary_search(sorted_list, left, right, key): midpoint = (left + right) / 2 middle_element = sorted_list[midpoint] if middle_element == key: return "Key found at position: " + str(midpoint) if right <= left: return "Could not find element" if key < middle_element: retur...
43f837964e71bf191eb7d40d4092de41df411f04
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/pascals_triangle_2.py
632
4.03125
4
""" Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, return [1,3,3,1] Leetcode question: https://leetcode.com/problems/pascals-triangle-ii/ """ def get_pascal_row(row_index): """Optimized for O(k) space""" row = [0 for i in range(0, row_index + 1)] for row_num in...
a61877902f47e882fa5aabd0adbaa55f1ffe1d92
davidadamojr/diary_of_programming_puzzles
/bit_manipulation/same_number_of_ones_bf.py
1,446
3.75
4
""" Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. """ # brute force solution that first counts the number of ones in the integer and # then continuously increments or decrements until it finds an integer with the # ...
f71d41af482269acd95a3e621f86682fb14a89ed
davidadamojr/diary_of_programming_puzzles
/bit_manipulation/counting_bits.py
1,292
4.09375
4
""" Given a non-negative integer number "num". For every numbers i in the range 0<=i<=num, calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5, you should return [0,1,1,2,1,2] Follow up: - It is very easy to come up with a solution with run time O(n*sizeof(inte...
b590a55877b09b5d7ad28b1d059988d6b6d18fbb
davidadamojr/diary_of_programming_puzzles
/recursion_and_dynamic_programming/pick_m_elements_tail_recursion.py
965
4.0625
4
""" Write a method to randomly generate a set of n integers from an array of size n. Each element must have equal probability of being chosen. """ import random # @param original_list list of n elements where m elements will be picked from # @param number_of_elements list of elements to be picked # @param m_index t...
7056be4296ae099551ffab90ac66075025d906b0
davidadamojr/diary_of_programming_puzzles
/recursion_and_dynamic_programming/all_subsets_recursive.py
638
4.0625
4
""" Write a method to return all subsets of a set """ all_subsets = [[]] # @param original_set a list of integers def get_all_subsets(original_set, n): # recursive solution - O(2^n) where n is the size of the original set if n >= len(original_set): return new_subsets = [] for subset in all_...
77bde9fd4e70f7bb6b56df5aeda363b9642b6db9
davidadamojr/diary_of_programming_puzzles
/misc/count_twos_bf.py
522
3.96875
4
""" Write a method to count the number of 2s between 0 and n """ # brute force solution # sum up the number of twos in each digit from 0 to n def number_of_twos(number): count = 0 for i in range(2, number + 1): count = count + get_number_of_twos(i) return count def get_number_of_twos(number): ...
f26151d672804487996c5e3f0633515146a92ab9
davidadamojr/diary_of_programming_puzzles
/recursion_and_dynamic_programming/string_combinations.py
960
4.09375
4
""" Implement a function that prints all possible combinations of the characters in a string. These combinations range in length from one to the length of the string. Two combinations that differ only in ordering of their characters are the same combination. In other words, "12" and "31" are different combinations ...
e114ca362bb69f5298c5137696ee4aaffec569ad
davidadamojr/diary_of_programming_puzzles
/mathematics_and_probability/intersect.py
931
4.125
4
""" Given two lines on a Cartesian plane, determine whether the two lines would intersect. """ class Line: def __init__(self, slope, yIntercept): self.slope = slope self.yIntercept = yIntercept def intersect(line1, line2): """ If two different lines are not parallel, then they intersect...
3c964c3542a076dfd60282db1d6fbeeae0f88132
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/excel_sheet_column_number.py
851
4.03125
4
""" Given a column title as appears in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 Leetcode problem: https://leetcode.com/problems/excel-sheet-column-number/ """ def title_to_number(column_title): # this is pretty much a base 26 number...
76e8af6b3ef66bce39724bd917d84150361c139e
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/excel_sheet_column_title.py
662
4.15625
4
""" Given a positive integer, return its corresponding column title as it appears in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB """ def convert_to_title(num): integer_map = {} characters = "ZABCDEFGHIJKLMNOPQRSTUVWXY" for i in range(0, 26): integer_map[i] = c...
16cd5990109cf3465638230214e4dbedc66bbc54
Zurol/UAD-IntroduccionProgramacion
/conjuntosInterseccionUnion.py
1,068
3.859375
4
# Generar la unión e intersección de 2 colecciones. animalesTerrestres = ["Perro", "Gato", "Tortuga", "Liebre", "Pingüino"] animalesMarinos = ["Tortuga", "Ballena", "Calamar", "Pingüino"] # A Unión B animales = [] for animalMarino in animalesMarinos : for animalTerrestre in animalesTerrestres : #pr...
a1adebf6a6f32f9139d65179988fe3220ce2e058
Adria-Bonjorn/PersonalProjectsPython
/ComfredABCv2ENG.py
5,363
3.90625
4
#CODE FOR HVAC MACHINE SELECTION****By: Adrià Bonjorn Cervera - July 2021 #Import function "ceil" from library "math" from math import ceil print("\n----------------------------------------") print("AIR CONDITIONING MACHINE SELECTION - Adrià Bonjorn") print("----------------------------------------\n") #-...
8ec11e6432d5ab941bc2b38d119b38d01387cc67
tborisova/homeworks
/7th-semester/ai/hw4.py
1,497
3.703125
4
import collections import functools class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def __init__(self, func): self.func = func self.cache = {} def __...
5d28c27cfcdfdcee291dac3178563271a81ef909
Pokecris200/CNYT
/clasico_a_cuantico.py
602
3.515625
4
from matplotlib import pyplot from Libreria1 import * import math def pot (matriz,exp): for i in range (1,b): res = multiMatrix(matriz,matriz) return res def experimentos(a, b, c): r1 = pot(a,c) r2 = Accion(r1,b) return(res2) def probabilidad (vector): x,y = [],[] for ...
8fe3537b1aae05334e6137adfb355f936d7a1c99
pareshh7/beautifulsoup
/14 Next Siblings & Previous Siblings.py
530
3.828125
4
from bs4 import BeautifulSoup #import beautiful soup library def read_file(): #function to read file file = open('three_sisters.html') data = file.read() file.close() return data soup = BeautifulSoup(read_file(),'lxml') #make soup p = (soup.body.p) # .next_siblings returns an iterator of next...
866d5d5c3cedd726a360e6c14fd079248b128ff6
pareshh7/beautifulsoup
/15 Find All Function Parameters (1).py
963
3.71875
4
from bs4 import BeautifulSoup #import beautiful soup library def read_file(): #function to read file file = open('three_sisters.html') data = file.read() file.close() return data soup = BeautifulSoup(read_file(),'lxml') #make soup #Signature: find_all(name, attrs, recursive, string, limi...
85c3c31a4e98c2951446401c6bc8994aba9eda08
parthpatadiya/Incubyte_assessment_parth_patadiya
/data_cleaning.py
2,389
3.703125
4
import pandas as pd import numpy as np def data_cleaning(file_path): #Name of each columns column_name=["Customer Name","Customer ID","Customer Open Date","Last Consulted Date","Vaccination Type", "Doctor Consulted","State","Country","Date of Birth","Active Customer"] # Read pipe delimit...
bf0610b20d7800f7686f8a779546e16e98af2b13
Annarien/Python-Getting-Started
/exceptional.py
1,398
3.65625
4
""" Follows the work done on exceptions in the course: Core Python: Getting Started @ https://app.pluralsight.com/course-player?clipId=a8b1ac0f-c305-4505-a0d8-b40f4f858fcf """ # imports import sys from math import log # this is the DIGIT_MAP used throughout this file DIGIT_MAP = { 'zero': '0', 'one': '1', ...
d94edb8bda80e920c6ffe3012c7d817b783265bd
Engy-Bakr/python
/ASSIG0/ass1.py
264
3.921875
4
def vowelsremover(word): vowels = ('a', 'e', 'i', 'o', 'u') for i in word: if i in vowels: word=word.replace(i,'') return(word) # word=input('input the word ') # print(vowelsremover(word))
6394500e3e3f5d5d0864e34609b2e24c1118b1a0
liangricky7/mathcircleproject2019
/mathcircleproj.py
820
4.03125
4
from matplotlib import pyplot as plt import random as rnd import numpy as np #starting amount of money x = [0] y = [50] def flipping_fair(n_simulations = 50): # amount of dollars balance = 50 for i in range(n_simulations): # marks bounds of gambling while 100 > balance and balance > 0: coin = rnd.randint...
ad0077c9a88adf7c5b74afa0e53814d6bb84875b
aedillo15/RolePlayingGame
/modules/Game.py
24,925
4.1875
4
"""This python file is going to serve as the implementation of game data and logic and the interactivity with the user.""" #Imported Modules including random, Warrior, Wizard import random import Warrior import Wizard #This GameMenu() method represents the introduction of the game, asking for users name and creating th...
f5bd29f7ef1a6e02b7260da959eaaf82fbf1e992
thetravisw/Data-Structures-And-Algorithms2
/Data_Structures/old_stuff/linked_list/ll_merge/ll_merge.py
524
3.890625
4
from Data_Structures.linked_list import Linked_List def merge_lists (list_a, list_b): results = Linked_List() if list_a.head == None: return list_b if list_b.head == None: return list_a a = list_a.head b = list_b.head results.head = a if a == None: results.head = b if a != None...
f929d0829121d98e1d799e18ad2b86cbe2f1992a
eoguzinci/KUL_Datathon_Laqua
/leuvenair/myutils/gmap_utils.py
1,881
3.546875
4
# do not forget to enable gmaps in jupyter notebook by executing the following command # in ipython shell ``jupyter nbextension enable --py gmaps`` import gmaps import numpy as np def get_gmap_figure(LAT, LON, filename = 'apikey.txt'): # Reference: https://jupyter-gmaps.readthedocs.io/en/latest/tutorial....
9b3ddafe986acf4bbd79367e34b6d2eabcadb314
gabrielelanaro/scripting
/scripting/textprocessing.py
1,945
3.5625
4
import re from utils import partition def grep(pattern, filename): """Given a regex *pattern* return the lines in the file *filename* that contains the pattern. """ return greplines(pattern, open(filename)) def greplines(pattern, lines): """Given a list of strings *lines* return the lines tha...
2e1878f64e8d2492350bd51fd13e41922d31dc97
jeremy1111/bink
/helper_funcs.py
573
3.5625
4
from datetime import datetime, date def organise_output(contents): list_contents = list(contents) for i, d in enumerate(list_contents): line = '|'.join(str(item).ljust(80) for item in d) if i == 0: print('-' * len(line)) print(line) def convert_to_date(date_string): str...
72c326034ab55fd69ebfcfeaaa7403d7af9b79b7
RKH333/BYC
/BYC.py
2,431
4.03125
4
# Juego Bulls&Cows/ Toros y Vacas # Roberto Chen Zheng from random import randint def Reglas(): print("\nEl objetivo:\nAdivinar el número al azar de n dígitos") print("Las cifras son todas diferentes") print("Toro: Si una cifra está presente y se encuentra en el lugar correcto") print("Vaca: ...
44f5fcd365a974b30ce7c120070e701b3b8f0efa
MichaelLegg/AdventOfCode2017
/Day 4/Kane/adventofcode_day4.py
1,586
3.734375
4
def noDupes(): count = 0 with open('input.txt') as f: for line in f: line = map(str, line.split(" ")) bool = False for i in range(len(line)): for j in range(i+1,len(line)): line[i] = line[i].rstrip('\n') line[j] ...
41bfd5f2166cc575d70d6f38f572530da07ae8bb
San221/Snake-game-using-python-turtle-module
/snake_game.py
4,340
3.953125
4
import turtle import time import random delay =0.1 ## Score score=0 high_score=0 ## Set up screen wn= turtle.Screen() wn.title("Snake Game by San") wn.bgcolor("green") wn.setup(width=600, height=600) wn.tracer(0) # BY putting zero it turns off the screen animation ## Snake head head= turtle.Tur...
91efd9412dab08e3f3735a4f909da79648c1b511
Hchyeria/some-data-structure-and-algorithm
/1/SplayTree.py
5,536
3.9375
4
# -*- coding:utf-8 -*- """ Splay tree Question 1 Author: Hchyeria """ # 定义一个 TreeNode 类 保存树的节点信息 # 包括自身的数值 和 左右孩子节点 父节点信息 class TreeNode: def __init__(self, val: int): self.val = val self.left = self.right = self.parent = None # 定义一个 BinarySearchTree 类 # 可以进行删除 插入 和 查找操作 # 其中都需要将目标节点...
8d089b1da8015d9e4e9420e10d63b7a22ab11dbd
spacerunaway/world_recoder
/music/chord.py
11,104
3.859375
4
from scale import * import copy CHORD_TYPE={'M':major,'m':minor,'dim','aug'} class Chord(Scale): """ A chord is any harmonic set of pitches consisting of two or more (usually three or more) notes (also called "pitches") that are heard as if sounding simultaneously. (For many practical and theoretical p...
ea8f49b1df16ef031010fcf8629412362eccffe0
CindyWei/Python
/ex18.py
752
3.953125
4
#coding=utf-8 ''' 2014-2-9 习题18:命名、变量、代码、函数 ''' #this one is like your scripts with argv def print_two(*args): #将函数的所有参数都接收进来 arg1, arg2 = args #将参数解包 print "arg1: %r, arg2: %r" %(arg1, arg2) #ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (a...
e6d847fbca7e196b13b3da94080a760656626497
CindyWei/Python
/ex41.py
1,295
4.15625
4
#coding=utf-8 ''' 2014-2-11 习题41:类 ''' class TheThing(object): def __init__(self): self.number = 0 def some_function(self): print "I got called" def add_me_up(self, more): self.number += more return self.number a = TheThing() b = TheThing() a.some_function() b.some_function() print a.add_me_up(20) prin...
ed1bd6b9eeb6d9dafad2bab38a3516836d0178c5
elisemmc/EECS800
/Lab2/NaiveBayes.py
4,276
3.65625
4
# coding: utf-8 # In[6]: from __future__ import division from sklearn import datasets import pandas as pd import numpy as np import math import operator #Please complete the following Naive Bayes code based on the given instructions # Load the training and test dataset. #Please handle the data with 'dataframe' ty...
282c057e572159d08a607c0f382c0e53b27a45e1
cfernandez005/Software-Testing-with-Python
/Shopping List Test/hw2.py
3,173
3.5625
4
#Chris Fernandez #4/9/16 #Assignment #2: unittest module import unittest #imports in the unittest class from hw1 import * #imports all code from hw1.py class shoppingListTest(unittest.TestCase): #class that defines code to be tested def testIsComplete_onePositiveQuantity(self): # is_complete function test ca...
00e06879ec7de3ee1fc6e9927b5e7c8783047067
m-hawke/codeeval
/moderate/170_guess_the_number.py
338
3.625
4
import sys for line in open(sys.argv[1]): l = line.split() lower = 0 upper = int(l[0]) for answer in l[1:]: guess = lower + ((upper - lower + 1) // 2) if answer == 'Lower': upper = guess - 1 elif answer == 'Higher': lower = guess + 1 else: ...
065771d0f3f9d50fe8cdf1ec1fbe6c44ea3b2cb3
m-hawke/codeeval
/easy/202_stepwise_word.py
226
3.703125
4
import sys for line in open(sys.argv[1]): longest = '' for word in line.split(): if len(word) > len(longest): longest = word for i, c in enumerate(longest): print '*' * i + c, print
4688687e9a0f060339ab9aa968ce420d3a458e8f
m-hawke/codeeval
/easy/240_mersenne_prime.py
894
3.671875
4
import sys def is_prime(n): if n <= 1: return False if n <= 3: return True if n%2 == 0 or n%3 == 0: return False if n < 25: return True for i in range(3, int(n**0.5)+1, 2): if n%i==0: return False return True from itertools import count def g...
a0670f05cc06bde04970f5325947af298724ff90
m-hawke/codeeval
/easy/139_working_experience.py
1,663
3.703125
4
import sys month_name_to_number = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12) def to_months(s): month, year = s.split() return (int(year) * 12) + month_name_to_number[month] for line in open(sys.argv[1]): months = 0 previous_end = 0 for start, end i...
0fe3ef67c5d137ae7ea4d3615800e98af00a1138
m-hawke/codeeval
/easy/19_bit_positions.py
168
3.5
4
import sys for line in open(sys.argv[1]): n, p1, p2 = (int(x) for x in line.split(',')) print('true' if ((n >> (p1-1) & 1) == (n >> (p2-1) & 1)) else 'false')
5185d421330d59dc45577e6ed4e046a961461ae6
m-hawke/codeeval
/moderate/17_sum_of_integers.py
970
3.703125
4
import sys for line in open(sys.argv[1]): numbers = [int(x) for x in line.strip().split(',')] max_ = sum(numbers) for length in range(1, len(numbers), 2): # N.B increment by 2 sum_ = sum(numbers[:length]) max_ = sum_ if sum_ > max_ else max_ for i in range(len(numbers)-length): ...
332acd1b09be1ad4bdea876a5f3f82633319c7bc
cryojack/python-programs
/charword.py
402
4.34375
4
# program to count words, characters def countWord(): c_str,c_char = "","" c_str = raw_input("Enter a string : ") c_char = c_str.split() print "Word count : ", len(c_char) def countChar(): c_str,c_char = "","" charcount_int = 0 c_str = raw_input("Enter a string : ") for c_char in c_str: if c_char is not " "...
97b52a2ae01df1847f043ac37a45c2d47e2cbb3f
cryojack/python-programs
/multiply.py
298
4.0625
4
#This program prints a multiplication table upto count_int num1_int = 1 num2_int = 1 res_int = 0 count_int = 10 while num1_int <= count_int: res_int = num1_int * num2_int print num1_int , " x " , num2_int , " = " , res_int num2_int += 1 if num2_int > count_int: num2_int = 1 num1_int += 1
e8db5926f025fcd3547334aeb313c1a7c7012940
akshatha-nayak/quiz-application
/quiz_application_akshatha.py
7,733
3.734375
4
import json def edit_q(di,sub,level,ques): print(di["quiz"][sub][level][ques]["question"]) question=input("Edit question: ") di["quiz"][sub][level][ques]["question"]=question return di def edit_o(di,sub,level,ques): c=1 for option in di['quiz'][sub][level][ques]['options']: ...
7111f56b0b2682a68818482d802c98aa4b81e072
dennis-wei/AdventCode2019
/17/solution.py
2,157
3.5
4
from computer import Computer import time from collections import defaultdict import math def parse_input(filename): with open(filename, 'r') as f: return [int(n) for n in f.read().strip().split(',')] def get_adjacent(x, y): return [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)] def print_grid(grid)...
112b49adaf048b44ce9ef2cc25520fd5d85685be
Rekk-e/FoodForStudent
/main.py
630
3.75
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. # Press the green button in the gutter to run the script. if __name__ == '__main__': print('n=') n = int(input()...
a922e393c7f593a0f00bbe645c9dc344db6c173c
Daywison11/Python-exercicios-
/ex040.py
587
3.84375
4
#Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem # no final, de acordo com a média atingida: #- Média abaixo de 5.0: REPROVADO #- Média entre 5.0 e 6.9: RECUPERAÇÃO #- Média 7.0 ou superior: APROVADO n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a se...
28d38ddd8f5cf86011e785037ef891a338810b23
Daywison11/Python-exercicios-
/ex014.py
252
4.25
4
# Escreva um programa que converta uma temperatura digitando # em graus Celsius e converta para graus Fahrenheit. gc = float(input('infoeme a temperatra em °C :')) fr = ((9*gc)/5) + 32 print('a temeratura de {}°C conrresponde a {}° F'.format(gc,fr))
4da9c666be85e52340aab787a3111fa7da1a1e29
Daywison11/Python-exercicios-
/ex013.py
259
3.640625
4
"""faça um programa que leia o salario de um fncionario e calcule o novo salario com 15% de almento""" sl = float(input('digite o seu salario atual :')) s1 = (sl * 15) s2 = (s1 / 100) s3 = (s2 + sl) print('o seu salrio com 15% de almento é {}'.format(s3))
09a9915bab7ba3d94aeb385f9500567d3f47f9ee
Daywison11/Python-exercicios-
/ex001.py
214
3.625
4
nm =input('input qual seu nome ?') idd =input('quantos anos voce tem ? ') cdd =input('qual sua cidade natal?') print('então seu nome é',nm,'voce tem',idd,'anos e voce mora na cidade de',cdd) print('estou certo?')
a1694deb4ac7b9e21d5057dbba059274cfea5290
Daywison11/Python-exercicios-
/ex006.py
246
4.09375
4
"""#crie um algoritimo que mostre seu dobro, triplo e a raiz quadrada""" n1 = int(input('digite um numero: ')) D = (n1 * 2) t = (n1 * 3) rq = (n1 **(1/2)) print('o dobro desse numero é {} o triplo é {} e a raiz quadrada é {}'.format(D,t,rq))
7a4e9d405f3eaf80368e7d8d64ffbcf79d806a36
hunguyen1702/lpthw
/ex45_maze_runner/weapon.py
726
3.546875
4
class Weapon(object): def __init__(self): self.name = "Weapon" self.damage = 0 self.stability = 0 def decrease_stability(self): self.stability -= 1 def is_broken(self): if self.stability < 1: print "%r is broken" % self.name return True ...
19310bbd5067e23a07056a18585c5d2ff328d72a
ecaoili24/holbertonschool-higher_level_programming
/0x0B-python-input_output/9-add_item.py
505
3.6875
4
#!/usr/bin/python3 """Module 9-add_item Adds all arguments to a Python list, and then save them to a file """ import sys import json save_to_json_file = __import__("7-save_to_json_file").save_to_json_file load_from_json_file = __import__("8-load_from_json_file").load_from_json_file filename = "add_item.json" my_li...
9f98c013d81e525f857fafffec8301a5f57b97ca
ecaoili24/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
111
3.578125
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): return {key: x * 2 for key, x in a_dictionary.items()}
b3acfef8d2e2a8974b0c41b133bde3c2e7091030
ecaoili24/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,283
4.0625
4
#!/usr/bin/python3 """ This module contains the matrix_divided function """ def matrix_divided(matrix, div): """ Divides all elements of a matrix. Returns a new matrix (list of list). The result is rounded to 2 decimal places. """ if not isinstance(matrix, list) or len(matrix) == 0 or not mat...
5940b3f15cdea71a5c640d29579398334e0381b7
sachin-goyal-github/python-dojos
/katas/data-munging/part-one.py
762
3.984375
4
""" # http://codekata.com/kata/kata04-data-munging/ Part One: Weather Data In weather.dat you’ll find daily weather data for Morristown, NJ for June 2002. Download this text file, then write a program to output the day number (column one) with the smallest temperature spread (the maximum temperature is the second colu...
580abee3fc3b1aa466caa38d6e38e2b0e4fb3d50
guard1000/Everyday-coding
/190319_[모의 SW 역량테스트]_벽돌 깨기.py
3,840
3.5
4
import itertools def bomb(board2, pos): nxt=[] if len(pos) == 0: return board2 for p in pos: #다음 폭발 d = p[2] board2[p[0]][p[1]] = 0 #펑 for r in range(1,d): #up if p[0] - r < 0 or board2[p[0] - r][p[1]] == 0: break elif board2[p[0]-r][p[1]] != 1 and [p[0...
29d286f30d32b97138e37ae81ceb5bb38a63c4b5
guard1000/Everyday-coding
/1013문알준비.py
843
3.953125
4
''' print([num * 3 for num in range(3)]) print([num * 3 for num in range(10) if num % 2 == 0]) print([x * y for x in range(2, 10) for y in range(1, 10)]) ''' # 실습 1 for i in range(5): # 혹은 (1,6): for j in range(5-i): print('*', end='') print("") #실습 2번 print('1번') num = [1,2,3,4,5,6,7,8,9,10] resul...
e19a24fc954f816fea4cd614353d38e5cc5f1698
guard1000/Everyday-coding
/14주차_문알준비_tkinter.py
5,193
3.53125
4
from turtle import* penup() 금액 = numinput("지불액",'얼마를 받아야 합니까? ') goto(0,260) msg1 = str(int(금액))+'원 받아야 합니다!' write(msg1,align = "left", font=('Arial', 15,"bole")) 낸돈 = numinput("받은돈",'얼마를 받았습니까? ') goto(0,290) msg2 = str(int(낸돈))+'원 받았습니다!' write(msg2,align = "left", font=('Arial', 15,"bold")) if 낸돈 < 금액: goto(2...
8604f551595a8601f5b3085c2d7e2623af5e69e6
guard1000/Everyday-coding
/algo0920.py
761
3.5
4
#선택 정렬 def SelectionSort(data): for i in range(0, len(data)-1): j=i+1 while(j < len(data)): if data[i] > data[j]: data[i],data[j] = data[j],data[i] j = j+1 return data All = [] #데이터 리스트입니다. with open('data.txt') as f: #데이터를 READ하...
f9840bccce9ab85dd3a92b646d80f5134f81ac5a
guard1000/Everyday-coding
/190118_타일 장식물.py
234
3.546875
4
def func(a,b,N): c = a+b N -= 1 if N == 0: return 2*(c+b)+2*c return func(b,c,N) def solution(N): if N == 1: return 4 if N == 2: return 6 return func(1,1,N-2) print(solution(5)) print(solution(6))
8bee9637f999a7d2b935c2b334cb3e54b9525572
guard1000/Everyday-coding
/190226_자동완성.py
1,617
3.640625
4
class Node(object): def __init__(self, key, data=None): self.key = key self.data = data self.cnt=0 self.children = {} class Trie(object): def __init__(self): self.head = Node(None) def insert(self, string): curr_node = self.head for char in string: ...
76137c57fb4ed3643916d81c75f2fc7b6047a95d
guard1000/Everyday-coding
/1006_H-Index.py
391
3.6875
4
#string = "this is test string" #print (string.find("test")) def solution(phone_book): answer = True pb= sorted(phone_book, key=lambda x: len(x)) for i in range(len(pb)-1): for j in range(1, len(pb)-i): if pb[i+j].find(pb[i]) == 0: answer = False break ...
75754e6d155b309fe88826f1e31abf1f89b26f89
guard1000/Everyday-coding
/quick_sort.py
1,020
3.578125
4
def quick_sorted(arr): if len(arr) > 1: #그래도 일단 원소가 2개이상은 되어야 정렬을 할 것입니다. pivot = arr[len(arr) - 1] #피봇을 잡음. left, mid, right = [], [], [] #피봇보다 작은 녀석은 left, 큰건 right, 피봇과 같은 값이면 mid에 for i in range(len(arr)): if arr[i] < pivot: left.app...
f459575bade7989019661f8cb804b67d89fa0059
guard1000/Everyday-coding
/0902.py
1,980
3.515625
4
import re #입력받는 특수문자, 숫자를 없애기 위해 정규식 사용 str1 = input() str2 = input() str1 = re.sub('[^A-Za-z]+', '', str1) #정규식. A-Z나 a-z외엔 모두제거 str2 = re.sub('[^A-Za-z]+', '', str2) str1 = list(str1) #정규화된 결과를 한글자씩 list로 넣음 str2 = list(str2) len1 = len(str1) #각...
b05739c495c2fa16e7bcbc7ec804562ffead519c
sallybao29/Softdev-Spring
/hw09/qsort.py
325
3.5
4
import random def qsort(l): if len(l) <= 1: return l pivot = random.choice(l) nl = l[0:pivot] + l[pivot+1:] lh = [x for x in nl if x < pivot] uh = [x for x in nl if x > pivot] return qsort(lh) + [x for x in l if x == pivot] + qsort(uh) l = [10, 5, 9, 10, 4, 256, 2, 2] print qsor...
2fe0c11eec86719da7ff695feec54bc2a5aedead
Tohanos/randomPotGenerator
/main.py
1,337
3.671875
4
import random import numpy as np import matplotlib.pyplot as plt class RandomPot: def __init__(self, initval, maxspeed, mindif): self.value = initval self.maxSpeed = maxspeed self.speed = 0 self.mindif = mindif def calcnextval(self, target): dif = target - self.value ...
97b03f37db8b4930824932c531d53d3140fe190b
sysravi/codechef_pr_beginner
/HEADBOB.py
343
3.765625
4
r=int(input()) for _ in range(r): n=int(input()) x=input() flag=False for i in x: if i!="N": if i=="Y" : ntn="NOT INDIAN" if i=="I": ntn="INDIAN" flag=True break if (flag==False): print("NOT SURE") el...
7e1a037b78764940af13e570c85594f6e9ff8752
sysravi/codechef_pr_beginner
/TRISQ.py
111
3.609375
4
for i in range(int(input())): x = int(input()) x -= 2 x = x//2 y = int(x*(x+1)/2) print(y)
d2ba291623cfb50ca5845e2d668f0cabf51aaa53
operationstratus/viper_chaos
/battleship_game/battleship_01.py
1,659
3.703125
4
n = 5 # n x n b = 10 # boats HITS = 0 BOOMS = 0 class Tile: def __init__(self, boat=False): self.__boat = boat self.__character = " " def shoot(self): if self.__boat: self.__character = "x" return self.__boat # returns true if there indeed was a boat here...
4b99c54daf8a88d2f1b7d612de255bd7900baeee
SuperN8er/MMM
/median.py
689
4.03125
4
"""Module for working with median""" from rand_data import get_rand_nums def calc_median(nums): """Calculate the mean, given a list of numbers""" sorted_nums = sorted(nums) print(sorted_nums) length = len(sorted_nums) midpoint = length // 2 if (length % 2) == 1: # odd median ...
2ca54deca377673e4503cfff0a5a3859d3cdff28
netraan/star-python
/star_turtleramdom.py
738
3.765625
4
import turtle import time import random start = time.time() #init t=turtle.Turtle() t.hideturtle() # number of points n = random.randrange(3,10) # number of points RT = random.randrange(1,200) # deg right turn L = random.randrange(10,100) # line length dL = random.randrange(10,100) LT = RT-360/n #print parameters p...
f36812817952c945fab0a069bef59c400a0f7abc
Bairdotr/Development
/auth.py
4,843
3.875
4
# register # - first name, last name, password, email # - generate user account number # login # - account number & password # bank operations # Initializing the system import random import validation import database from getpass import getpass def init(): print("Welcome to bankPHP") ...
c08e6a357ee5cd58f4a171dc81b001df5a8f487a
rPuH4/pythonintask
/INBa/2015/Serdehnaya_A_M/task_5_25.py
1,494
4.25
4
# Задача 5. Вариант 28. # Напишите программу, которая бы при запуске случайным образом отображала название одной из пятнадцати республик, входящих в состав СССР. # Serdehnaya A.M. # 25.04.2016 import random print ("Программа случчайным образом отображает название одной из пятнадцати республик, входящих в состав СС...
7f6cb8a9c235dd399d270576726824353ed5af7e
ThomasBrouwer/project_euler
/problem_34.py
336
4.03125
4
def factorial(n): result = 1 while n > 1: result *= n n -= 1 return result def sum_factorial_of_digits(n): digits = str(n) return sum([factorial(long(char)) for char in digits]) curious_numbers = [] for i in xrange(3,factorial(9)*9): if i == sum_factorial_of_digits(i): curious_numbers.append(i) print sum(...
f63b7915ae8b9778ceeccc99e377065f609a8efe
ThomasBrouwer/project_euler
/problem_10.py
524
3.546875
4
def find_next_prime(values,start,length): for v in range(start,length): if values[v] != 0: return v return -1 # We mark values by 0 if they are marked off max_value = 2000000 primes = [1] # little hack values = range(0,max_value+1) values[1] = 0 # Use sieve of Eratosthenes while True: next_prime = find_next_pr...
1af2a3e8831f99c842cefccdfec0dad506020c94
ThomasBrouwer/project_euler
/problem_18.py
946
3.578125
4
triangle = \ """75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 6...
0f0d02cc5888cd6871a57557b9588e56031f37be
ThomasBrouwer/project_euler
/problem_50.py
1,211
3.640625
4
import math from collections import deque def is_prime(n): for i in xrange(2,long(math.sqrt(n))+1): if n % i == 0: return False return True def find_no_consecutive_terms(value,primes,best_so_far): selected_primes = deque([]) sum_selection = 0 length_selected = 0 for prime in primes: selected_primes.appen...
ff91fe7350f4ffa0662b186a62708101dfb8e0a6
ThomasBrouwer/project_euler
/problem_31.py
703
3.890625
4
def greedy_fill(coin,money_left,stack): while coin <= money_left: stack.append(coin) money_left -= coin return money_left def coins_lower_than(coins,value): return [coin for coin in coins if coin < value] coins = [1,2,5,10,20,50,100,200] coins_left = coins[:] stack = [] money_left = 200 number_ways = 0 while ...
bbeda9d0c0021a86fffa083afebc231058a65596
rixwoodling/betelnuts
/hsinchu.py
531
3.671875
4
#!/usr/bin/python3 from time import sleep import piglow import random piglow.auto_update = True piglow.all( 0 ) def colorful_raindrops(): count = 0 leds = list(range( 0,18 )) random.shuffle( leds ) while ( count < 3 ): for i in leds: piglow.led( i, 100 ) sleep( 0.1 ) ...
fe090069d1ceb7fda31264a723f18bd67d48842a
jocarmp08/Tutoria-IC1802
/Semana #7/2016106261_Examen01.py
8,283
4.0625
4
''' Examen I de Introducción a la programación Estudiante: José Carlos Montoya Pichardo Carné: 2016106261 ''' # =========================Función sumatoria_pares============================= ''' Esta función permite sumar los números que se encuentran dentro de un rango definido, basado en su valor par o impar. Entr...
ef43a75e51b3d92d10d3e67ad1db0549fce4afd1
War10c3/AI_ML-Assignment
/assign7.py
486
3.765625
4
#ques 1 a=eval(input('enter dictionary')) b=int(input('enter the value')) for k,v in a.items(): if b==v: break print(k) #ques 2 a={'sarthak':{'maths':30,'physics':30,'chem':90},'ronaldo':{'maths':90,'physics':50,'chem':10},'vipul':{'maths':78,'physics':30,'chem':60}} b=str(input('enter name of st...
9effe1afdc7532ae0535d09927626a6fdd586c28
War10c3/AI_ML-Assignment
/assign9.py
668
3.65625
4
# ques 1 a=3 try: if a<4: a=a/(a-3) except ZeroDivisionError: print("this question has Zero division error") print(a) ques 2 l=[1,2,3] try: print(l[3]) except IndexError: print("It shows index error\n") print (l) # ques 3 """ OUTPUT = An Exception Nam...
bbaf1dec6b370ba832181e6b33f6e0f18a8490fb
ElianEstrada/Cursos_Programacion
/Python/Ejercicios/ej-while/ej-14.py
476
4.21875
4
#continuar = input("Desea continuar? [S/N]: ") continuar = "S" while(continuar == "S"): continuar = input("Desea continuar? [S/N]: ") print("Gracias por usar mi sistema :)") ''' con ciclo while pedir al usuario una cantidad númerica a ahorrar y luego que le pregunten a al usuario si desea agregar otra canti...
ff9783b7f1e118bf72d8ee96b1dd858f67689337
chipmunk360/hello_py
/number_guessing_game.py
972
3.78125
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 25 22:29:02 2016 @author: pi """ import random secret = random.randint ( 1, 20) guess = 0 tries = 0 print "AHOY! i'm the Dread Pirate Roberts and I hae a secret!" print " It is a number from 1 to 20. I'll give you 6 tries. " while guess != secret and tries < 6: ...
f88b76619437517a26c8ab5510592227bd4f94a8
chipmunk360/hello_py
/monkey_shakespeare.py
4,087
3.5
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 26 04:05:12 2016 @author: pi """ #=============================================================================== # Pyevolve version of the Infinite Monkey Theorem # See: http://en.wikipedia.org/wiki/Infinite_monkey_theorem # By Jelle Feringa #===========================...
2c12b700e72b2cd155a8dca90a3e2389106eed3f
koenigscode/python-introduction
/content/partials/comprehensions/list_comp_tern.py
311
4.25
4
# if the character is not a blank, add it to the list # if it already is an uppercase character, leave it that way, # otherwise make it one l = [c if c.isupper() else c.upper() for c in "This is some Text" if not c == " "] print(l) # join the list and put "" (nothing) between each item print("".join(l))
d51b6c59a12f740e9c95f675a3d84fa98d608fb9
koenigscode/python-introduction
/content/partials/basic_syntax/string_formatting_examples.py
210
3.609375
4
who = "I" version = 3 print( who + " love Python " + str(version) ) print( "%s love Python %s" % (who, version) ) print( "{} love Python {}".format(who, version) ) print( f"{who} love Python {version}" )
d4cec66953d44684f1c17c6c76eaeb20c6d417ec
samgensburg/adventofcode
/2020/3b.py
742
3.578125
4
import re def main(right, down): with open('3.dat', 'r') as file: y = 0 count = 0 fall = down - 1 for line in file: fall += 1 if fall == down: fall = 0 ...
0cdfc292b376b2666cf02479a3ee6224ef1bd7cc
samgensburg/adventofcode
/2021/02a.py
331
3.53125
4
def main(): with open('02.dat', 'r') as file: x = 0 y = 0 for line in file: parts = line.split() value = int(parts[1]) if parts[0] == 'forward': x += value elif parts[0] == 'down': y += value elif parts[0] == 'up': y -= value else: raise 'how did I get here?' return x * y pri...
22e20f3364f8498766caf17e4dc8b967ef217f5b
BMariscal/MITx-6.00.1x
/MidtermExam/Problem_6.py
815
4.28125
4
# Problem 6 # 15.0/15.0 points (graded) # Implement a function that meets the specifications below. # def deep_reverse(L): # """ assumes L is a list of lists whose elements are ints # Mutates L such that it reverses its elements and also # reverses the order of the int elements in every element of L. #...
383473ada2e5332caee9ab02bd421b024fa1cf50
OrmandyRony/initialPython
/PythonBasico/estructuras.py
1,242
4.0625
4
# -*- coding: utf-8 -*- #Estructuras de control de flujo #Asignación múltiple a, b, c = 'string', 15, True print (a) print (b) print (c) # En una tupla mi_tupla = ('Hello world', 2020) texto, anio = mi_tupla print (texto) print (anio) # En una lista mi_lista = ['Argentina', 'Buenos Aires'] pais, provincia = mi_l...
fd87f0b66dc286e83c64e7500d5d391a7d86677d
OrmandyRony/initialPython
/ExercisePython/degreeConverter.py
349
4.09375
4
""" Escribe un programa que le pida al usuario una temperatura en grados Celsius, la convierta a grados Fahrenheit e imprima por pantalla la temperatura convertida. """ print("Convertidor de grados celcius a fahrenheit") celcius = float(input("Ingrese los grados celcius: ")) fahrenheit = (celcius * 9/5) + 32 print("Gra...
85af22591e1b052ff672eafa626d6b30fd716853
kyj0101/python_coding_test
/codeup/기초100/6064.py
120
3.859375
4
a,b,c = input().split() a = int(a) b = int(b) c = int(c) print(a if a < b and a < c else (b if b < a and b < c else c))
9c7beb4090f3aad39d66c3fe54fd656c374f1af6
kyj0101/python_coding_test
/codeup/기초100/6078.py
82
3.6875
4
char = input() while char != 'q': print(char) char = input() print(char)
73e4c51440c5d6da38f297556843c0173f0153ee
alexhong33/PythonDemo
/PythonDemo/Day01/01print.py
1,140
4.375
4
#book ex1-3 print ('Hello World') print ("Hello Again") print ('I like typing this.') print ('This is fun.') print ('Yay! Printing.') print ("I'd much rather you 'not'.") print ('I "said" do not touch this.') print ('你好!') #print ('#1') # A comment, this is so you can read your program later. # A...
8fe5c8e513e65e92210c9b0cc3cb1ae38c4d6532
yanuar-nc/python-lesson
/oop/vehicle/car.py
642
3.546875
4
from . import Vehicle class Car(Vehicle): brands = { 'BMW': {'price': '$40,000', 'speed': '1000cc'}, 'LAMBO': {'price': '$50,000', 'speed': '1100cc'}, 'CIVIC': {'price': '$60,000', 'speed': '400cc'}, 'FERARI': {'price': '$80,000', 'speed': '2000cc'} } def get_price(self): if self._check_brand(self....
50dfeab0a39678d5713d49e59c86079d2d16faa6
Choewonyeong/FireSafery-Schedule
/method/dateList.py
1,149
3.59375
4
from datetime import datetime from datetime import date from pandas import Timedelta def __returnDate__(year, month, day): weekend = ['(월)', '(화)', '(수)', '(목)', '(금)', '(토)', '(일)'] idx = date(year, month, day).weekday() return weekend[idx] def __returnDayCount__(year, month): if month == 12: ...
e5bf45c4b1461958b53df754af879bd9b7aedef1
johanarangel/variables_python
/ejercicios_practica.py
7,607
4.3125
4
#!/usr/bin/env python ''' Tipos de variables [Python] Ejercicios de práctica --------------------------- Autor: Johana Rangel Version: 1.3 Descripcion: Programa creado para que practiquen los conocimietos adquiridos durante la semana ''' __author__ = "johana Rangel" __email__ = "johanarang@hotmail.com" ...
b0280148b992b2069dc7608da4f84df75ef91dcd
anvartdinovtimurlinux/ADPY-12
/2.7/stack.py
350
3.546875
4
class Stack: def __init__(self): self._storage = [] def is_empty(self): return bool(self._storage) def push(self, item): self._storage.append(item) def pop(self): return self._storage.pop() def peek(self): return self._storage[-1] def size(self): ...