blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0839ad64aebafea6ced255fec5696425f36fd724 | rambahub/catchphraze | /YT downloader.py | 1,467 | 3.953125 | 4 | """
This is a tool to download the highest resolution stream from a youtube URL the user pastes into the blank field.
"""
#import Libraries tkinter for the GUI and pytube for the youtube download funtionality
import tkinter
from pytube import YouTube
#create the parameters of the popup interface that the user then can... |
0f3a9d445d08f5f4dbe0c38228bff9591c7d0a18 | Lana-Pa/Codility | /reverse_array.py | 180 | 3.78125 | 4 | #hhh
def reverse_array(ar):
l = len(ar)
for i in xrange(l//2):
k = l-1-i
ar[i], ar[k] = ar[k], ar[i]
print ar
ar = [1,2,3,4,5,6,7,8]
reverse_array(ar) |
0d0595795e5ed79dcc9ab3c7a29e5a2fd8f9ce39 | SNstudentJulia/SNWD201706 | /11.2 Vehicle Manager/VehicleManager.py | 4,466 | 4.09375 | 4 | class Vehicle(object):
def __init__(self, brand, model, kilometers, service_date):
self.brand = brand
self.model = model
self.kilometers = kilometers
self.service_date = service_date
def add_new_kilometers(self, new_kilometers):
self.kilometers += new_kilometers
def... |
ab636a185ec1a7d485495df45fa190e03480fb19 | AnikHawk/AI-Lab | /Pacman/search/demooooooooo.py | 1,403 | 3.734375 | 4 |
import util
def graphSearch(problem, frontier):
explored = []
frontier.push([(problem.getStartState(), "Stop", 0)])
while not frontier.isEmpty():
# print "frontier: ", frontier.heap
path = frontier.pop()
# print "path len: ", len(path)
# print "path: ", path... |
0702cc32a63d02f83a8ff80bbccb66553af7ca24 | missreya/time-calculator | /src/time_calculator.py | 2,604 | 4.03125 | 4 | def add_time(start, duration, date=False):
#### -------------------- Hours / Minutes / AM PM Calculations -------------------- ####
(clock_start, am_pm_start) = start.split(" ") #(3:00 PM) becomes ("3:00", "PM")
(hour_start, minute_start) = clock_start.split(":") #("3:00") becomes (3, 00)
(hour_durat... |
d2c3467bc7935d43467dec88f31d8cd7ddf6493b | toha0730/ll-parser | /parser.py | 8,275 | 3.796875 | 4 | import sys
import grammar
class LL:
def __init__(self, parse_input, rec_mode, grammar):
# Add '$' add the end of the parse input to be able to parse using the parser
self.parse_input = parse_input + '$'
self.rec_mode = rec_mode
self.terminals = grammar.terminals(grammar)
sel... |
d0d29f695f792edb7032a1e254d5000cd9edb1c9 | BestDerpy/dice-roller | /dice-roller.py | 676 | 3.9375 | 4 | def diceroll(dice):
import re
import random
m = 0
n = 0
result = 0
if bool(re.match(r"^[1-9]?\d[dD]([1-9]?\d|100)?$", dice)) and not bool(re.match(r"^\d+[dD]1$", dice)):
cast = re.split("[dD]", dice)
m = int(cast[0])
n = int(cast[1])
else:
print("Your dum")
while m > 0 and n > 0:
... |
47df823afcfa8678e98f6fc960070ac7bfaf84e9 | dylanPMurphy/algo_expert | /python/BST/BST_Construction.py | 1,847 | 3.875 | 4 | class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
runner = self
while runner is not None:
if value < runner.value:
if runner.left == None:
runner.left = BST(value)
return self
else:
runner = runner.left
else:
... |
83d1318506eb615c49927dc774ebfbbb4642c9bb | Kwang-min/Python-basic | /list.py | 503 | 3.828125 | 4 | x = list() # 빈 리스트 만들기
y = [] # 빈 리스트 만들기
a = [1,2,3]
b = ["hello","hi"]
c = [1,2,"hello"]
print(a)
print(b)
print(c)
print(a + b)
print(a[0])
a[2] = 10
print(a)
num_elements = len(a)
print(num_elements)
x = [4,2,5,1]
y = sorted(x)
print(y)
z = sum(y)
print(z)
for n in y:
print(n)
u = y.index(5)# .i... |
2340b0734cd72f8c7036d0efd020035d5331ccd8 | suhasgaddam/blackjack-python | /blackjack/shoe.py | 5,218 | 3.578125 | 4 | #!/usr/bin/python
"""This module provides the :class:`shoe` object
"""
import blackjack.card as card
import random
import logging
#: a logger object
LOGGER = logging.getLogger(__name__)
class Shoe(object):
"""A Shoe object
Contains :attr:`_number_of_decks` * (13 * 4) :class:`blackjack.card.Card`
objects... |
6ac8ae6bd9cb5653a3a7f75ed1e592ac884d4e9f | stephny/Casino-game | /Casino.py | 4,123 | 3.53125 | 4 | # Programme du ZCasino
# importation des fonctions utiles
import os
from random import randrange
from math import ceil
# Déclaration des fonctions
def pair(nb):
"""Fonction permettant de vérifier si un nombre est pair ou impair"""
impair = True
if nb % 2 == 0:
impair = False
return impair
... |
8260b8e9222dcf913d528318b02bf5dad6dcb2d5 | ppjgoncalves/A1_SSFO | /Figures_5_S2/lsqfitma.py | 2,113 | 3.5 | 4 | from __future__ import division
import numpy as np
def lsqfitma(X,Y):
'''
original function and documentation
% lsqfitma.m by: Edward T Peltzer, MBARI
% revised: 2016 Mar 17.
%
% M-file to calculate a "MODEL... |
336b5c0b10e71f5ccfa41892a060946e7939a08e | RyanSamman/KAU-CPIT110 | /Chapter 3/FormatTest.py | 785 | 3.875 | 4 | x = 16.405674
# deletes anything outside 2 dp
print("x is", format(x, ".2f"))
# Keeps the string ending 10 characters from the left side of the page (right justified)
print(format(57.467657, "10.2f"))
print(format(12345678.923, "10.2f")) # str width is over 10, so moves 1 spot, but d.p is kept at 2
print(forma... |
51546c76ecbf338cd995a1f59b352aa8da7c9956 | RyanSamman/KAU-CPIT110 | /Lab3/P3.py | 186 | 3.859375 | 4 |
# Prompt input
Celsius = eval(input("Enter a degree in Celsius: "))
# Processing
Fahrenheit = (9/5) * Celsius + 32
# Output
print(Celsius,"Celsius is",Fahrenheit,"Fahrenheit") |
ffefc2996ba9be92631a2f4d534e7537bd776bdd | RyanSamman/KAU-CPIT110 | /Lab5/Problem 4_2.py | 344 | 4 | 4 | inputInteger = 1234 #eval(input("Enter an integer: "))
integer1 = str(inputInteger // 1000)
inputInteger %= 1000
integer2 = str(inputInteger // 100)
inputInteger %= 100
integer3 = str(int(inputInteger / 10))
inputInteger %= 10
integer4 = str(inputInteger)
print("The reversed number is " + integer4 + integer3 ... |
64257c97ff69207985c00d191e214967cf402ea7 | cpile/CS118-ERAU | /Practice/Map.py | 377 | 3.828125 | 4 |
def even(k):
return k % 2 == 0
def odd(k):
return not k % 2 == 0
def my_filter(f, it):
return [i for i in it if f(i)]
text = "1,2,3,4,5,6,7,8,9,10"
x = list(filter(even, map(int, text.split(","))))
y = list(filter(odd, map(int, text.split(","))))
y = list(my_filter(odd, map(int, text.split(","))))
... |
3cbbf1bf1ec178e83b0ef5d2c0110390577c65a8 | mevans86/rosalind | /transcribe_dna.py | 452 | 3.796875 | 4 | def transcribe_DNA(seq):
"""Given a DNA string t, return the transcribed RNA string of t."""
return seq.replace("T", "U")
# end transcribe_DNA
# main block
filename = raw_input("Path to Rosalind Input File: ").strip()
try:
f = open(filename, "r")
except IOError:
print "A file does not exist at this location, or so... |
8c567a996873d46835f5c75df3ca0f81280dd45a | mevans86/rosalind | /mendels_first_law.py | 1,754 | 3.609375 | 4 | def probability_of_dominant_phenotype(KMNstring):
"""Given: Three positive integers k, m, and n, representing a population containing k+m+n organisms:
k individuals are homozygous dominant for a factor, m are heterozygous, and n are homozygous recessive.
Returns the probability that two randomly selected mating org... |
10ccb73f505d78d6d169b4deefa54bd78234b1e2 | mevans86/rosalind | /enumerating_lexicographically.py | 809 | 4.375 | 4 | import itertools
import math
def sorted_sequences(alphabet, length):
"""Returns a list of tuples, each of which is a sequence of length length with letters
contained in the given alphabet. Tuples are sorted alphabetically, based on the alphabet
string provided."""
return list(itertools.product(alphabet, repeat=len... |
705d8dc899f5b861442252179f450e808c3657c4 | vcelis/python-3-bootcamp | /project2/blackjack/tests/card-test.py | 1,720 | 3.65625 | 4 | import unittest
from carddeck.card import Card
class CardTest(unittest.TestCase):
def test_one(self):
my_card = Card(Card.rank_values[1], Card.suit_values[0])
rank = my_card.rank
suit = my_card.suit
face_up = my_card.face_up
value = my_card.get_value()
self.assertEq... |
f67c9334d31e69863a26a55c600c7fa0a7aa6ccc | PFSWcas/CS231n_note | /notebook/Assignment1/cs231n/classifiers/K_NearestNeighbor.py | 6,008 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 12 21:26:29 2016
@author: ZhangHeng
"""
import numpy as np
class KNearestNeighbor(object):
""" a KNN classifier with L2 distance"""
def __init__(self):
pass
def train(self,X,y):
"""
Train the classifier. For KNN, this... |
0ba8eb3e905da8cd367e7590007a33ee686b838c | lesterlaitw/age | /age.py | 499 | 3.953125 | 4 | #if_1練習
#age = input('請輸入年齡: ')
#age = int(age)
#if age >= 20:
# print('你可以投票了!')
#else:
# print('你還不能投票!')
#if_2練習
age = input('請輸入年齡: ')
age = int(age)
if age < 13:
print('Hi,小朋友')
elif age >= 13 and age < 18:
print('Hi,中二生')
elif age >= 18 and age < 22:
print('Hi,大學生')
elif age >= 22 and age < 30:
print('你已經是... |
7628223b3d8a3898911eeb22ae666a66fff91ee2 | thefb/HashTable | /hash.py | 2,754 | 3.59375 | 4 | # Capacidade do array interno
INITIAL_CAPACITY = 50
# Estrutura de dados em nós - essencialmente um nó de listas conectadas
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
def __str__(self):
return "<Node: (%s, %s), next %s>" % (... |
7cabf84d3594c17df351c7be339d271e1869d248 | kushshah289/imdb_web_crawler | /indexer.py | 2,179 | 3.703125 | 4 | import json
from functools import reduce
import pprint
pp = pprint.PrettyPrinter(indent=4)
class Indexer:
"""
Indexer class is repsonsible to create an index for efficient retrieval
of data
attributes:
self.index = stores the index
"""
def __init__(self):
self.index = {}
... |
0cac51f9a8636401bd221a2f9b48d9c961232435 | AmeerCh/programs | /python/sum.py | 248 | 4.15625 | 4 | print('To find the sum of two numbers, ', end = "")
Number1 = int(input('enter the first number:'))
Number2 = int(input('Enter the second number:'))
Sum = (Number1) + (Number2)
print('The sum of {0} and {1} is {2}'.format(Number1, Number2,Sum)) |
16fcc941ecb594995b4342eee069dfecffdc7727 | NavrasK/exposurecoin | /.legacy2/extern/usr/user.py | 1,840 | 3.640625 | 4 | import os
import hashlib
import rsa
class User():
def __init__(self, name):
self.name = str(name) # Name is your username and password in a way
self.id_key = None # IDKey is your public key
self.p_key = None # Key is your private key (DO NOT LOSE IT!)
self.usrkeys = {}
prin... |
cc30c4481a2ff9859b2912d426a7329ebb2b9082 | postBG/MLcamp | /week1/7. Linear Regression for Class Data.py | 1,223 | 3.515625 | 4 | import statsmodels.api
import numpy
def main():
(N, X, Y) = read_data()
results = do_multivariate_regression(N, X, Y)
print(results.summary())
effective_variables = get_effective_variables(results)
print(effective_variables)
def read_data():
# 1
f = open("students.dat", 'r')
line... |
59995e8141cf04efae7e5382294f3cb7f46ab5c9 | postBG/MLcamp | /week2/1. Probability.py | 1,107 | 3.796875 | 4 | import numpy
import elice_utils
def main():
num_flips = int(input())
prob_head = float(input())
coin_results = flip_multiple_times(num_flips, prob_head)
print(visualize(coin_results))
def flip_a_coin(prob_head):
random_num = numpy.random.random()
# exercise
if random_num < prob_head:
... |
80ad4daf5b713cb3311f1040f0ec1cc452404934 | ssubramanian90/Algorithm_design | /Algorithms Analysis and Design/Week 1/1-3 Karustsuba Multiplication.py | 739 | 3.5 | 4 | """Karatsuba Multiplication"""
def karatsuba(anumber1, anumber2):
length1=len(str(anumber1))
length2=len(str(anumber2))
if length1==1 and length2==1:
return anumber1*anumber 2
else:
maxlen=max(length1, length2)
a=a... |
3dc9f8c8f60205555a079319cb048205da0cccc2 | CardinisCode/CS50_aTasteOfPython | /arithmetic.py | 804 | 4.21875 | 4 | # "x = input("x: ")
# y = input("Y: ")
# print(x + y)
# # Ouch it's adding them together as strings! aka 4 + 2 = 42
# a = int(input("a: "))
# b = int(input("b: "))
# print(a + b)
# # Alas! I get the expected output! :) "
# c = input("c:")
# d = input("D:")
# print(a * b)
# # Intersting if I multiply characters, I ge... |
09863e344504cc422a192daa3f270c18ec866762 | kaoru-kitajima/titanic | /sample.py | 387 | 3.921875 | 4 | # サンプル
print("hello world!")
sum1 = 2 + 3
if sum1 is not (int):
print(sum1)
# どうしたってこのままではおわれない。
def Add13(data):
"""
"""
data += 13
return data
if sum1 < 14:
sum2 = Add13(sum1)
print(sum2)
if sum2 > 4:
print(sum2.__abs__)
ans = float(input("input number you like"))
print("you ... |
208c3b5632617a66611db8064f2bdb3ac137527b | AakashPawanGPS/SquareShift | /main.py | 1,162 | 3.578125 | 4 | #Importing Functions required
from AirplaneFunctions import orderSeating, AisleSeats, WindowSeats, MiddleSeats
#Inputs
seating_arrangement = input()
passenger_id = input().split(" ")
passenger_id = [int(x) for x in passenger_id]
seating_arrangement_list = []
matrix = []
for i in seating_arrangement:
try:
... |
414d74823d7f0078f2585d0cabec69c7d93d86a4 | vanessalb08/learnignPython | /desafio039.py | 348 | 4.125 | 4 | from datetime import date
ano = int(input('Qual o ano de seu nascimento? '))
idade = date.today().year - ano
if idade == 18:
print('Está na hora de se alistar')
elif idade <= 18:
print('Você ainda vai se alistar, faltam {} anos'.format(18 - idade))
else:
print('Você já passou do tempo de se alistar a {} an... |
b3707773f5f4a88e6d551c590335cf62e1ca283e | vanessalb08/learnignPython | /desafio054.py | 429 | 3.859375 | 4 | #Ler ano de nascimento de 7 pessoas e mostrar quantas não são de maior
from datetime import date
maior = 0
menor = 0
for c in range(1,8):
ano = int(input('Digite o ano de nascimento da {}ª pessoa: '.format(c)))
idade = date.today().year - ano
if idade >= 21:
maior += 1
else:
menor += 1
p... |
ebbed59063bff51f0f9ddce5a66a05d23a8eac4c | vanessalb08/learnignPython | /desafio060.py | 160 | 4 | 4 | num = int(input('Digite um número: '))
soma = 1
fat = 1
while soma <= num:
fat = fat * soma
soma += 1
print('O fatorial de {} é {}'.format(num, fat))
|
9af81f25cbbd587b9eff33476889ded917d246bb | vanessalb08/learnignPython | /desafio040.py | 344 | 3.875 | 4 | nota1 = float(input('Qual a primeira nota? '))
nota2 = float(input('Qual a segunda nota? '))
media = (nota1 + nota2)/2
if media < 5:
print('Sua média é {}. REPROVADO!'.format(media))
elif 5 < media < 6.9:
print('Sua média é {}. RECUPERAÇÃO!'.format(media))
else:
print('Sua média é {}. APROVADO, PARABÉNS!'.... |
605b30f536e07caa826757630a034168b47688de | vanessalb08/learnignPython | /desafio064.py | 291 | 3.828125 | 4 | num = 0
cont = 0
soma = 0
while num != 999:
num = int(input('Digite um número [Para sair digite 999]: '))
if num == 999:
soma = soma - num
cont = cont - 1
cont += 1
soma = soma + num
print('Você digitou {} números e a soma deles é {}'.format(cont, soma))
|
7f787449c65000acda65ef4d5dd3fd9ab0a722ad | vanessalb08/learnignPython | /desafio034.py | 245 | 3.859375 | 4 | sal = float(input('Qual o valor do seu salário? R$'))
if sal <= 1250:
print('Seu novo salário será R${:.2f}, com aumento de 15%.'.format(sal*1.15))
else:
print('Seu novo salário será R${:.2f}, com aumento de 10%.'.format(sal*1.10))
|
91e2b4236febdf55356a98bdf3c387e24f7d2361 | vanessalb08/learnignPython | /desafio 066.py | 291 | 3.859375 | 4 | soma = cont = 0
while True:
num = int(input('Dugite um valor (999 para parar): '))
if num == 999: #Antes de somar, verifica se o número é o flag
break
cont += 1 #só será contabilizado se não for o flag
soma += num
print(f'A soma dos {cont} valores foi {soma}!')
|
315ee14529f666cf7660408c0de8d62e98f94a9a | Th3Av1at0r/CIS106-Avi-Schmookler | /Assignment 3/Activity #2.py | 389 | 4.09375 | 4 | print("How old are you in Years?")
# This program gives you your age in months, days, hours, muinets, and seconds
yRS = int(input())
mTH = yRS * 12
dYS = yRS * 365
hRS = dYS * 24
mIN = hRS * 60
sEC = mIN * 60
print("Your age on your birthday is " + str(mTH) + " Months or " + str(dYS) + " Days or " + str(hRS) ... |
4c71da2fb1b7f06d5707e45ec4c964f4b8399184 | Th3Av1at0r/CIS106-Avi-Schmookler | /Assignment 13/Activity 3.py | 540 | 4.21875 | 4 | # this program asks for values seperated by commas
# and prints them on seperate lines
def get_values():
values = input("Please enter values separated by commas.\n")
return values
def get_final_values(values):
final_values = values.split(",")
return final_values
def displa... |
af8203cd8d6ee0bd0eb124b29c106568828ceabb | remerjohnson/metadata-work | /src/data_subset.py | 5,214 | 3.5625 | 4 | """
data_subset.py:
Takes a giant CSV and subsets it based on license,
then outputs to individual CSVs
"""
import os
import pandas as pd
# Import our giant CSV into a giant DataFrame
df_cil = pd.read_csv('/mnt/rdcp-staging/rdcp-0126-cil-staging-qa/Spreadsheet_Subsetting/Copy of cil_excel_object_input.csv', low_mem... |
3df2016537ebace4104062325acc7b155a088d67 | saggarwal98/Practice | /Python/Assignment/5.py | 669 | 3.71875 | 4 | import sys
arg_number=len(sys.argv)
choice=input()
if choice=='a':
i=1
sum=0
while i<arg_number:
n=int(float(sys.argv[i]))
sum+=n
print(sum)
elif choice=='b':
i=1
highest=0
while i<arg_number:
n=int(sys.argv[i])
if highest<n:
highest=n
print(hi... |
b5189a0f63422c0af9fff4edde495654e88398d7 | saggarwal98/Practice | /Python/tuples.py | 78 | 3.578125 | 4 | tuple1=("abc","def","ghi")
print(len(tuple1))
print(tuple1)
print(tuple1[0:2]) |
09eabd5cce983222d9dfd87bd0a04132ec7fff33 | saggarwal98/Practice | /Python/TCS_ION_Lite/1.py | 1,041 | 3.6875 | 4 | class Account:
def __init__(self,accntNo,accntName,accntBalance):
self.acctNo=int(accntNo)
self.acctName=str(accntName)
self.accntBalance=int(accntBalance)
class Demo:
def __init__(self):
pass
def depositAmnt(self,accObj,amount):
accObj.accntBalance+=amount
... |
83055e8d5b05504d448848a6971161abec0f3483 | vucalur/knabees | /src/main/resources/scripts/generator.py | 701 | 3.890625 | 4 | #!/usr/bin/env python
import random
from sys import argv, stdout
from functools import reduce
def usage():
print("Usage: python " + argv[0] + " dimensions items_num knapsack_max items_max")
exit()
def print_list(l):
print reduce(lambda x,y: str(x)+" "+str(y), l)
try:
dimensions = int(argv[1]... |
fa1fb14a79c5796f43b878fdb698d56d5f268d2d | rcampbell1337/Python_Experiments | /images.py | 2,623 | 3.65625 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("Images")
# Select an image to be put into a label object and placed on the screen
my_img1 = ImageTk.PhotoImage(Image.open("c:/img/henry.jpg"))
my_img2 = ImageTk.PhotoImage(Image.open("c:/img/harry.jpg"))
my_img3 = ImageTk.PhotoImage... |
687e77b39143e7d712c6fd4b78b1422bd62c1787 | jglatts/pir-led | /pir_led_jawn.py | 993 | 3.828125 | 4 | #!/usr/bin/env python
import RPi.GPIO as GPIO
import time
from time import sleep
PIR_OUT_PIN = 11 # pin11
LedPin = 13 # pin13
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(PIR_OUT_PIN, GPIO.IN) # Set BtnPin's mode is input
GPIO.setup(LedPin, GPI... |
5d281937380062aaba9f1d9842d484b8314550c2 | ArshanKhanifar/eopi_solutions | /src/vlad/problem_15_p_1_var1_vlad.py | 2,668 | 3.734375 | 4 | from protocol.problem_15_p_1_var1 import Problem15P1Var1
"""
THINGS TO NOTE ABOUT THIS PROBLEM
"""
class Problem15P1Var1Vlad(Problem15P1Var1):
def towers_of_hanoi(self, n_rings):
# return self.iterative_shit(n_rings)
return self.another_iterative_one(n_rings)
"""
after writing the test ... |
332b9c6882ca0040c24462607e1b6b2b4a193e3f | ArshanKhanifar/eopi_solutions | /src/ziad/problem_11_p_1_var1_ziad.py | 1,406 | 3.90625 | 4 | '''
Find the first occurrence of an element greater than k in A.
* if k is one of the keys in the array, then it's easy - all we need is to find its last occurrence and then return the next index.
'''
# time: O(log n)
# space: O(1)
def naive_search_first_occurrence_of_element_greater_than_k(arr, k):
lower, u... |
3a7e8622b20747a0f1daa8a5f274a716dfb9c5dd | ArshanKhanifar/eopi_solutions | /src/ziad/problem_11_p_8_ziad_var1.py | 1,813 | 3.515625 | 4 | from protocol.problem_11_p_8_var1 import Problem11P8Var1
import random
class Problem11P8Var1Ziad(Problem11P8Var1):
def find_median(self, non_sorted_list):
return self.find_median_with_quick_select(non_sorted_list)
# Method 1
# I ended up taking a hint from a really clean solution developed by by Rus... |
28066e1349bec552fb495adca5aff51f07b57e94 | ArshanKhanifar/eopi_solutions | /src/vlad/problem_11_p_1_vlad.py | 2,124 | 3.625 | 4 | from protocol.problem_11_p_1 import Problem11P1
"""
THINGS TO NOTE ABOUT THIS PROBLEM
This is exactly the same problem as the having infinitely many identical eggs that all break starting at floor x and
onward and you have to fly floor x since all floors before floor x can be considered as 0 and all floors x and up c... |
fa501831788f62c71624f7cffbf4ed59d67caa2a | ArshanKhanifar/eopi_solutions | /src/protocol/problem_14_p_1.py | 2,049 | 3.578125 | 4 | from protocol.errors import EOPINotImplementedError
class Problem14P1(object):
def is_binary_search_tree(self, root):
raise EOPINotImplementedError()
class TreeNode(object):
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = righ... |
9f8d998c561031a4d36948455618425cde8993bd | natelee3/python2 | /dictionary1.py | 383 | 4 | 4 | meal = {
"entree": "smash burgers",
"drink": "IPA",
"side": "fries",
"dessert": "oreos"
}
# if "dessert" in meal:
# print("Of course I had dessert!")
# else:
# print("I didn't have dessert")
meal["appetizer"] = "bloomin' Onion"
meal["drink"] = "sweet tea"
del meal["side"]
for key, value in m... |
6358363a4a625c176f7a726a7956b4ba2833765c | sitati-elsis/data-structures-and-algorithms | /python/stack.py | 531 | 4.03125 | 4 | class Stack:
def __init__(self):
self.storage = ""
def push(self, word):
self.storage = self.storage + "-" + word
def pop(self):
word = self.storage[self.storage.rfind('-')+1:]
self.storage = self.storage[:self.storage.rfind('-')]
return word
def size(self):
... |
8d84a7c748689d4d1b9ba2128c02505276703190 | sitati-elsis/data-structures-and-algorithms | /python/selection_sort.py | 455 | 4.15625 | 4 | def selection_sort(array):
result = array
list_size = len(array)
# go through all elements in the array
for i in list(range(list_size)):
minimum_index = i
for j in list(range(i+1, list_size)):
if array[minimum_index] > array[j]:
minimum_index = j
arra... |
d68b089b2570d8ac571a4a4b9d6e15a4c32d8cc4 | SkyThonk/Calculating-Work-Function-frequency-Kinetic-Energy-Graph-b-w-K.E-wavelength--py | /Kinetic Energy.py | 1,446 | 3.6875 | 4 | ###Calculating Work Function,frequency, Kinetic Energy & Graph b/w K.E & wavelength###
#######################################################################################
#######################################################################################
import matplotlib.pyplot as plt
# H constant de... |
2b4b5b16aa7e74dc74ca92d7a65c3e94a0725dca | aliciamorillo/Python-Programming-MOOC-2021 | /Part 3/21. Find all the substrings.py | 202 | 3.921875 | 4 | word = input("Please type in a word:")
character = input("Please type in a character:")
for i in range(len(word)):
if word[i] == character and len(word[i:i+3]) == 3:
print(word[i:i+3]) |
3f640f56a6e1309bda7c0f541633ac14bc35be93 | aliciamorillo/Python-Programming-MOOC-2021 | /Part 3/22. The second occurrence.py | 389 | 4.0625 | 4 | string = input("Please type in a string:")
substring = input("Please type in a substring:")
substringLength = len(substring)
index1 = string.find(substring)
index2 = string.find(substring, index1+substringLength)
if index2 != -1:
print(f"The second occurrence of the substring is at index {index2}.")
... |
809e648ee67e8abe675b2ac10a181af9dd5a3030 | aliciamorillo/Python-Programming-MOOC-2021 | /Part 2/18. Repeat password.py | 248 | 3.921875 | 4 | password1 = input("Password:")
while True:
password2 = input("Repeat password:")
if password1 == password2:
print("User account created!")
break
if password1 != password2:
print("They do not match!") |
2c29c2dfc211eb8d0b016ca083fd364d7755c05f | aliciamorillo/Python-Programming-MOOC-2021 | /Part 3/25. Factorial.py | 302 | 4.25 | 4 | while True:
number = int(input("Please type in a number:"))
if number <= 0:
print("Thanks and bye!")
break
factorial = 1
for i in range(1,number + 1):
factorial = factorial*i
print("The factorial of the number ",number,"is",factorial) |
c9691964a582473f0792804203922561c2b37a8c | aliciamorillo/Python-Programming-MOOC-2021 | /Part 3/08. String multiplied.py | 118 | 3.984375 | 4 | string = input("Please type in a string:")
amount = int(input("Please type in an amount:"))
print(string * amount) |
45e62735287f20b6bf48eb00de9c0cfa3b80ef3b | aliciamorillo/Python-Programming-MOOC-2021 | /Part 1/28. Daily wages.py | 565 | 4.28125 | 4 | #Please write a program which asks for the hourly wage, hours worked, and the day of the week.
# The program should then print out the daily wages, which equal hourly wage multiplied by hours worked, except on Sundays when the hourly wage is doubled.
hourlyWage = float(input("Hourly wage:"))
hoursWorked = float(i... |
81b2c81970367b1edc7be30a655689218d34a2fa | aliciamorillo/Python-Programming-MOOC-2021 | /Part 1/27. Temperatures.py | 496 | 4.3125 | 4 | #Please write a program which asks the user for a temperature in degrees Fahrenheit, and then prints out the same in degrees Celsius.
# If the converted temperature falls below zero degrees Celsius, the program should also print out "Brr! It's cold in here!"
temperature = int(input("Please type in a temperature (F)... |
2ff4121ec752931b756b21f7a634d80cb13c4a48 | aliciamorillo/Python-Programming-MOOC-2021 | /Part 1/09. Fix the code Utterances.py | 223 | 3.5625 | 4 | #PHere is a program which should ask for three utterances and print them out
part1 = input("The 1st part: ")
part2 = input("The 1st part: ")
part3 = input("The 1st part: ")
print(part1 + "-" + part2 + "-" + part3 + "!") |
87e56b67de5c345990e970bd5323973bc60f1e7e | Taejin1221/MyStudy | /DataStructure/Queue/PriorityQueue/PriorityQueue.py | 1,187 | 4.0625 | 4 | class PriorityQueue():
def __init__(self):
self.queue = [ None, ]
self.size = 1
def push(self, data):
self.queue.append(data)
self.size = self.size + 1
me = self.size - 1
mom = me // 2
while (me != 1 and self.queue[mom] > self.queue[me]):
self.queue[mom], self.queue[me] = self.queue[me]... |
8750e4d57d38ec2bff7ae5ef2219de5717b8dffa | Taejin1221/MyStudy | /DataStructure/Queue/LinearQueue/Queue.py | 587 | 3.671875 | 4 | # Queue.py
class Queue:
def __init__(self):
self.__queue = []
self.__size = 0
def push(self, data):
self.__queue.append( data )
self.__size += 1
def pop(self):
if self.__size:
self.__size -= 1
return self.__queue.pop(0)
else:
return -1
def size(self):
return self.__... |
61a35662171d636c0b2bc306cdb554e7e4c5ee88 | Sayaer/GoogleFinalProject | /final_project_dir/changeImage.py | 1,249 | 3.6875 | 4 | #! /usr/bin/env python3
import os
from PIL import Image
def process_images():
"""Solves the following Problem: Change image size from 3000x2000 to 600x400
then change format from .TIFF to .JPEG"""
# Note: Files have a transparency layer, convert to RGB
# Note: Save files in the same directory, with .... |
e3b4388ea509878598ce1b450d98d57a74e9542d | mnur53/code_jam | /2018/Qualification/1_saving_the_universe/save_universe.py | 1,481 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def build_hack_tree(program):
current_dmg = 0
power = 1
command_potential = []
hack_efficiencies = []
for command in program:
if command == "C":
command_potential.append(power)
power = power * 2
else:
... |
e7c4ca9f11f069b7d3d2f658fd13ace41441bcf0 | mivler/DemonetizationProject | /order_ngram_file.py | 913 | 3.6875 | 4 | """
Author: Matthew Ivler
Takes a file of ngrams and their counts, then puts them in order for easier diagnosis on what a good count cutoff is.
"""
filename = "trigrams_count.txt"
fileout = "trigrams_count_ordered.txt"
threshold = 100
def main():
# Initialize dictionary {key = word : value = count}
unordered_... |
93d0167f9c0d5fc717e316494665b5d2a6bc5022 | boraxpr/bitesofpy | /15/enumerate_data.py | 500 | 3.5625 | 4 | names = 'Julian Bob PyBites Dante Martin Rodolfo'.split()
countries = 'Australia Spain Global Argentina USA Mexico'.split()
def enumerate_names_countries():
"""Outputs:
1. Julian Australia
2. Bob Spain
3. PyBites Global
4. Dante Argentina
5. Martin USA
... |
0c1776ec7dbe1dc117af0fd10ce4b1be6b6b84b0 | boraxpr/bitesofpy | /78/common.py | 559 | 3.9375 | 4 | from functools import reduce
def common_languages(programmers):
"""Receive a dict of keys -> names and values -> a sequence of
of programming languages, return the common languages"""
listoflang = [programmers[dev] for dev in programmers]
return reduce(set.intersection, map(set, listoflang))
# pri... |
46e3fb7806d70dc3c0bea6e82daf0498ffdd2d69 | boraxpr/bitesofpy | /86/rgb2hex.py | 430 | 4.09375 | 4 | def rgb_to_hex(rgb):
"""Receives (r, g, b) tuple, checks if each rgb int is within RGB
boundaries (0, 255) and returns its converted hex, for example:
Silver: input tuple = (192,192,192) -> output hex str = #C0C0C0"""
if rgb[0] > 255 or rgb[1] > 255 or rgb[2] > 255:
raise ValueError
r... |
3fa0e6a2418ab18ac10ca59527d41f5a8387f288 | boraxpr/bitesofpy | /119/xmas.py | 481 | 4.03125 | 4 | def generate_xmas_tree(rows=10):
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****"""
tree = list()
for row in range... |
62cc2e4121bf8d217e156107f473efb7bef4f821 | boraxpr/bitesofpy | /187/howold.py | 1,031 | 4.03125 | 4 | from dataclasses import dataclass
from dateutil import utils
@dataclass
class Actor:
name: str
born: str
@dataclass
class Movie:
title: str
release_date: str
def get_age(actor: Actor, movie: Movie) -> str:
"""Calculates age of actor / actress when movie was released,
return a string li... |
5022e342bde035099b30f439174af06cc854dc3e | boraxpr/bitesofpy | /169/convert.py | 622 | 4.15625 | 4 | def convert(value: float, fmt: str) -> float:
"""Converts the value to the designated format.
:param value: The value to be converted must be numeric or raise a TypeError
:param fmt: String indicating format to convert to
:return: Float rounded to 4 decimal places after conversion
"""
fmt = fmt... |
fe0c281153675a51fa6e2dced4532c479e5da72b | boraxpr/bitesofpy | /149/words.py | 780 | 3.90625 | 4 | wordsx = "It's almost Holidays and PyBites wishes You a Merry Christmas and a Happy 2019".split()
words = ['abc55', 'B1te', 'hope', 'how4', 'it', "Let's", 'see', 'this', 'this', 'works', '1sorts,', '22', '4', '55abc']
def sort_words_case_insensitively(words):
"""Sort the provided word list ignoring case, and numb... |
f02e2c02174259989e8af4c7f7f0b85e82fa5933 | rsera/Junior-Knights | /Pygame Code/Pygame 1/DrawingShapes.py | 1,932 | 3.96875 | 4 | # Always import pygame and sys (system)
import pygame, sys
from pygame.locals import *
# Always initialize before any other pygame code
pygame.init()
# Now we begin the "stuff that is done once."
# Create a window surface object
canvas = pygame.display.set_mode((640,480))
# You can set a caption at the top of the wi... |
77ca921c958bd68b34f030d63e7594d8bc9866af | rsera/Junior-Knights | /Old examples/Code/If statement Examples.py | 2,821 | 4.46875 | 4 | # Junior Knights Day 2 - if statement examples
# you always have a Boolean condition in your if statement
# if the condition evaluates to true, you will execute any code that follows it that is indented in one level
# any following lines that are not indented with the if statement are executed regardless of if the con... |
7e4e799fafa0e46923bc11d6a6d58c8c61080e34 | Alexsandr-STARosta/Php_Pozdnykov | /Pozdnykov_04.py | 465 | 3.546875 | 4 | #Задание 4
def polinom (a):
number_a=len(a)-1
number_b=0
while number_a >= 0:
if a[number_a] == a[number_b]:
number_a=number_a-1
number_b=number_b+1
else:
return("Фраза не являеться палиндромом")
return("Фраза являеться палиндромом... |
73c7396d9f3f3911c4a5eb7271d985bb2d4da548 | achuang2718/Rydberg_userlib | /analysislib/Rydberg/analysis_utils/labrad_fitting_routines.py | 2,274 | 3.5625 | 4 | import numpy as np
import scipy.optimize
def gaussian(offset, height, center_x, center_y, width_x, width_y):
"""Returns a gaussian function with the given parameters"""
width_x = float(width_x)
width_y = float(width_y)
return lambda x,y: offset+height*np.exp(
-(((x-center_x)/width_x)**2... |
32f1eaa7f167c0fd71ee22921c2e40ab85ab1d82 | Kbalazs3/True-Detective | /truedetective.py | 2,165 | 3.828125 | 4 |
def is_twodigit_odd(number):
if len(str(number)) == 2 and number % 2 != 0:
result = True
else:
result = False
return result
def has_access(user, users_groups, file_owner, writable_by_owner, file_group, writable_by_group, writable_by_others,
sudo_mode):
if sudo_mode:
... |
9049a7fbeb18606a8005bd0ae1d6a9214c054193 | glitchymoons/cliocrypt | /caesar.py | 703 | 3.984375 | 4 | def caesarEnc(plaintext, key):
ciphertext = ""
for c in plaintext:
if c.isalpha():
if c.isupper():
ciphertext += chr((ord(c) - 65 + key) % 26 + 65)
if c.islower():
ciphertext += chr((ord(c) - 97 + key) % 26 + 97)
else:
cipher... |
b38285c4c47d96618441e891f86214bf7d02c14f | ksu3101/studyPythonRepo | /studyList.py | 2,621 | 3.921875 | 4 | # List study
# list examples
list1 = []
list2 = [1, 2, 3]
list3 = ['kang', 'kim', 'park']
list4 = ['kim', 100, 0.15, 'lee']
list5 = [1, ['kim', 'jung', 'lee'], 2, 3]
strList = ['kim', 'lee', 'park', 'kang']
print(strList[0] + strList[2])
print(strList[-1])
testList = [1, 4, 6, 12, 20]
print(testList[-1])
testList2 =... |
06565b13116bebbe8b3a7306f7a0531adbefdd7c | ksu3101/studyPythonRepo | /lotto.py | 237 | 3.609375 | 4 | import random
class Lotto:
numbers = [i for i in range(1, 46)]
def generate_number(self):
random.shuffle(self.numbers)
def __str__(self):
return self.numbers[0:6].__str__()
lotto = Lotto()
lotto.generate_number()
print(lotto)
|
c9302580075d1aae7d1d3405ca4389267516bfba | ksu3101/studyPythonRepo | /studyclasses/cal.py | 1,574 | 4.15625 | 4 |
class Calculator:
x = 0
y = 0
# 클래스의 생성자
def __init__(self, x, y):
self.x = x
self.y = y
# x 와 y 의 합을 얻는 함수
def add(self):
return self.x + self.y
# x 에서 y 를 뺀 값을 얻는 함수
def minus(self):
return self.x + self.y
# x 와 y를 나눈 값을 얻는 함수 (x 나 y가 둘 중 하나라도 0 일경우 0을 반환)
def divide(self):
if self.x == 0 or ... |
cd55c46b76add264e9fce1f1beba3d6bb40e35eb | ksu3101/studyPythonRepo | /testString.py | 1,941 | 3.546875 | 4 | montyPython = "Monty python's Flying Circus"
# 문자열의 길이 `len()`
print("monty's count = %d" % len(montyPython))
# 문자열에서 특정 문자나 단어의 갯수 세기 `count()`
print(montyPython.count('o'))
print(montyPython.count('on'))
# 문자열에서 특정 문자의 인덱스 얻기 `find()` : 없을 경우 -1
# 가장 처음을 찾게 되는 문자의 인덱스를 얻는다.
print(montyPython.find('p'))
print(monty... |
7df1a53efeb81750dff8b69690c921a3e1951c72 | RhobbeMartin/Greeting-Card | /main.py | 591 | 3.53125 | 4 | import turtle
#turtle.Screen allows you to define your screen size
screen = turtle.Screen()
screen.setup(500,500)
screen.bgcolor("#8F6161")
# dictionary of colors (https://htmlcolorcodes.com/) to pick color
colors = {
"blue":"#358FC8",
"red":"#FF2D00",
"pink":"#FF00DC",
"yellow":"#FCFF00",
"black":"#000000"... |
262f60c0011830a64694f86657130cdcf147bf08 | cp1372/HackerRank | /camelcase.py | 171 | 3.84375 | 4 | #!/bin/python
import sys
s = raw_input().strip()
words = 1
for x in s:
#Comparison on ASCII values
if x < 'a':
words += 1
print words |
a30011d3198da5a6618f873ed20071ae03fd5eb5 | supersunspp/DataStructure_And_Algorithm | /Algorithm/希尔排序/hillSort.py | 531 | 3.859375 | 4 | # coding=utf8
def swap(a, firstIndex, secondIndex):
t = a[firstIndex]
a[firstIndex] = a[secondIndex]
a[secondIndex] = t
def hillSort(a):
if len(a)<=0:
return ''
length = len(a)
h = 1
while h<(length/3):
h = h * 3 + 1
while h>=1:
for i in range(h,... |
e8f6299930d0c2a1e5387a0305d9ecb7d160603b | supersunspp/DataStructure_And_Algorithm | /LeetCode/53/maxSubArray.py | 251 | 3.59375 | 4 | def maxSubArray(nums):
b = []
if len(nums)==0:
return 0
b.append(nums[0])
mam = b[0]
for i in range(1,len(nums)):
b.append(max(nums[i],b[i-1]+nums[i]))
if mam<b[i]:
mam=b[i]
return max(b)
|
b8008103888a6c08b48deaa15905eaab39264333 | supersunspp/DataStructure_And_Algorithm | /Algorithm/二分查找/binarySearch.py | 444 | 4.03125 | 4 | def binarySearch(a, key):
low = 0
high = len(a) - 1
if key==a[low]:
return low
if key==a[high]:
return high
if key<a[low] or key>a[high]:
return
while (high-low)>1:
mid = low + (high - low) / 2
if a[mid]>key:
high = mid - 1
elif a[mi... |
3a36faffe2aefe256995fc436a6f5ecd418f7ae1 | Tushar07082/Hackerrrank_questions | /python/strings_alphabet_rangoli.py | 1,221 | 3.703125 | 4 | def print_rangoli(size):
m = chr(96+size)
w = m
for i in range(size):
print("-"*(2*size - 2-2*i),end="")
for j in range(2*i + 1):
print(m,end="")
if((j+(2*size - 2-2*i)) <= 2*size - 1):
... |
917ca606d78a6946e26e8f1449208f1964bdd226 | abhishekatujjain/OpenCV3 | /histogram.py | 1,814 | 3.71875 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
def drawHist():
''' histogram will help to understand the image: intensity, contrast'''
''' This function creates a black image from numpy and
plots histogram on the number of pixels with color values
It will create only one h... |
39bc88c53b6cee18e1e04a9316e1101c5dd41f3a | anoushkaalavilli/Character-Distribution | /distribution.py | 2,515 | 4.34375 | 4 | """
distribution.py
Author: Anoushka Alavilli
Credit: Sarah, Dina, Jasmine, Mr. Dennison, my dad, http://stackoverflow.com/questions/15536287/stripping-commas-and-periods
Assignment:
Write and submit a Python program (distribution.py) that computes and displays
the distribution of characters in a given sample of tex... |
61198cd25bf2986ccb756376c975b8d31dc9fe3f | Tanya3108/kmap | /K-Map.py | 21,335 | 3.6875 | 4 | # CSE 101 - IP HW2
# K-Map Minimization
# Name:Tanya Sanjay Kumar
# Roll Number:2018109
# Section:A
# Group:05
# Date:16-10-2018
import copy
#matches two characters and replaces the non-matched character with a "-"
def matchingChars(x,y):
x=str(x)
y=str(y)
n=len(x)
c=0
... |
fb583cf9f74aed932de1aab6c1e99a50fc870525 | csmali/twitter_sentiment_analysis | /number.py | 1,313 | 3.84375 | 4 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import operator
def print_words(filename):
d = {}
f = open(filename,'rU')
... |
357d3c0bbb58aebff846a7276c7746baf7a80bcb | zachgarwood/redshelf | /purchase_sort/data_io.py | 1,834 | 3.59375 | 4 | """Import and export data to and from external files"""
import csv
import json
from .bucket import Bucket
from .purchase import Purchase
BUCKETS_FILE_FIELDS = ['publisher', 'price', 'duration']
BUCKETS_FILE_PATH = 'data/purchase_buckets.csv'
PURCHASES_FILE_FIELDS = ['order_id',
'isbn',
... |
ef42a22217d8fa730c777df29be6e9a9fc398410 | shadydealer/Python-101 | /Solutions/week11/CinemaReservation/src/queries/ms_handler.py | 867 | 3.71875 | 4 | #import sqlite3
import psycopg2
"""
Executes and commits a query that makes changes to the dbName.
@params dbName - name of the database we're altering.
@params query - query we're executing.
"""
def execute_and_commit(*, dbName, query,values=None):
connection = psycopg2.connect(f'dbname={dbName}')... |
48611a8e455a4dcd248e65f77e5be622b461ddd1 | shadydealer/Python-101 | /Solutions/week01/steps_in_python.py | 1,616 | 3.75 | 4 | import math
def sum_of_digits(n):
n = abs(n)
sum = 0
while n > 0 :
sum += (n%10)
n//=10
return sum
def to_digits(n):
arr = []
if n == 0:
arr.append(0)
while n > 0 :
arr.append(n%10)
n//=10
arr.reverse()
return arr
def to_number(digits):
num =0
for digit in digits:
num *=10
num += digit
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.