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 |
|---|---|---|---|---|---|---|
840747d89d7f2d84c7b819b5d26aa4ac1ea93254 | felixguerrero12/operationPython | /learnPython/ex15_Reading_Files.py | 739 | 4.25 | 4 | # Felix Guerrero
# Example 15 - Reading Files
# June 28th, 2016
# Import the sys package and import the arguement module
from sys import argv
# The first two command line arguements in the variable will be
# these variables
script, filename = argv
# 1. Open up variable filename
# 2. Give the content of the file to t... |
b80d5d8ad771c06c00a2aaef6e398cae8948f51a | MarkVoitov/grocery_shopping_list | /grocery_shopping_list.py | 915 | 3.984375 | 4 | # here we write function print_shopping_list()
# that select unique product names and add values
def print_shopping_list(dish1, dish2):
data = set(dish1.keys()).union(dish2.keys())
for i in data: # check for two conditions in a loop
amount = 0
if i in dish1.keys():
... |
e759de7216ff2929058152f0169622bf47954db9 | jasper-ckn/games | /tictactoe.py | 4,075 | 3.890625 | 4 | # Tic Tac Toe
theBoard = {
'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' ',
}
player = 1 # To initialise first player
total_moves = 0 # To count the moves
end_check = 0
def check():
# Checking the moves of player one
# Check for every horizon... |
1a40317f937d0483db5d4ae97b82b4b70211b970 | cljacoby/MotorcycleData | /clean.py | 1,034 | 3.78125 | 4 | """
Simple python script to double check database and make sure every row has a
year, make and model
"""
import sqlite3
import os
import sys
def get_bad_rowids(dbconn, table_name):
cursor = dbconn.cursor()
badies = []
query_all = "SELECT rowid, * FROM {}".format(table_name)
for row in cursor.execute(q... |
f470996fc6e31fd4f224dc9b64ae49d60cfd081f | coymeetsworld/advent-of-code-2018 | /day07/sum_of_its_parts_part_two.py | 4,470 | 3.65625 | 4 | #!/usr/bin/python
# Example of step input:
# Step C must be finished before step A can begin
def parse_step(step):
words = step.split()
return words[1], words[7]
def print_timeline(current_second, processing_nodes, completed_nodes):
p_nodes = ''
for node in processing_nodes:
#print p_nodes
... |
b84ed61555994e7807489cf9c0575dbc4fd298f6 | coymeetsworld/advent-of-code-2018 | /day06/chronal_coordinates_part_one.py | 3,336 | 3.703125 | 4 | #!/usr/bin/python
import sys
def print_grid(grid):
print "#######GRID########"
for y in range(len(grid)):
for x in range(len(grid)):
print grid[x][y],
print
print "###################"
print
def find_infinite_locations(grid):
inf_locations = []
for x in range(len(grid)):
... |
f94130e83bda579698bbb0921c8fa43736279ff5 | dgupta777/Python-Scripts | /bin/Lost Robot/Solution.py | 509 | 4.09375 | 4 | #According to question we can only instruct robot up or down or left or right. So in his current coordiantes and home coordinates one of the/
#coordinate either X or Y must be same.
for _ in range(int(input()):
x1,y1,x2,y2=map(int,input().split())#This will parse input to x1,y1,x2 and y2
if x1!=x2 and y1!=y2:
... |
546e63ca99db0a9d32aea7b4111dfbb9885ffb89 | xolar1989/Numeric_algorithm_3 | /program/objects/Matrix.py | 2,032 | 3.734375 | 4 | import math
from copy import deepcopy
class Matrix:
def __init__(self,size_x , size_y,value=0):
self.size_x = size_x
self.size_y = size_y
self.matrix_tab = [[value for x in range(size_x)] for y in range(size_y)]
def __getitem__(self, position):
y,x = position
if y < 0 ... |
35a41935069d1a84cb72cfa34a17f5beb73e5745 | Zaela24/pathfinder | /pf_diagonal_shot_calc.py | 914 | 3.921875 | 4 | # Zaela
#
# Range increment calculator for shooting diagonally in Pathfinder.
# Takes two arguments, length and height, then returns the distance of the shot.
# Rounds down if remainder when divided by 5 is less than 1, otherwise rounds
# up to the nearest 5 foot increment
def diagonal_shot(length, height):
... |
c20c9425be567bf98450b6c341357ca9c6b7fccd | lalitgarg12/tensorflow-repo | /TensorFlow in Practice Specialization/01. Introduction to TensorFlow Coursera/Week1 - A New Programing Paradigm/01HelloWorld.py | 1,285 | 4 | 4 | import numpy as np
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential([keras.layers.Dense(units = 1, input_shape = [1])])
model.compile(optimizer = 'sgd', loss = 'mean_squared_error')
#Equation of a line y = 2x - 1
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([... |
7d0af416a449f00eb65dd5cf35c8883306447451 | lalitgarg12/tensorflow-repo | /Tensorflow 2 for Deep Learning Specialization/02. Customizing your models with Tensorflow 2/Week2 - Data Pipeline/02DatasetGenerator.py | 3,238 | 4.53125 | 5 | # If datasets are bigger, they will not fit into memory
# A generator is function that returns an object that you can iterate over
# and it yields a series of vaalues but doesn't store those values in memory.
# Instead it saves its own internal state and each time we iterate the generator.
# It yields the next value in... |
07a340dbeaaf4bda96ba51770ac8f23a4f062c69 | gregory-h93/BubbleSort | /BubbleSort.py | 998 | 4.09375 | 4 | def bubbleSort(array, arraySize):
for maxElement in range(arraySize - 1, 0 - 1, -1):
for index in range(0, maxElement - 1 + 1, 1):
if array[index] > array[index + 1]:
temp = array[index]
array[index] = array[index + 1]
array[index + 1] = temp... |
451700ee74f47681206b30f81e7c61b80c798f8c | ChiefTripodBear/PythonCourse | /Section7/utils/database.py | 1,803 | 4.1875 | 4 | import sqlite3
"""
Concerned with storing and retrieving books from a list.
Format of the csv file:
[
{
'name': 'Clean Code',
'author': 'Robert',
'read': True
}
]
"""
def create_book_table():
connection = sqlite3.connect('Section7/da... |
625707a1917c8f1e91e3fd9f2ee4a51102f27af5 | golddiamonds/LinkedList | /LinkedList.py | 2,790 | 4.28125 | 4 | ##simple linked list and node class written in python
#create the "Node" structure
class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def getData(self):
return self.data
#create the structure to hold information about the list
#including ... |
b2d5ffca030b0181b0432fe39d860ac6667861c7 | unbreakablelzc/Memorisation | /lstm.py | 17,637 | 3.796875 | 4 | """A Recurrent Neural Network (LSTM) that performs dynamic computation
over sequences with variable length.This example is using a memlog_200_1
and data_200_200_hard dataset to classify sequences.
"""
import tensorflow as tf
import numpy as np
import random
import os
# Parameters
start_learning_rate = 10**-5
tra... |
798570abf5b70b1a73d55aae296a94d2018685ba | chunter-202/Linear-Regression | /main.py | 3,069 | 3.546875 | 4 |
#############################################
# Linear Regression #
# Taylor Chase Hunter #
# #
# This code takes in data from auto-mpg #
# And trains a linear regression model on #
# it. #
##############... |
2eb73df553f36afcce0238724038de953cf176e6 | joaopalet/LEIC-IST | /1st_Year/FP/1st_Project/proj1-86447.py | 4,494 | 3.59375 | 4 | #_____________Disciplina: Fundamentos de Programacao_____________#
#__________________Joao Lopes Palet de Almeida___________________#
#_____________________________86447______________________________#
#1.1 - VERSAO SIMPLIFICADA
#1.1.1
def gera_chave1(letras):
#Funcao que recebe um argumento,... |
73373404a5503ed040a4ab812d0941411cf9f2ad | SergueiNK/p3_help_mcgyver_escape | /maze.py | 2,433 | 3.53125 | 4 | #!/usr/bin/python3.9
# -*-coding:utf-8 -
import constants
import random
class Maze:
"""
class Maze who defined the labyrinth.
Methods: __init__, init_items_coord,
update_list_floors_coord
"""
list_walls_coord = []
list_floors_coord = []
position_guard_coord = ()
position_... |
2561de6ae71bb41a50f8d3a56f81c9583770dbd8 | s1nn105/abiturDerivativesEtcP | /main.py | 824 | 3.9375 | 4 | from sympy import *
from polynomial import *
import sys
import time
init_printing()
polynomial,ad = create_term()
x = Symbol('x')
f= polynomial #everybody likes f(x) instead of polynomial(x)
# first the derivative
print(pretty(f))
print("Whats the derivative ? ")
t1 = time.time()
input("press any key if finished")
t2=t... |
c92d9e636bb8771f42ccf63d91a743e55df0e92b | ankitad87/Python | /mostFrequent.py | 423 | 3.90625 | 4 | n = int(input("Enter the number of elements :\n"))
list1 = []
print("Enter the list elements :")
for i in range(0,n):
ele = int(input())
list1.append(ele)
print(list1)
dict1 = {}
for i in list1:
if i in dict1:
dict1[i] += 1
else:
dict1[i] = 1
max_value = max(dict1.values(... |
34518198d4445856607dd480a3e81e492508bedd | olegborzov/otus_algo_1218 | /hw3/eratosfen.py | 2,131 | 4.15625 | 4 | """
Алгоритм решета Эратосфена с улучшениями:
- Битовые операции - каждый элемент массива представляет собой true/false
для определенного числа. Используя этот алгоритм можно уменьшить потребности
в памяти в 8 раз.
- Откидываются четные числа
- Сегментация - вычисления выполняются блоками определенного размера.
""... |
f522a00ec6511aebe18049ee9be693e17164aebe | jacobcohen76/Interview-Questions | /word_ladder.py | 599 | 3.9375 | 4 | import collections
from typing import Dict, Iterable, Set
def replace_letter(s: str, r: str, i: int) -> str:
return s[:i] + r + s[(i + 1):]
def enumerate_word(word: str, letter: str):
for i in range(len(word)):
yield replace_letter(word, letter, i)
def make_adjacency(words: Iterable[str], letter: st... |
868917548a1e71fccb133f6fd482b8598728833b | jacobcohen76/Interview-Questions | /arrays/two_sum.py | 354 | 3.6875 | 4 | from typing import List, Tuple
def two_sum(nums: List[int], target: int) -> Tuple[int, int]:
found = dict()
for i in range(len(nums)):
complement = target - nums[i]
if complement in found:
return (i, found[complement])
else:
found[nums[i]] = i
return None
pr... |
93298489780f962100fa464b3c8644057cca5acf | emuyuu/design_pattern | /1_creational_design_patterns/builder.py | 2,285 | 3.546875 | 4 | # Builder Pattern
# 同じ引数を使って別の形をしたインスタンスを生成したいときに使用できる。
# 抽象基底クラスを継承するのがポイント。ここで共通で使用されるメソッドを定義する。
# 実際に成形処理を行うそのクラスを継承した具体的なクラス。
# 疑問:
# 抽象基底クラスを継承させなくても動作したのだが、このクラスはなぜ必要?
# 何を想定して用意してある?
# 特徴:
# 組みあがったものに対してしか(html, text)しか編集できない。
import abc
def main():
html = Director().construct(HTMLBuilder())
text = ... |
3d289735bca17f15a1e100fdaa01b4a86b871a25 | emuyuu/design_pattern | /3_behavioral_design_patterns/iterator_pattern.py | 1,704 | 4.59375 | 5 | # iterate = 繰り返す
# Iterator:
# > Anything that is iterable can be iterated,
# > including dictionaries, lists, tuples, strings, streams, generators, and classes
# > for which you implement iterator syntax.
# 引用:http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
# ----------------------------------... |
43053b4f679df7d9222759c5914cdde3904c29a4 | transformandodados/code_interview_training | /europe/freq.py | 354 | 3.578125 | 4 | """
>>> freq('banana')
{'b_com_fatia_linear': 1, 'a_com_fatia_linar': 3, 'n': 2}
>>> freq('aha')
{'a_com_fatia_linar': 2, 'h': 1}
"""
from functools import reduce
def freq(s):
def contar_letra(resultado, letra):
resultado[letra] = resultado.get(letra, 0) + 1
return resultado
r... |
c1ec59195c63af40dc51cc85a6e48549fa537f42 | transformandodados/code_interview_training | /old/dinheiro.py | 436 | 3.953125 | 4 | def conta_vogais(frase):
espaço = " "
vogais = ['a_com_fatia_linar', 'e', 'i', 'o', 'u']
print(f' qtide de espaços vazios: {frase.count(espaço)}')
ordem = sorted(frase)
for i in range(len(ordem)):
if ordem[i] in vogais:
print(f'{ordem[i]}= {frase.count(ordem[i])}')
# program... |
28a6f92ddd324a4b1432d7f1af1e8cb9a58d87af | transformandodados/code_interview_training | /old/imc.py | 958 | 3.609375 | 4 | def calcular_imc(peso, altura):
limites_superiores={
17:"Muito abaixo do peso",
18.5:"Abaixo do peso",
25:"Peso normal",
30:"Acima do peso",
35:"Obesidade I",
40: "Obesidade II (severa)",
}
imc = float(peso / (altura ** 2))
for limite_superior, msg in lim... |
99a214e31f4f1251f04f6f66fb4c96ef57049873 | crashley1992/Alarm-Clock | /alarm.py | 2,189 | 4.28125 | 4 | import time
from datetime import datetime
import winsound
# gets current time
result = time.localtime()
# setting varable for hour, minute, seconds so it can be added to user input
current_hour = result.tm_hour
current_min = result.tm_min
current_sec = result.tm_sec
# test to make sure format is correct
print(f'{cur... |
ef4d8edb8bb9fde25f34bd82a72635cce4bff1ac | Sherm46290/pythonFun | /game.py | 2,967 | 3.921875 | 4 | # Name: Richard Sherman
# Date: 7/22/19
# Filename: game.py
# Description: Rock, Paper, Scissors, Lizard, Spock game
import random
# welcome and name input
print("Welcome to the Rock-Paper-Scissors-Lizard-Spock Game")
name = input("Please enter your name: ")
name = name.title()
# game rules
print("W... |
0b48c3a83f7a6ea2b1ec50acf999e4b75b771aad | shubham-gaikwad/Competitive-Coding-5 | /cc-5.py | 3,382 | 4.09375 | 4 | # problem 1 : 36. Valid Sudoku : https://leetcode.com/problems/valid-sudoku/
# Time Complexity : O(1) Making 3 loops : one for row, column, and squares. each of it visits all 81 locations
# Space Complexity : O(1) maintaining a list of size = 9
# Did this code successfully run on Leetcode : Yes
# Any problem you faced ... |
23983cbb84f1b375a5c668fb0cb9f75aef9a67e9 | steve-thousand/advent_of_code_2018 | /5.py | 1,076 | 4.125 | 4 | input = "OoibdgGDEesYySsSMmlLIKkkVvKvViERxXVvrfmMsSFeaAvnNVdMmJjDBmMXbBJjWwPZzpHhLlCsSfFpPcKVvxlLXbBkxUIJjfFoOigEeGHhdDJjdDAazTtrRCotTFfOoOcZPDejJEdpTzsSYzZMmyMmZtshHJzZkKYyJjnAaNjpflLFPUuNndnPpNxAiIMbBCcgLlGPrRpmaHnNhXDoOzZxXUdjJWwilLIDutWwTjwMmWcCJvVxXthHfFkKdDWwmMHjbBKkRrXxlLJhOoTYytKZzrGvVgabbBBjJpPAKMmsSktwWfFTWoO... |
60f5c28a69a776bd15e4b121e8823f3840cfab92 | amirkhan1092/machine_learning | /personalAssistant/assistant_python.py | 1,865 | 3.578125 | 4 | # importing speech recognition package from google api
import speech_recognition as sr
import playsound # to play saved mp3 file
from gtts import gTTS # google text to speech
import os # to save/open files
import wolframalpha # to calculate strings into formula
from selenium import webdriver # to control browser o... |
cf823ebcf1c564bef2ed6103588b2ff8ed1e86da | donrax/point-manipulation | /point_side_line.py | 623 | 4.34375 | 4 | import numpy as np
def point_side_line(p1, p2, p):
"""
Computes on which side of the line the point lies.
:param p1: [numpy ndarray] start of line segment
:param p2: [numpy ndarray] end of line segment
:param p: [numpy ndarray] point
:return: 1 = LEFT side, 0 = ON the line, -1 = RIGHT side
... |
84d6ee056bb099be066eaad41b5db90c95fa5936 | tomasroy2015/pythoncrash-study | /fibonacci.py | 297 | 4.25 | 4 | def fibonacci(n):
if(n <= 1):
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
nterms = int(input("How many terms? "))
if(nterms < 0):
print("Enter valid input")
else:
print("Print fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i))
|
206a2ed470dbbbe357a0293e3c7fe33e779adc48 | manu-s-s/openai | /Untitled-1.py | 82 | 3.515625 | 4 | k='3\n\n4\n\n\n5'
k=k.split('\n')
k[:] = [item for item in k if item!='']
print(k) |
afe4410847eaff437f357401cd9bdba6e34f18f1 | bitmakerlabs/python_to_javascript_autopilot | /autopilot.py | 1,976 | 3.796875 | 4 | def get_new_car():
return {
'city': 'Toronto',
'passengers': 0,
'gas': 100,
}
def add_car(cars, new_car):
cars.append(new_car)
return "Adding new car to fleet. Fleet size is now {}.".format(len(cars))
def pick_up_passenger(car):
car['passengers'] += 1
car['gas'] -= 10
return "Picked up passe... |
eb68be7eed7ee41eadf2cd56fd635eab443d6056 | jpauloqueiroz/Machine_Learning_Python | /source/Linear_Regression/Linear_Regression_Hard/ml8.py | 384 | 3.890625 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slope(xs, ys):
numerator = (np.mean(xs)*np.mean(ys)) - np.mean(xs*ys)
denominator = np.mean(xs)**2 - np.mean(xs**2)
ret... |
8109b6cc23f445a36a20ede14643f25d483236bd | g-d-l/project_euler | /done/188.py | 421 | 3.734375 | 4 | import sys
def recurse(powers, base, power):
if power == 1:
return base
else:
exp = recurse(powers, base, power - 1)
exp %= len(powers)
return powers[exp]
powers = [1]
start = 1777
base = 1777
power = 1855
mod = int(10 ** 8)
while base != powers[0]:
powers.append(base)
... |
de1e3edfb7d043ea3a56c1f3944970d061eb6bfd | g-d-l/project_euler | /in_progress/138.py | 2,107 | 3.96875 | 4 | from fractions import Fraction
import math
def is_square(n):
root = int(math.sqrt(n))
if root * root == n:
return True
else:
return False
def continued_fraction(n):
series = []
m = 0
d = 1
a = int(math.sqrt(n))
series.append(a)
while a != 2 * series[0]:
m = ... |
a93e4dad7f911afb201bc96b591abd7aeb2282c9 | g-d-l/project_euler | /done/080.py | 368 | 3.53125 | 4 | from decimal import *
getcontext().prec = 102
current = str(Decimal(2).sqrt())
squares = [x ** 2 for x in xrange(1,11)]
irrationals = [x for x in xrange(1,101) if x not in squares]
result = 0
for i in irrationals:
current = str(Decimal(i).sqrt())
result += int(current[0])
for index in xrange(2, 101):
... |
6be14d54e99636b9b984d16b67bc2d93b83a1b7b | HongDaeYong/codingStudy | /DaeYong/4Sort/sortProb2_.py | 351 | 4 | 4 | """
한개 틀림
"""
def solution(numbers):
answer = ''
numbers.sort(key=lambda x: str(x) * 3, reverse=True)
for n in numbers:
answer += str(n)
return answer
numbers1 = [6, 10, 2]
numbers2 = [3, 30, 34, 5, 9]
numbers3 = [3, 33, 300, 330, 333]
print(solution(numbers1))
print(solution(numbers2))
prin... |
123d56c53b033ebf467442213572c962ea18b22d | HongDaeYong/codingStudy | /ayun/1_hash/2_전화번호목록.py | 260 | 3.625 | 4 | from collections import Counter
def solution(phone_book):
answer = True
for i in phone_book:
num=0
for j in phone_book:
if i==j[0:len(i)]:
num=num+1
if num>=2:
return False
return True |
e8d0d65f683f38f64f8d23d0f580bef843815544 | HongDaeYong/codingStudy | /haegu/Brute-Force Search/bfsearch_3.py | 1,100 | 3.59375 | 4 | # [완전탐색] 숫자야구
#ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ
def solution(baseball):
answer = 0
for i in range(123, 988):
check = 0
a = i // 100
b = (i % 100) // 10
c = i % 10
if a == b or b == c or c == a:
continue
elif b == 0 or c == 0:
continue
for j... |
694407aba53f5e34c599eeabf0db651f385eac89 | HongDaeYong/codingStudy | /haegu/2018_Kakao_Blind/01_OpenChatting.py | 440 | 3.71875 | 4 | # 오픈채팅방
def solution(record):
answer = []
enter = "님이 들어왔습니다."
out = "님이 나갔습니다."
dic={}
for i in record:
if i.split()[0]!="Leave":
dic[i.split()[1]]=i.split()[2]
for i in record:
r = i.split()
if r[0]=="Enter":
answer.append(dic[r[1]]+enter)
... |
c02347502196ce328044701cc5db71db765cdeb3 | HongDaeYong/codingStudy | /DaeYong/5brute-forceSeearch/BFSProb2.py | 672 | 3.828125 | 4 | import itertools
def isPrime(num):
if num == 1 or num == 0:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def solution(numbers):
answer = 0
numNum = len(numbers)
numbers = list(numbers)
allPermut=[]
for i in range(1, numNu... |
fc9014d00f028df4982ef100f92acb34ee72c623 | chingismaksimov/smart_rockets | /particle_module.py | 1,469 | 3.640625 | 4 | import vectors_module
import math
import numpy as np
class Particle:
def __init__(self):
self.position = None
self.velocity = None
self.mass = 1
def move(self):
self.position.addTo(self.velocity)
def accelerate(self, acceleration):
# where acceleration is a vecto... |
3df404a69c20ac429f5485d0f91cd44bd9b96396 | giuseppedipasquale/srm-designer | /src/srm/chamber.py | 907 | 3.625 | 4 | from numpy import pi
class Chamber:
"""
Class to represent a solid rocket motor chamber.
"""
def __init__(self, D, L, MEOP):
"""
Constructor
:param D: Diameter of chamber [mm]
:param L: Length of chamber [mm]
:param MEOP: Maximum expected operating pressure [MP... |
344526eae7c5dbd587492e02bd0cb9b67c873673 | Amit-Patel/Virtual-Shopping-Mall | /main.py | 152,655 | 3.671875 | 4 |
import pygame
import math,decimal
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
PURPLE = ( 255, 0, 255)
WANT = ( 250, 20, 20)
GOLD = ( 255, 165, 0)
SKY = ( 0, 153, 153)
GREY = ( 135, 135, 135)
global... |
0bc5e164f4a3a6eabf32afd9dc99c343aca64af2 | mgalindo077/Python_Graficos | /practical_label.pyw | 372 | 3.640625 | 4 | from tkinter import *
root=Tk()
miFrame=Frame(root, width=500, height=400)
miFrame.pack()
miImagen=PhotoImage(file="mouse.gif")
Label(miFrame, image=miImagen).place(x=50, y=50)
miLabel = Label(miFrame, text="Esta es una prueba")
miLabel.place(x=100, y=200)
Label(miFrame, text="Otra manera sin declaracion", fg="bl... |
a0b0b4c5c549c61d8d7897c0e868a7acbf1afd25 | Ahsanhabib1080/CodeForces | /problems/B/HonestCoach.py | 792 | 3.59375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1360/B
Solution: Sort the numbers in strength list so that the neighbors are the numerically closest numbers. Now we need
to find the smallest difference of neighbors. One of that pair would be list A's max and other would be list B's min.
''... |
f715957386fc80195edc05ef526bdf38b39c2c88 | Ahsanhabib1080/CodeForces | /problems/A/MinimalSquare.py | 1,328 | 3.734375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1360/A
Solution: The rectangles need to be touching each other inorder to use the minimum space. Now the question arises if
they would touch along the height or the width.
If they touch along the height, then the side of the square should be... |
ebed36a80201b9fc32a33f9f37f8abbe1f3cf982 | Ahsanhabib1080/CodeForces | /problems/B/LovelyPalindromes.py | 749 | 3.875 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/688/B
Solution: If we observe the first few palindromes of even length, for the first 9 palindromes,
we get 11 to 99. After that, we go to 1001 and then put these 11 to 99 between two 1s. This results in
palindromes 1111, 1221, 1331 to 1991. I... |
af400568471789ccd79f049d805e364257da5b24 | Ahsanhabib1080/CodeForces | /problems/A/MaximumGCD.py | 703 | 4 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1370/A
Solution: GCD gives the biggest divisor for the given numbers. For a given number, we can go till its half to get the
biggest factor. Therefore, if n is even, n/2 should give the other number which would be the GCD. Otherwise whe n is ... |
5b772eab87467a98e4c38b620b8a9b1490a4b59a | Ahsanhabib1080/CodeForces | /problems/A/PatrickAndShopping.py | 822 | 3.921875 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/599/A
Solution: The roads Basically there are 3 alternatives of traveling.
Option 1: Use the road d1 to go to shop 1, return via it, use d2 to go to shop 2 and return via it to home.
Option 2: Use the road d1 to go to shop 1, go to shop 2 vi... |
5337ee3e297eab0da301f1f2753e31e75df0b697 | Ahsanhabib1080/CodeForces | /problems/B/Barrels.py | 1,034 | 3.5 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1430/B
Solution: Since we want to pour from the most filled barrels so that difference is higher, we firstly
sort the barrels in decreasing order. Then we add together the first k elements to get the joint content
of poured in barrels. Since t... |
b98ba75d4e58c7d84785a11ae74b752423461491 | Ahsanhabib1080/CodeForces | /problems/A/OmkarAndPassword.py | 835 | 3.859375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1392/A
Solution: If there exist at least 2 different numbers in the array, it can always be reduced to 1 since addition of those
distinct numbers can result in another distinct number thereby reducing the array to 1 element. Only if there is o... |
64a4649939197d1f465def768d988197e80746c6 | Ahsanhabib1080/CodeForces | /problems/A/Pangram.py | 614 | 3.796875 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/520/A
Solution: Maintain a set of characters seen in the string. In the end, the size of that set should be 26 denoting all
characters were observed at least once in the string. Make sure we add characters in one case in the set to deal with
u... |
e99c926b167010aea5ef2ccf0b5f37a1bdde23a8 | Ahsanhabib1080/CodeForces | /problems/B/CollectingPackages.py | 2,293 | 3.9375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1294/B
Solution: At the sight of this question, it may appear that we need to perform DFS while maintaining the different paths
and finally returning the lexicographically smallest one. But we don't need to actually simulate the DFS.
Since ... |
2241d4c8167900bf10bc10aa7b99094357095a51 | Ahsanhabib1080/CodeForces | /problems/A/DivideIt.py | 1,081 | 3.84375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1176/A
Solution: When n is divisible by 2, we do one operation of n/2. When it is divisible by 3, even though we do one operation
of 2n/3, the 2 multiplied in the numerator will cause one operation of n/2. Hence it amounts to two operations. S... |
9f7a8ee2fabc2634c59797f734d0320e1a77c5f2 | Ahsanhabib1080/CodeForces | /problems/C/TwoBrackets.py | 1,343 | 3.828125 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1452/C
Solution: Its easy to see that to form a RBS, we need to already have seen an opening bracket
before we see the closing bracket of the same kind. If that happens, we have a valid pair and
hence a RBS which can be eliminated. Therefore, ... |
b1c92dbbdc0862e42b34429106dd17edc0801b8d | Ahsanhabib1080/CodeForces | /problems/A/FoxAndSnake.py | 903 | 3.5625 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/510/A
Solution: The rows have pattern for even and odd indexed ones. For the former, it has all cells with snake body,
while the later as alternating empty cells with right/left aligned snake body. Keep track of that with a boolean flag.
''... |
8d2c22ce705780d70c3d9eea840761412f79377f | Ahsanhabib1080/CodeForces | /problems/B/RestoreThePermutationByMerger.py | 736 | 3.625 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1385/B
Solution: The question boils down to have a linked hash set of the given array. That would preserve unique elements in
the order of their occurrences in the original array. We use OrderedDict for that here.
'''
from collections import... |
7ebc8b6850e8f520eeb025ff65bd51cb2e9f977b | Ahsanhabib1080/CodeForces | /problems/A/TelephoneNumber.py | 707 | 3.65625 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1167/A
Solution: From the first occurrence of 8 in the given string s, we should have at least 10 characters. Say that 8 exists
on ith index. Then n - 1 - i + 1 = n - i would give the length of the longest string starting with 8. That should b... |
46ff79c35f125bfddae9218b63c085d851d58a75 | Ahsanhabib1080/CodeForces | /problems/A/Twins.py | 817 | 3.671875 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/160/A
Solution: Find the total of all coins so that we know the half of the total value which you need to exceed. Now sort the
coins in reverse order and iterate over them. In each round, add the coin to your total and break the iteration if y... |
8b0be9058750d107d3b0a0e7fca11c49b310b55e | Ahsanhabib1080/CodeForces | /problems/A/Elephant.py | 666 | 3.734375 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/617/A
Solution: Keep the possible steps in decreasing order so that when we use them, we always try to use the larger step
first, thereby minimizing the steps needed. Now iterate till n is positive and use the possible steps to decrement n.
R... |
e562b59876199bf03b6aa533afe98f5f8d385fd5 | Meethlaksh/Python | /again.py | 1,899 | 4.1875 | 4 | #Write a python function to find the max of three numbers.
def m1(l):
d = max(l)
return d
l = [1,2,3,4,5]
print(m1(l))
#Write a python function to sum up all the items in a list
def s1(s):
e = sum(s)
return e
s = [1,2,3,4,5]
print(s1(s))
#multiply all the items in a list
import math
def mul1(x):
... |
baff5161fd319ce26fd9d5de0e68078885b9983e | Meethlaksh/Python | /studentclass.py | 985 | 4.125 | 4 | """Create a Student class and initialize it with name and roll number. Make methods to :
1. Display - It should display all informations of the student.
2. setAge - It should assign age to student
3. setMarks - It should assign marks to the student.
"""
"""
keywords:
parameter
methods
difference between functions and m... |
df843a63562ca88ce5a486507bdc72deb2b2f9b0 | starstarstarstars/children | /app1/hello.py | 503 | 3.875 | 4 | print("Hello World!")
A = 5+ 30*20
print(A)
fred = "why do grillas have big nostrils? Big Fingers!!"
print(fred)
fred = 'why do grillas have big nostrils? Big Fingers!!'
print(fred)
fred = '''How do dinosaurs pay their bills?
with tyrannosaurus!'''
print(fred)
silly_string = '''He said,"Aren't can't shouldn't wouldn't.... |
685393468f20a5931f9d246df25a987615e2b197 | pstetz/Games | /minesweeper/minesweeper.py | 3,492 | 3.640625 | 4 | import random
class Grid:
def __init__(self, row_size, col_size, num_bombs):
self.row_size = row_size
self.col_size = col_size
self.num_bombs = num_bombs
self.grid = [[ 0 for _ in range(col_size)] for _ in range(row_size)]
self.user_grid = [["-" for _ in range(co... |
4c9b5516dd65d451d858bc0a180ac32cbeda7c2d | aadit-meenege123/ACM-Research-Coding-Challenge | /DetermineOptimalClusters.py | 1,481 | 3.5625 | 4 | """
@author Aadit Meenege
@date 9/7/20
"""
# clustering dataset
# determine k using elbow method
import pandas as pd
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
import numpy as np
import matplotlib.pyplot as plt
#Read in data
# Please input your source file or change the... |
01a09bdf0985601e4e1064f94e9cbf0604b694f9 | joelhogg/pi_webserver1 | /coursework/Attendence_Register.py | 3,241 | 3.90625 | 4 | from tkinter import *
import sqlite3
#note there is a seperate py program to input into db table
class Table(Frame): #height=no. of columns width=rows[database function must be first ran]
def __init__(self,master,height,bigarray):
#width += 1 #have to use up one row for Subtitles
width = (le... |
9d786230cd6bb865b934b9eaa2ffd409c4b61110 | sooftware/Side-Projects | /C-Programming/4 week/6-2.py | 101 | 3.828125 | 4 | m,f=eval(input("Enter the mass in kg and the force in N:"))
a=f/m
print("The acceleration is ", a)
|
bca16ccf225b8f1bfb6b455ad0ef1d845d134d0e | FelixZFB/Python_interview_199_questions | /01_基础语法/5.2.2.sorted排序规则_传入多个规则_先小写然后大写再奇数再偶数.py | 1,272 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# project_xxx\venv\Scripts python
'''
Author: Felix
Email: xiashubai@gmail.com
Blog: https://blog.csdn.net/u011318077
Date: 2019/12/1 16:42
Desc:
'''
# 先看一下Boolean value 的排序:
# Boolean 的排序会将 False 排在前,True排在后
print(sorted([True,False]))
s = 'abC234568XYZdsf23'
# 排序规则:小写<大写<奇数<偶数
# 原理:先比较元组的第一个... |
5aa489c9e0a0703f54ff65bcba8758e152fff754 | ecogit-stage/udsnd_project-4 | /wrangling_scripts/clean_plot.py | 2,352 | 3.65625 | 4 | #import relevant libraries
import requests
import plotly.graph_objs as go
from collections import defaultdict
def clean_plot(graph_name, layout_name, url_string, format, per_page, mrv, title, x_label, y_label):
"""
Cleans and plots graphs from API data of World Bank with Plotly
Args:
- url... |
081eace4efc17f26488c5fd93c35466a6c1dd983 | burkhanShyngys/seminar2 | /myclass.py | 337 | 3.796875 | 4 | class Calculator:
def __init__(self, x, y, c):
self.x=x
self.y=y
self.c=c
def print_ans(self):
if self.y=='+':
print(self.x+self.c)
elif self.y=='-':
print(self.x-self.c)
elif self.y=='*':
print(self.x*self.c)
elif self.y=='/':
print(self.x/self.c)
def defaultVal(self):
self.x=5
self.... |
9a7b88faf1898e1787b4458c5976b4b57982e020 | bikescholl/macaddr | /scripts/mac_addr_lookup.py | 2,221 | 3.78125 | 4 | """
Command line Tool for looking up MAC Address information from macaddress.io
Parameters:
mac_address (str): Mac Address to be looked up against macaddress.io
"""
import json
import argparse
import os
import yaml
import requests
def get_mac_addr(userkey, mac):
"""
Function to get the Mac Address Info reques... |
64dfffacc21e4da4d988002514fd62aab742d282 | SophieTaminh/42_piscine-python-django_D02 | /ex02/beverages.py | 1,849 | 3.890625 | 4 | class HotBeverage:
def __init__(self,name="hot beverage",price=0.3 ,description="Just some hot water in a cup."):
self.price = price
self.name = name
self.description = description
#retourne une description de l'instance
def description(description):
return(description)
... |
bb824a3b11e0886df60e76646def3a525c77221b | jahedul29/Uva-Solutions | /uva136 - Ugly Numbers.py | 243 | 4.0625 | 4 | value = 2
counter = 1
while True:
if value%2 ==0 or value%3 == 0 or value%5 ==0:
counter += 1
print(value)
if counter == 1500:
print(f"The 1500'th ugly number is <{value}>")
break
value += 1 |
7af94610bc728cafab3be81dad9f1db1508ca142 | PsyTian/99-Problems-in-Python | /p6.py | 476 | 4.09375 | 4 | # FIind out whether alist is a palindromo.
# 判断一个列表是不是混问的。
def my_list_reverse(alist):
clist = alist[:]
blist = []
for each in alist:
blist.insert(0, each)
if clist == blist[:]:
print ("这个列表是回文。")
else:
print ("这个列表不清真。")
return blist #不return就是none,所以应该return点什么好呢。
# test
print(my_l... |
381f2eecb307f74e1139d2006c789ab3ec5bec29 | j611062000/ACM-Problems | /Related Problems/Largest Num after Removing Some Digits.py | 476 | 3.765625 | 4 | def removing_m_digits(m, d):
stack = []
for count, digit in enumerate(d):
isEnoughDigits = len(stack) + m + 1 > count + 1
isDigitGreatEnough = (digit > stack[-1]) if stack else True
while stack and isEnoughDigits and isDigitGreatEnough:
stack.pop()
if len(stack) < ... |
c96e3a4fe1b869250706b0118fb8021a4681f99d | LinusZetterman/Pygame | /FailedSnake/Resizing.py | 1,643 | 3.640625 | 4 | #videon jag utgick från https://www.youtube.com/watch?v=i6xMBig-pP4
import pygame
def gameSetup(): #creates the game window
pygame.init()
global win
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Test")
def fillScreen():
for y in range(1000):
for x in range(1... |
c5d9c1845a957bbfe9b042b88418816a9a43ce96 | tazeenm/NLP-Basics | /stemming_POSTagging_4.py | 715 | 3.546875 | 4 | '''
Stemming: same meaning words treated as 1 word. Reduce words to their stem words.
Part of Speech Tagging: Tag words based on whether it is a noun, verb, adjective, etc.
'''
import nltk
from nltk.tokenize import word_tokenize
#Stemmer used: Lancaster Stemmer
text = "Mary closed on closing night when she was... |
bc885627cd33d575e6fde8164772007366d9abbb | SavinEA/GB_hw | /python/hw_7/hw_7_3.py | 1,706 | 3.84375 | 4 | class OrganicCell:
def __init__(self, cell):
self.cell = cell
def __add__(self, other):
add_cell = self.cell + other.cell
return OrganicCell(add_cell)
def __sub__(self, other):
sub_cell = self.cell - other.cell
if sub_cell > 0:
return OrganicCell(sub_ce... |
4ade79012e22b0cd85c624a76f76e729b8840f12 | ande3674/python_old_maid | /oldmaid.py | 3,755 | 3.96875 | 4 | import oldmaid_deck
import computer_hand
import player_hand
import random
### Old Maid game
# The deck can be anything as long as every "card" has a match and there is one
# single Old Maid card
# The deck can be set up in deck_items.txt
# List two of each "card" and one "OLD MAID"
def main():
### HERE IS THE GA... |
bbf72269bee6e8edcef59ca6368744232822d971 | Murphydbuffalo/smile-o-meter | /neural_net/tests/test_cost.py | 3,284 | 3.515625 | 4 | import unittest
import numpy as np
from lib.cost import Cost
class TestCost(unittest.TestCase):
def setUp(self):
# A 1 in a particular row indicates the example belongs to the class
# with the index of that row. Eg given the labels below there are 3
# classes: 0, 1, and 2, and a single exa... |
51620a854494e9c94f09c0ffc92593f54f945276 | pwr-kstasinski/Z03-24g | /Lab 4/Solutions/zadanie11.py | 4,089 | 3.5625 | 4 | import math as dupa
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.value = data
tree = Node("")
OPERATORS = set(['+','-','*','/','(',')','^', 'mod','!','sqrt','log','abs'])
PRIORITY = {'+': 1, '-': 1, '*': 2, '/': 2,'^':3,'mod':2, 'sqrt': 4, 'abs': 4, 'log': 4,}
ON... |
ec3fbb868bcb96760065044649375b3694dc0bbc | Annarien/Tutorial2 | /Problem5.py | 2,922 | 3.53125 | 4 | #Problem 5: Complete the complex class definition to support -,*, and / ( sub , mul , and div ).
# Recall that a/b = a*conj(b)/(b*conj(b)).
# Show from a few sample cases that your functions work. (10)
import numpy
from numpy.fft import fft,ifft
from matplotlib import pyplot as plt
#create a class and in it put def... |
95dca42017cc2f13117686a6fe9b0a3046215562 | Arup/jobSearchBot | /databaseInsert.py | 924 | 3.71875 | 4 | #!/usr/bin/python
import sqlite3
def insert(diceId,positionId,jobtitle,location,companyName,postedDate,jobDescription,
postedBy,phoneNumber,email,contactText,posting_searched_date,isEmailSent):
conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM
cursor = conn.cursor()
print ("before i... |
814253dd2b24163e0b6a58b03ec49f96c4de189e | chaowarat/zumo-game | /tests/test_board.py | 16,258 | 3.578125 | 4 | import sys, random
from board import Board
from unittest import TestCase
from start_project import *
app = QApplication([])
class test_board(TestCase):
def test_roll_dice(self):
# Act
tmp = Board.random_position()
# Assert
self.assertTrue(tmp <= 3)
self.assertTrue(... |
56c2b50b1ad94eaf5a788b299e06dc02e97d0d6f | PermutaTriangle/PermStruct | /permstruct/permutation_sets/point_permutation_set.py | 898 | 3.6875 | 4 | from permuta import Permutation
from .permutation_set import PermutationSet
class PointPermutationSet(PermutationSet):
"""A permutation set containing only the single permutation of length 1."""
def __init__(self):
super(PointPermutationSet, self).__init__(description='point permutation set')
# W... |
7c24c6ea6e36cf073cd5f033ba1fe28d9b1ab706 | Moro-Afriyie/10-Days-Of-Statistics-Hackerrank | /10 Days of Statistics/Interquartile range.py | 547 | 4.09375 | 4 | '''
The interquartile range of an array is the difference between its first and third quartiles
'''
from statistics import median
n = int(input())
X = list(map(int, input().split()))
f = list(map(int, input().split()))
s = sorted([a for a, b in zip(X, f) for i in range(b)])
mid = len(s) // 2
if len(s) % 2 ==... |
e69b13c60ce749759fb0ef7b6db8a0fc610fc1c3 | Moro-Afriyie/10-Days-Of-Statistics-Hackerrank | /10 Days of Statistics/Poisson Distribution II.py | 291 | 3.6875 | 4 | # X^2 can be replaced by X + X^2 using the variance formula E[X^2] = X + X^2
meanA, meanB = list(map(float, input().split()))
Daily_cost_A = 160 + 40*(meanA + meanA**2)
Daily_cost_B = 128 + 40*(meanB + meanB**2)
print('{:.3f}'.format(Daily_cost_A))
print('{:.3f}'.format(Daily_cost_B)) |
171674547b89aecf719035c0f2a8cd2d6bdffead | ChrisTong1018/SlimeFunCalculator | /utils.py | 834 | 3.703125 | 4 | import math
def add(a, b, c):
if b in a.keys():
a[b] += c
else:
a[b] = c
def calculate(table, needs, exist):
loop = False
nextNeed = {}
# 遍历所有需要的
for key, value in needs.items():
# 如果表中有需要的
if key in table.keys():
if key in exist:
... |
d0c533d673968ef61526d8f6f6f01b3983e2cb0b | roque-brito/ICC-USP-Coursera | /icc_pt1/exe_extras/baskara0.py | 625 | 4 | 4 | import math
# ----------------------------------------
a = float(input('Digite o valor de a: '))
b = float(input('Digite o valor de b: '))
c = float(input('Digite o valor de c: '))
print('-'*40)
delta = (b ** 2) - (4 * a * c)
print('Delta = ', delta)
if (delta == 0):
r1 = (-b + math.sqrt(delta)) / (2 * ... |
b99f528a1d34ae4fc2f6efbd351b17bdd6234172 | roque-brito/ICC-USP-Coursera | /icc_pt1/ListExe-5/ex01_retangulos1.py | 293 | 3.921875 | 4 | # Imprime um retângulo:
# -------------------------
largura = int(input('Digite a largura: '))
altura = int(input('Digite a altura: '))
k = 0
while (k < altura):
k += 1
i = 0
while ( i < largura):
i += 1
print('#', end='')
print("")
|
7b495a1ce19ae0917e99c88c8aa06efa016d9454 | roque-brito/ICC-USP-Coursera | /icc_pt1/ListExe-5/ex02_retangulo2.py | 372 | 3.921875 | 4 | # Imprime um retângulo VAZIO:
# -------------------------
largura = int(input('Digite a largura: '))
altura = int(input('Digite a altura: '))
k = 0
print('#'*(largura))
while (k < altura-2):
k += 1
i = 0
print('#', end='')
while (i < largura-2):
print(' ', end='')
i +... |
1277529173bdfd744ca72e7a3459616a01b28e9f | roque-brito/ICC-USP-Coursera | /icc_pt2/week3/matrizes/exercicio_multiplica_matriz.py | 1,605 | 3.75 | 4 | import matriz
def produto_matriz(A, B):
num_linhas = len(A) # número de linhas da matriz A
num_colunas = len(B[0]) # número de colunas da matriz B
assert num_linhas == num_colunas # devolve erro se a condição não for verdadeira
# Criando uma matriz com num_linhas(A) = num_colunas(B):
C =... |
d20c3b7e09d7a003f03bbd45ab38f9ac06aa9ff5 | roque-brito/ICC-USP-Coursera | /icc_pt2/week1/cria_matriz_aula/cria_matriz_elemento_unico.py | 847 | 4.25 | 4 | def cria_matriz(num_linhas, num_colunas, valor):
'''
(int, int, valor) -> matriz(lista de listas)
Cria e retorna uma matriz com num_linhas linhas e num_colunas
colunas em que cada elemento é igual ao valor dado (valores iguais)
'''
# Criar uma lista vazia:
matriz = []
for i in... |
c8e87112f5906f4b228b83ad4f018d0290a7571d | roque-brito/ICC-USP-Coursera | /icc_pt2/week2/imprime_tabela_ASCCII.py | 539 | 4.09375 | 4 | '''
No ASCII (American Standard Code for Information Interchange),
cada caractere é representado usando apenas 7 bits, sendo que os c
aracteres de 0 a 31 são considerados de controle, e os de 32 a 127
correspondem aos caracteres comuns de um teclado de computador em inglês.
Execute o seguinte programa para ver os carac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.