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
f1f2b09a5a7d9453ee9ca98f74d12f73e75a182a
PropeReferio/practice-exercises
/important-concepts/get_digit.py
823
3.8125
4
import math class Solution: def get_digit(self, x: int, dig: int) -> int: '''Takes an int an a digit as input, outputs the value of said digit.''' return x // 10 ** dig % 10 # First floor division by 10 for 10's place, # 100 for 100's place, etc (puts 100's place digit in 1's place)...
9c4378edfdb41a942286830610d4bf2c24d2535f
PropeReferio/practice-exercises
/daily-coding-problem/dcp_10.py
266
3.71875
4
#This problem was asked by Apple. #Implement a job scheduler which takes in a function f and an integer n, # and calls f after n milliseconds. import time def scheduler(func, n): time.sleep(n/1000) f() def f(): print('Do stuff') scheduler(f, 5000)
07439e13efd7e16d993733605018fd0624c65820
PropeReferio/practice-exercises
/random_exercises/alien_colors.py
339
3.828125
4
# Ex 5-3 from Python Crash Course alien_color = 'red' points = 0 if alien_color == 'green': points += 5 print(f"Player 1 earned {points} points.") elif alien_color == 'yellow': points += 10 print(f"Player 1 earned {points} points.") elif alien_color == 'red': points += 15 print(f"Player 1 earned...
796c9387dce8f55b1a2a7efd90438bdff7eee5c8
PropeReferio/practice-exercises
/random_exercises/filter_with_lambda_enumerate.py
514
3.59375
4
def multiple_of_index(arr): print(arr) for i, x in enumerate(arr): print(i,x) def divisible_by_index(lst): for i, x in enumerate(lst): if not x % i: return True else: return False #return list(filter(divisible_by_index, arr[1:])) ...
89a8e2146e366ce54617134d314e68d81c6b340a
PropeReferio/practice-exercises
/random_exercises/cars.py
282
3.890625
4
def car_info(manu, model, **car_info): """Creates a dictionary with info about a car that can receive an arbitrary number of k,v pairs""" car = {} car['manufacturer'] = manu car['model'] = model for k, v in car_info.items(): car[k] = v return car
93dedb445a3623c144f6b064941685eea52144d8
PropeReferio/practice-exercises
/random_exercises/opportunity_costs.py
5,771
4.125
4
# A program I made to compare my lifetime earnings in my current career, and #after having taken a bootcamp, or going to college, taking into account #cost of bootcamp/school and the time spent not making money. current_age = float(input("How old are you? ")) retire_age = int(input("At what age do you expect to retire...
2c4c928322977ee0f99b7bfe4a97728e09402656
PropeReferio/practice-exercises
/random_exercises/temp_converter.py
586
4.28125
4
unit = input("Fahrenheit or Celsius?") try_again = True while try_again == True: if unit == "Fahrenheit": f = int(input("How many degrees Fahrenheit?")) c = f / 9 * 5 - 32 / 9 * 5 print (f"{f} degrees Fahrenheit is {c} degrees Celsius.") try_again = False elif unit == "Celsius"...
25cc7ac225f74fd71ba79e365a251a2daf83aeb7
PropeReferio/practice-exercises
/random_exercises/rand_pass.py
730
3.8125
4
# Ex 16 from practicepython.org Write a password generator in Python. Be #creative with how you generate passwords - strong passwords have a mix # of lowercase letters, uppercase letters, numbers, and symbols. The # passwords should be random, generating a new password every time the # user asks for a new password....
7b8aa1806a0084dfd6e189720fc10131d0e0b1b1
PropeReferio/practice-exercises
/random_exercises/fave_fruits.py
438
3.96875
4
# Ex 5-7 from Python Crash Course faves = ["Mangoes", "Papayas", "Maracuya"] if "bananas" not in faves: print("You don't like bananas?") if "mangoes".title() in faves: print("Yeah... mangoes are delish!") if "papayas".title() in faves: print("Papayas have a nice blend of flavors.") if "Maracuya" in faves:...
849c615ac2f77f6356650311deea9da6c32952bf
andrearus-dev/shopping_list
/myattempt.py
1,719
4.1875
4
from tkinter import * from tkinter.font import Font window = Tk() window.title('Shopping List') window.geometry("400x800") window.configure(bg="#2EAD5C") bigFont = Font(size=20, weight="bold") heading1 = Label(window, text=" Food Glorious Food \n Shopping List", bg="#2EAD5C", fg="#fff", font=bigFo...
74f7e45ab5fc619715f5e530b6790c65c51a3767
caiooliveirac/Jogo-da-Forca
/core.py
554
3.53125
4
#Modelo de criação de diferentes arquivos txt com dificuldades diferentes baseados numa lista arquivo = open('palavras2.txt',mode='r',encoding='utf8') arquivo2 = open('palavras3.txt',mode='r',encoding='utf8') todas = [] nivel = [] for linha in arquivo: linha.strip() todas.append(linha) for palavra in arquivo2...
66c823e68f5362768970826ee380e58da07b57d2
jamesspearsv/cs50
/pset6/mario/more/mario.py
648
4.03125
4
from cs50 import get_int def main(): h = 0 while h < 1 or h > 8: h = get_int("Height: ") printPyramid(h) # Function definitions def printPyramid(h): for i in range(h, 0, -1): # Print left half for j in range(h): if j < i-1: print(" ", end="") ...
026dc30173ab7427f744b000f55558ffc19099e8
glaxur/Python.Projects
/guess_game_fun.py
834
4.21875
4
""" guessing game using a function """ import random computers_number = random.randint(1,100) PROMPT = "What is your guess?" def do_guess_round(): """Choose a random number,ask user for a guess check whether the guess is true and repeat whether the user is correct""" computers_number = rand...
19c763e647a12c9b697005354a86de78726e08b7
lukechn99/leetcode
/nDistinct.py
572
3.828125
4
# given a string, find the number of substrings that have n distinct characters # use sliding window def distinct(string, ptr1, ptr2): pass def nDistinct(string, n): ptr1 = 0 ptr2 = n number_distinct = 0 while ptr1 < len(string) - n: while ptr2 < len(string): if distinct(st...
d1a7e7a1efd779623129ce86fa8237e490690b4b
lukechn99/leetcode
/traverse.py
264
3.5625
4
import os def traverse(dir): print(dir) tempcwd = os.getcwd() if os.path.isdir(os.path.join(tempcwd, dir)): for d in os.listdir(os.path.join(tempcwd, dir)): os.chdir(os.path.join(tempcwd, dir)) traverse(d) os.chdir(tempcwd) traverse(".")
4e9a3cb0737ffd797c2231646f57d6f00a14b4e9
lukechn99/leetcode
/pleasePassTheCodedMessages.py
2,429
3.984375
4
# Please Pass the Coded Messages # ============================== # You need to pass a message to the bunny prisoners, but to avoid detection, the code you agreed # to use is... obscure, to say the least. The bunnies are given food on standard-issue prison # plates that are stamped with the numbers 0-9 for easier...
6ff855754a5b040e7b46749ce8a68a90e15a389a
lukechn99/leetcode
/count_clicks.py
3,129
3.703125
4
''' You are in charge of a display advertising program. Your ads are displayed on websites all over the internet. You have some CSV input data that counts how many times that users have clicked on an ad on each individual domain. Every line consists of a click count and a domain name, like this: counts = [ "900,google...
fc3bd6d939a85c3cee0f57229bd9bbdcd4da9be0
lukechn99/leetcode
/removeN.py
822
3.75
4
def removeEven (list): for i in list: if i % 2 == 0: list.remove(i) return list list = [1, 2, 3, 4, 5, 6, 7, 8] print(removeEven(list)) def removeMultTwo (n): list = [] for i in range(2, n+1): list.append(i) for p in list: # p starts as 2 # multiplier = 2 # multiplier = 3 # ... for multiplier in ...
46f70133d8fc36aa8c21c51ba8cd35efd18fcfc7
MenggeGeng/FE595HW4
/hw4.py
1,520
4.1875
4
#part 1: Assume the data in the Boston Housing data set fits a linear model. #When fit, how much impact does each factor have on the value of a house in Boston? #Display these results from greatest to least. from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression import matpl...
256c69199c1891d4c678824e59db2b80b69e3aa2
sangianpatrick/hacktiv8-python-datascience
/day_01/task5.py
273
3.859375
4
#pesanan orderan = list() order = input("Masukkan pesanan pertama: \n") orderan.append(order) order = input("Masukkan pesanan kedua: \n") orderan.append(order) order = input("Masukkan pesanan ketiga: \n") orderan.append(order) print("Pesanan anda: \n") print(orderan)
0145516901db83e2d3f6d3e4962212eb8c2c27d8
sangianpatrick/hacktiv8-python-datascience
/day_02/task3.py
134
3.578125
4
pangkat = 3 for x in range(11): a = x**pangkat print("Hasil dari {x} pangkat {pangkat} adalah {a}".format(x=x,pangkat=pangkat,a=a))
546e3058dab3aec1e7aeac1c12d7a96ae404b1bd
ahilgenkamp/Pi_projects
/Boggle_AI/word_distribution.py
741
3.65625
4
#word distribution graph import string import matplotlib from nltk.corpus import words #load dictionary word_list = words.words() print('Total Words: '+str(len(word_list))) low = string.ascii_lowercase ''' for i in range(len(low)): num_letters = sum(a.lower() == low[i] for a, *_ in word_list) #for n...
a7a25c301bdd9cf4cfea71458868d1aa7d20b548
hannes1903/Homework-and-Exercises
/count.py
409
3.6875
4
import collections words = ['a', 'b', 'a', 'c', 'b', 'k'] c = collections.Counter(words) print (c) print (c.most_common(2)) print (c['i']) def count_1 (a): a = collections.Counter(words).most_common(2) return (a) print (count_1 (words)) ## d={} for word in words: if word in ('a', 'b', 'h'): ...
61a6ef3a2803175b7082beb408ba794a4980c9b4
hannes1903/Homework-and-Exercises
/even the last.py
309
3.5625
4
import math import statistics b = [1,2,4,5,6,7,8,9,6,6,4,5,] print(len(b)) list2=b[0::2] print (list2) list3=sum(list2)*b[-1] print (list3) def checkio(V): a=len(V) if a==0: return (0) else: list2=V[0::2] list3=sum(list2)*V[-1] return (list3) print (checkio(b))
3b75c81b02d0b18839a1ed43429119fc0a3d05af
J-man21/Python_Basics
/107_for_loops.py
595
3.84375
4
# For Loops # syntax # for item in iterable: # block of code import time cool_cars = ['Ferrari', 'Fiat', 'Skoda','Mk7','VW', 'focus'] #for car in cool_cars: # print(car) # time.sleep(1) count = 1 for car in cool_cars: print(count, '-', car) count += 1 time.sleep(1) # For loop for diction...
94d019ad93368584495f832b72ccc2c0230526c8
kyleo83/EscapeTheKonigsberg
/bridge.py
3,923
3.75
4
from scene import Scene from textwrap import dedent from stats_inventory import Person, Inventory import numpy as np class Bridge(Scene): def enter(self): print(dedent(""" You find yourself on bridge #7 and you are not alone. The captain of the ship 'Dicey Roll' is blocking your path ...
4766351a150037e894e98ccb190c9386af39a5a0
slackbot115/calculadora_lei_de_ohm
/lei de ohm.py
1,253
3.859375
4
op = input("Digite qual lei de ohm voce deseja efetuar as contas: \n1 - Primeira Lei de Ohm (digite 1)\n2 - Segunda Lei de Ohm (digite 2)\n\n") if op == "1": conta = input("Digite o valor que voce deseja encontrar: \nR - Resistencia\nV - Tensao\nI - Intensidade Corrente\nDigite a respectiva letra que voce deseja e...
cf716a695460503ee0dbc131e3569d60f2669393
jsrawan-mobo/samples
/python/ce/tictactoe.py
1,567
3.703125
4
# To go faster m = 1000 # So avoid going through 1M squares. We would need to do 4 types. So could be 4 * 1000 # This is pretty fast, so i don't think it be a problem # We know the sum of any board is M class TicTacToe(object): def __init__(self, m): self.the_board = [[False for x in xrange(m)] for y i...
c88ca226b26c7b77b58a6181dc36031c6d31d7fd
jsrawan-mobo/samples
/python/ce/baybridges2.py
11,010
3.734375
4
from copy import copy from itertools import permutations, chain from sys import argv # # Two sequences where the greatest subsequence, which is NON continguous # assume only one unique # Create a recursive sequence, that basically takes the left, and walks through all possibilities # Its recursive # This below will t...
a6622d0573a5ead8200ba2ffb9eb5d736d0b7cb3
easontm/Cinemagraphs
/scripts/note_refresh.py
726
3.515625
4
import urllib.request import fileinput from os import system localNotePath = "/home/pi/Cinemagraphs/notes/Notes.txt" remoteNotePath = "https://www.dropbox.com/s/nh8o4gou047td5m/Notes.txt?dl=1" # Download the notes from remoteNotePath and save it locally under localNotePath: with urllib.request.urlopen(remoteN...
9d723b583cec6a1c2ec2aea6497eec0d6dd6d27f
ageinpee/DaMi-Course
/1/Solutions/Solution-DAMI1-Part3.py
2,024
4.15625
4
''' Solution to Part III - Python functions. Comment out the parts you do not wish to execute or copy a specific function into a new py-file''' #Sum of squares, where you can simply use the square function you were given def sum_of_squares(x, y): return square(x) + square(y) print sum_of_squares(3, 5) # Try out you...
3abbabd95a1f0b3d2cc6f91659af0231d9d9b112
sejinwls/2018-19-PNE-practices
/session-17/client2.py
1,771
3.921875
4
# -- Example of a client that uses the HTTP.client library # -- for requesting a JSON object and printing their # -- contents import http.client import json import termcolor PORT = 8001 SERVER = 'localhost' print("\nConnecting to server: {}:{}\n".format(SERVER, PORT)) # Connect with the server conn = http.client.HTT...
6f4e6fe5a6989ddd065712fe1e9d917d31648b6b
sejinwls/2018-19-PNE-practices
/Session-7/client.py
426
3.546875
4
# Programming our first client import socket # Create a socket for communicating with the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket created") PORT = 8080 IP = "212.128.253.108" # Connect to the server s.connect((IP, PORT)) # Send a message s.send(str.encode("HELLO FROM MY CLIENT")...
45fc9452f03b169869eb753bf3ffc017540dd052
sejinwls/2018-19-PNE-practices
/session-5/ex-1.py
620
4.1875
4
def count_a(seq): """"THis function is for counting the number of A's in the sequence""" # Counter for the As result = 0 for b in seq: if b == "A": result += 1 # Return the result return result # Main program s = input("Please enter the sequence: ") na = count_a(s) print...
3e282477d9c87ed3371cec434b14c76908e72b91
ElonRM/DataScienceBuch
/Kapitel_5_Statistik/Lagemaße.py
1,223
3.609375
4
from typing import Counter, List import numpy num_friends = numpy.random.binomial(100, 0.06, 206) def mean(xs: List[float]) -> float: return sum(xs)/len(xs) # Die Unterstriche zeigen, dass dies "private" Funktionen sind, da sie nur # von unserer median Funktion, nicht aber von anderen Nutzern unserer Statistik...
4e8419fba8837646ac89192407d2f4fcf9c74fa0
ElonRM/DataScienceBuch
/Kapitel_5_Statistik/Einen_einzelnen_Datensatz_beschreiben.py
790
3.625
4
import numpy as np from collections import Counter from matplotlib import pyplot as plt import math num_friends = np.random.binomial(100, 0.08, 204) friends_counter = Counter(num_friends) plt.bar(friends_counter.keys(), friends_counter.values(), edgecolor=(0, 0, 0)) #plt.xticks([20*i for i in range(6)]) #plt.yticks([i...
e152129339f29660b810322076c088030a59ff0d
ElonRM/DataScienceBuch
/kapitel_3_Daten_Visualisierung/Balkendiagramme.py
2,264
3.8125
4
from matplotlib import pyplot as plt from collections import Counter plots = ["movies", "grades", "mentions"] # Funktioniert nicht wirklich... selected_plot = plots[2] #grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0] x_values = { "movies": ["Annie Hall", "Ben-Hur", "Casablanca", "Gandhi", "West Side...
468fc754315c516757a5e679e03e13d97d69f3f5
Sergey-Shulnyaev/my_python
/graphics/moodle/1/15.py
3,969
3.828125
4
from math import sqrt import math class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(%.2f, %.2f)" % (self.x, self.y) def distanceTo(self, point): return math.sqrt((self.x - point.x) ** 2 + (self.y - point.y) ** 2) def __sub__(self,...
29f58b769d226b4790169e5730c7a9075b8b0451
Sergey-Shulnyaev/my_python
/HomeWork_10.09.19/Third.py
2,353
3.640625
4
import tkinter class GaloConverter: def __init__(self): # Создать главное окно. self.main_window = tkinter.Tk() # Создать три рамки, чтобы сгруппировать элементы интерфейса. self.top_frame = tkinter.Frame() self.mid1_frame = tkinter.Frame() self.mid2_frame = tkint...
4d7589abe594f6a22e9d308214666b90054a23c4
Sergey-Shulnyaev/my_python
/graphics/moodle/1/4.py
818
4.0625
4
from math import sqrt class Line: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __str__(self): if self.a < 0: a = " - %.2fx" % (-self.a) else: a = "%.2fx" % (self.a) if self.b < 0: b = " - %.2fx" % (-self.b) ...
18fc474590f1def29690c55bd15232b983edba25
Sergey-Shulnyaev/my_python
/HomeWork_1/cinema_price.py
1,448
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 14:37:06 2019 """ def vibor_film(film,time): if film == 'Пятница': if time == 12: return 250 elif time == 16: return 350 elif time == 20: return 450 elif film == 'Чемпионы': if time == 10: ...
38285d586d40592a3a00bace74aa4166960e6b03
moreira-matheus/math-fun
/exp_pow.py
513
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 13:58:42 2018 @author: USP """ import random import matplotlib.pyplot as plt def exp_pow_num(x): return x**x def exp_pow_den(x): return x**(1./x) N = 20000 x_low, x_high = 10**(-6), 2 x = sorted([random.uniform(x_low, x_high) for _ in range(N)]) y_num = [e...
7b5046099a1e06aa79d090d9f2d3fee33da48946
aratik711/100-python-programs
/my_exception_2.py
456
3.859375
4
""" Define a custom exception class which takes a string message as attribute. Hints: To define a custom exception, we need to define a class inherited from Exception. """ class myError(Exception): """My own exception class Attributes: msg -- explanation of the error """ def...
dbe164b35c75b08ccfca88cf63db48220b7ffafc
aratik711/100-python-programs
/number_add.py
386
4.09375
4
""" Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106 """ num = int(input()) num1 = int("%s" % num) num2 = int("%s%s" % (num, num)) num3 = int("%s%s%s" % (num, num, num)) num4 = i...
30ee27670b91ef7aa6bfc727131e6d2271c00f6c
aratik711/100-python-programs
/frequency.py
692
4.09375
4
""" Question: Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. Suppose the following input is supplied to the program: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. Then, the output should be: 2:...
e14736ccc657561a7db0a6653d64f05953b85d30
aratik711/100-python-programs
/eval_example.py
320
4.28125
4
""" Please write a program which accepts basic mathematic expression from console and print the evaluation result. Example: If the following string is given as input to the program: 35+3 Then, the output of the program should be: 38 Hints: Use eval() to evaluate an expression. """ exp = input() print(eval(exp))
0e38a128a6b075c53e090d701674e4ff4b32026d
aratik711/100-python-programs
/isogram.py
516
3.859375
4
""" Determine if a word or phrase is an isogram. An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times. Examples of isograms: lumberjacks background downstream six-year-old The word isograms, however, is not an ...
d33e36b0734802ce63caaa7310a21ecb2b6081d6
aratik711/100-python-programs
/subclass_example.py
382
4.125
4
""" Question: Define a class named American and its subclass NewYorker. Hints: Use class Subclass(ParentClass) to define a subclass. """ class American: def printnationality(self): print("America") class NewYorker: def printcity(self): American.printnationality(self) p...
f3744e80c43703b02eab678c8b9e4b5d9569f3fb
ValeriiaGW/IntroPython_Bakanova_Valeriia
/HW4/hw_test.py
1,361
3.890625
4
values = [1, 2, 3, 4, 5] print(type(values)) values = (1, 2, 3, 4, 5) print(type(values)) values = (1, 2, 3, 4, 5) values = list(values) print(type(values)) values = [1, 2, 3, 4, 5] values = tuple(values) print(type(values)) values = [1, 2, 3, 4, 5] result = [] for value in values: result.append(value) print(re...
86977ffec84ee264f4dbf4c17e374611ca7ef533
ValeriiaGW/IntroPython_Bakanova_Valeriia
/HW_8/hw_8.py
2,845
3.640625
4
# 1) Дан список словарей persons в формате [{"name": "John", "age": 15}, ... ,{"name": "Jack", "age": 45}] # а) Напечатать имя самого молодого человека. Если возраст совпадает - напечатать все имена самых молодых. # б) Напечатать самое длинное имя. Если длина имени совпадает - напечатать все имена. # в) Посчитать средн...
b02b74b30fa5db9a2c53d84dae858543ef2e3e00
S-Cardenas/Chess_Python_FP
/Pawn.py
3,416
3.546875
4
#location has to be the index of the list board def Pawn(piece, location, board, active_indx): if piece > 0: if location >= 9 and location <= 16: a = location + 1 * 9 b = location + 2 * 9 c = location + (1 * 9) + 1 d = location + (1 * 9) - 1 new_indxs = [a, b, c, d] #Check if new location is a...
e4d60aa8dc63871a3076ef785a7aabab78806d79
SudeepNadgambe/cv
/Guess_game.py
812
3.96875
4
import random print("Welcome to the Number Guessing Game\nI am thinking of a number between 1 and 100") guessed_number=random.randint(1,100) print(guessed_number) level=input("Type 'e' for easy level\nType 'h' for hard level\n") if level == 'e': chances = 10 elif level == 'h': chances = 5 else: ...
a3863e7f034ce25c3b0803c0230e732508e90d98
jordwhit3288/PTO-App
/PTO_Calculator_v4.0.py
10,363
3.859375
4
from datetime import date import datetime from datetime import datetime import time import pandas as pd import numpy as np def hours_current_balance(nurse_or_not): if nurse_or_not == 'yes': nurse_hours_num = accruing_pto_hours() nurse_hours_pto = input('Are you going to use PTO?') ...
4e86f5a5a42e92bae21d418e4e7e29718ca47ec9
ncrafa/infosatc-lp-avaliativo-03
/exercicio 3.py
327
3.921875
4
numero=int(input("Insira um numero de 1 a 12: "))-1 meses=["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"] for x in range(1,12): if x==numero: print(" mês de: ",meses[numero]) if x != numero : print(" mês não encontrad...
58694ea2088a17fc1bff58cc191519bb5277daf3
ryan-ghosh/Python-Projects
/ESC180_Labs/LAB!.py
866
3.625
4
def find_euclidean_distance(x1, y1, x2, y2): """ (float,float,float,float) -> float """ def is_cow_within_bounds(cow_position, boundary_points): """ Your docstring here """ def find_cow_distance_to_boundary(cow_position, boundary_point): """ Your docstring here """ def ...
eb63a6c9cc749b10b0d18785e756048bee6b0dde
ryan-ghosh/Python-Projects
/scheduler.py
1,465
3.6875
4
class Node: def __init__(self, date:int, schedule:dict): self.date = date self.schedule = schedule def add_task(self, time:int, task:str): self.schedule[time] = task def print_task(self, time:int): print(self.schedule[time]) def print_schedule(se...
944dbd5c7aa1cb0f5543c61e7a44dd2507eb8274
Macro1989/cp1404practicals
/prac_02/randoms.py
652
3.953125
4
import random print(random.randint(5, 20)) # line 1 print(random.randrange(3, 10, 2)) # line 2 print(random.uniform(2.5, 5.5)) # line 3 #What did you see on line 1? 13 #What was the smallest number you could have seen, what was the largest? 5 and 20 #What did you see on line 2? 3 #What was the smallest number you...
26b320e3ef9c264c91eceb6661117ec9356d117a
JoCGM09/AlgorithmsAndDataStructuresPython
/Algorithms/Search/binary_Search.py
1,484
4.03125
4
""" - Search algorithm who search a value in a given list by looking for the middle of it. If we get a match return the index, else if we do not get a match check whether the element is less or greater than the middle element. If is greater pick the elements on the right and start again, if is less pick the left. - I...
5e0fc9b783390cb732bee5f5cba05f87a75591eb
julianandrews/adventofcode
/2019/python/utils/pq.py
1,325
3.796875
4
import heapq class UpdateableQueue: def __init__(self): self.count = 0 self.values = [] self.entries = {} def push(self, value, priority): """Add a new value or update the priority of an existing value.""" if value in self.entries: self.remove(value) ...
d21fe1c61458bf07a2f42d8236972c5073bc4286
julianandrews/adventofcode
/2015/python/day13.py
1,050
3.5
4
import collections import fileinput import itertools def happy_sum(people, happy_map): neighbors = itertools.cycle(people) next(neighbors) return sum( happy_map[a][b] + happy_map[b][a] for a, b in zip(people, neighbors) ) def part1(happy_map): return max( happy_sum(people...
190b8e36d82e4d4e8b6f90f3f31b44981f1906f2
imudiand/recipes
/Python/decorators/decorators.py
2,107
3.9375
4
from functools import wraps # Why use functools.wraps ?? # When you print get_text.__name__ doesnt return get_text # without using wraps; you'l see that the name is overridden # to the wrapper functions name - func_wrapper. # Hence, use this @wraps decorator on the wrapper_function # and pass the func as an argument ...
6e137cdf18daa271370c51ee89fb3f3d05e1cbda
imudiand/recipes
/Python/generators/non-generator_prime_nums.py
666
3.96875
4
import math # Non-Generator Implementation - Get prime Numbers def get_primes(input_list): prime_numbers_list = [] for item in input_list: if is_prime(item): prime_numbers_list.append(item) return prime_numbers_list def get_primes2(input_list): return [ item for item in input_list if is_prime(item) ] def i...
a8f29d0c4f9adb25af4ff18d596b2f5301801bdc
imudiand/recipes
/Python/tuts/recursion/recursive_sum.py
312
3.8125
4
def r_sum(num_list): sum = 0 for item in num_list: if type(item) == type([]): sum += r_sum(item) else: sum += item return sum def main(): list1 = [3, 5, 9, 20, 100] print r_sum(list1) list2 = [3, [4, 2, 4], 2, [3, 4, [5, 3], 12], 2, 9] print r_sum(list2) if __name__ == "__main__": main()
52c361e776fc68c64270961259066b5e6eac6364
rootwiz/colorful_hexagon
/Hexagon.py
1,683
3.625
4
# screen size S_HIGHT = 500 S_WIDTH = 500 # 正六角形クラス class Hexagon: ''' ---- / \ \ / ---- ''' size = 40 def __init__(self, x, y, color, wall): self.width = Hexagon.size self.height = Hexagon.size * 3 // 4 pos_x = self.size // 3 pos_y =...
ab158012359b50275f2adabb082830fb37bfd103
joeycarter/atlas-plot-utils
/examples/random_hist.py
1,151
3.5
4
#!/usr/bin/env python """ Random Histogram ================ This module plots a random histogram using the ATLAS Style. .. literalinclude:: ../examples/random_hist.py :lines: 12- """ from __future__ import absolute_import, division, print_function import ROOT as root from atlasplots import atlas_style as astyl...
544d131948f0580166fee32c23c6c936795fb419
Kelsey2018/Algorithm_2020HIT
/algorithm/quickSort/main.py
3,207
3.640625
4
# -*- coding: utf-8 -*- # @Author: Xiang xi # @Date: 2020-05-05 10:32:35 import random import copy import random import time import math def quickSort(A,p,r): if p < r: q = rand_partition(A,p,r) quickSort(A,p,q-1) quickSort(A,q+1,r) return A def swap(A,i,j): temp = A[i] A[i]...
025ec86f422233e500aeaf2b9c6f6432db4585b4
ssanusi/Data-Structure
/Stack/Python/Stack.py
574
3.90625
4
class Stack(object): def __init__(self): self.data = [] self.count = 0 def push(self, item): self.data.append(item) self.count += 1 def pop(self): if self.count == 0: return "Stack is Empty" data = self.data[-1] del self.data[-1] ...
933e0974e486a9710bb592955f206300485b798f
CodeupClassroom/bayes-python-exercises
/pandas_exercises.py
5,254
3.75
4
import numpy as np import pandas as pd from pydataset import data ## Exercise 1 # On average, which manufacturer has the best miles per gallon? # How many different manufacturers are there? # How many different models are there? # Do automatic or manual cars have better miles per gallon? mpg = data('mpg') mpg["mpg"]...
0fbfa0dc00e79f42281e3829b339f181bc801cd1
jmcq89/code
/ProjectEuler/Project Euler 12.py
506
3.796875
4
from math import sqrt def factors(n): fact=[1,n] check=2 rootn=sqrt(n) while check<rootn: if n%check==0: fact.append(check) fact.append(n/check) check+=1 if rootn==check: fact.append(check) fact.sort() return fact def triangleFactors(max): n=6 triangle=2...
799e4ea0240a9b0a49f66d7cd959dc1b4132a221
jmcq89/code
/ProjectEuler/Project Euler 67.py
607
3.5
4
def _reduce_triangle(to_reduce): last_row=to_reduce[-1] for index in xrange(len(to_reduce)-1): to_reduce[-2][index]+=max(last_row[index:index+2]) del to_reduce[-1] def find_max_sum(triangle): while len(triangle)>1: _reduce_triangle(triangle) return triangle[0][0] def _parse_triang...
448e960d5310146600fcd81d8210ba68c5071fa1
dknitk/programs
/python/projects/KWPythonSample/KWHelloWord.py
404
3.890625
4
num1 = input("Enter the first Number:") num2 = input("Enter the first Number:") result1 = int(num1) + int(num2) result2 = float(num1) + float(num2) print(result1) print(result2) cordinates = (4, 5) print(cordinates[0]) print(cordinates[1]) def sayHi(): print("Hello") sayHi() # Function and class declarati...
dc8cd70b3df76eec86889021b5d8ca1bf329b79f
webclinic017/machinelearning
/Artificial_Intelligence_with_Python/legacy/chap_6.py
564
3.53125
4
import sys def logic_programming(option=1): if option == 1: ''' Matching mathematical expressions ''' print("Example: I say Hello world") pass elif option == 2: ''' Validating primes ''' pass elif option == 3: ''' Parsing a family tree ''' pass e...
1b2f0f743c907d65b09cebaa80561cb3fb920ef3
pinruic/CSC361
/lab3/smtpclient.py
1,939
3.609375
4
from socket import * msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = "smtp.uvic.ca" portnumber = 25 # Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET, SOCK_S...
840b38a9c037abbe972948fe8facd628b05c1617
nishthabhatia/bmi210_final_project
/app.py
7,019
3.6875
4
from owlready2 import * #Load the ontology and present the introduction. def setup(): #Load the existing ontology onto = get_ontology('ProjectOntology.owl') onto.load() convo_running = True #TO DO --> ADD COLOR! header = """ ███████╗██╗████████╗███╗ ██╗███████╗███████╗███████╗ ██╔════╝██║╚══██╔══╝████╗ █...
7ffcf00691eee8175109679f13106cc2f9e72497
rafajob/Python-beginner
/ordenada.py
324
3.671875
4
def ordenada(lista): fim = len(lista) for i in range(fim): pos = i if len(lista) != 1: for j in range(i + 1, fim): if lista[j] < lista[pos]: return False else: return True else: return True ...
5409cb2ddb690e2bdc967850ca25651155358714
rafajob/Python-beginner
/contanumero.py
173
3.875
4
numero = int(input("Digite o valor de n: ")) soma = 0 while (numero != 0) : resto = numero % 10 soma = soma + resto numero = numero // 10 print(soma)
8be521fba75c13d82fe0e3715c432ea3d0402293
rafajob/Python-beginner
/adjacente.py
282
4.09375
4
numero = float(input("Digite um numero: ")) teste = 1 teste2 = 0 while (teste != teste2) and (numero != 0) : teste = numero % 10 numero = numero // 10 teste2 = numero % 10 if teste == teste2: print("Adjacente") else: print("Não Adjacente")
255e13684231f6258958b6da62ff4a8548a13ac0
Olumuyiwa19/aws_restart
/Moisture_Estimator_Script.py
1,665
3.78125
4
#This code estimate the Yes = True while Yes: Grain_Type = str(input("Enter the type of your grain: ")) Wg = float(input("What is the weight of your grain? ")) MC_Wg = int(input("what is the moisture content of your wet grain? ")) MC_Dg = int(input("what is your desired final moisture content for the ...
776209f54c8a436bcde8099db7e82855cc7a6adf
sureshpodeti/Algorithms
/dp/slow/no_of_subsets_to_sum.py
972
3.703125
4
''' Given a weight array 'A'. we need to figureout no.of subsets of elements in 'A' will sum up to weight't' psudo code: brute-force algorithm: 1. Let f(A, m, t) (where m =|A|) denote no_of solutions 2. we can pick any element from the A and check if how many solutions it forms, or how many solut...
12f63228c0b4b788891c84edb85d49ef248090c8
sureshpodeti/Algorithms
/dp/efficient/maximum_sum_path_divisibilty_condition.py
708
3.6875
4
''' Maximum path sum for each position with jumps under divisibility condition: Given an array of n positive integers. Initially we are at first position. We can jump position y to position x if y divides x and y < x. The task is to print maximum sum path ending with every position x where 1 <= x <= n. Here position ...
0306359920877c74481047b9a0c113f04392e5ce
sureshpodeti/Algorithms
/dp/efficient/min_edits.py
3,043
3.625
4
''' Given string s1, and s2 . we have following operations each of same cost: 1. insert 2. remove 3. replace we can perform above three operations on string s1 to make it string s2. eg: s1 = Geek , s2= Gesek Here, we should insert s into s1 to make it s2. so we need 1 operation. hence, a...
f3953a4b15af2cef12066243c8c760dfe7b5ae61
sureshpodeti/Algorithms
/dp/efficient/longest_increasing_subsequence.py
609
3.953125
4
''' Given an array, we need to return the length of longest increasing subsequence in that. eg: A = [50, 3, 10, 7, 4, 0,80] The idea is, if we know the longest increasing subsequence which at index i. can we found LIS which ends at i+1 ???? Yes, we need to follow the below algorithm to do that. time ...
2f133b9e5687578ca73e329c24c3197512b7d790
sureshpodeti/Algorithms
/dp/slow/min_steps_to_minimize_num.py
740
4.15625
4
''' Minimum steps to minimize n as per given condition Given a number n, count minimum steps to minimize it to 1 according to the following criteria: If n is divisible by 2 then we may reduce n to n/2. If n is divisible by 3 then you may reduce n to n/3. Decrement n by 1. brute-force solution: tim...
b451c8b81268bfa225e669f9532971a2a6ebf3d9
sureshpodeti/Algorithms
/dp/slow/longest_sum_contiguous_subarray.py
719
3.71875
4
''' Longest sum contigous subarray: Given an one-dimensional array. we need to find the logest contigous subarray which gives the maximum sum eg: A = [a,b,c] brute-force algorithm: Generate and test a1= [a] a2= [a, b] a3= [a,b,c] b1 = [b] b2 = [b,c] c1 = [c] so, we need to return th...
f7b05c070eb88efe3ea889c2d77647a6e9cf6b4d
sureshpodeti/Algorithms
/dp/slow/min_cost_path.py
1,157
4.125
4
''' Min cost path: Given a matrix where each cell has some interger value which represent the cost incurred if we visit that cell. Task is found min cost path to reach (m,n) position in the matrix from (0,0) position possible moves: one step to its right, one step down, and one step diagonally ...
70d8adee68755bbc2b792c471c2ce8bd0aa04205
oway13/project-presentation
/WebScraper PYTHON3/hearthpwn_scraper.py
4,806
3.5
4
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import re import json def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML,...
b1173a7eeb9e3fffefa507594125fea06e7a5a74
zhangli1229/gy-1906A
/demo/day-03/tupel.py
209
3.6875
4
#列表和元组的区别 #1.元组中只有一个数据的时候,后边必须带一个逗号,列表就不需要 a = [1] b = (1,) print(a) print(b) #2.元组中的数据不可修改 # a[0] = 2 # print(a)
25bd2d75157436ba58f2a472ee71080438a28c25
hiyamgh/Forecasting-Demand-Primary-Health-Care
/initial_input/helper_codes/data_subset.py
5,111
3.625
4
from pandas import DataFrame import pandas as pd import numpy as np import os.path import sys sys.path.append('..') from initial_input.helper_codes.data_set import DataSet class DataSubset: def __init__(self, df): self.original_df = df def copy_df(self): return self.original_df.copy(deep=True...
48f13070c13aa87c81d705e51481278336cf1c19
hossainlab/statsandpy
/book/_build/jupyter_execute/descriptive/m3-demo-01-ReadingFromAndWritingToFilesUsingPandas.py
2,348
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().system('python --version') # #### Installation of pandas # In[2]: get_ipython().system('pip install pandas') # In[3]: get_ipython().system('pip install numpy') # #### Installation of matplotlib # In[4]: get_ipython().system('pip install matpl...
72b8750a3c41dca8a93cea4edc0cb704fb79b175
ertugrul-dmr/automate-the-boring-stuff-projects
/comma-code/comma-alt.py
366
3.71875
4
# Another variation to automate the Boring Stuff With Python Ch. 4 Project spam = ['apples', 'bananas', 'tofu', 'cats', 'coconuts'] def comma(items): # Combines list into a string of the form item1, item2, item 3 and item 4 if len(items) == 1: print(items[0]) print('{} and {}'.format(', '.jo...
8f83e4e958303fca9387b8697e8a9f83c38356e3
ertugrul-dmr/automate-the-boring-stuff-projects
/spreadsheet-cell-inverter/inverter.py
538
3.90625
4
# A program to invert the row and column of the cells in the spreadsheet. import openpyxl inputwb = openpyxl.load_workbook('produceSales.xlsx', data_only=True) inputSheet = inputwb.active maxRow = inputSheet.max_row maxColumn = inputSheet.max_column outputwb = openpyxl.Workbook() outputSheet = outputwb.a...
c6e2d36b530c166448f12701ef4017d89b1667b4
ertugrul-dmr/automate-the-boring-stuff-projects
/rockpaperscissors/rockpaperscissors.py
2,665
4
4
# This is a game tries to simulate rock, paper, scissors game. import random import sys def maingame(): # Start's the game if player chooses to play. wins = 0 losses = 0 draws = 0 while True: # Main loop print(f'Wins: {wins}, Losses: {losses}, Draws: {draws}') if wins ==...
ffd91a476007794992ffedccc592bbc3685c864a
themaddoctor/BritishNationalCipherChallenge
/2020 special edition/forum/gantun/encrypt.py
987
3.609375
4
#!/usr/bin/env python # based on Gantun from https://susec.tf/tasks/gantun_229621efd1dcc01ef8851254affd1326887ec58e.txz #from random import randint randint = [] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def encrypt(p): global randint numbers = [] for char in p.upper(): numbers.append(alphabet.inde...
c6c138a068df67112091256c4491e3ea2b539a39
blairg23/files-in-folder
/files_in_folder.py
15,406
3.78125
4
#-*- coding: utf-8 -*- ''' Description: Checks existence of files from one given folder in the other given folder. - If the left folder is larger than the right folder, it will return the filenames and hashes of the remaining files. - If the right folder is larger than the left folder, it will return a True if all fil...
99226eef5a94c5a5394dc4d6cb645b7334d271a0
cs-summercrew/Summer19-SeedSystems
/OpenCV-Examples/Image Detection/cam.py
4,474
3.546875
4
# Authors: CS-World Domination Summer19 - CB ''' Simply display the contents of the webcam with optional mirroring using OpenCV via the new Pythonic cv2 interface. Press <esc> to quit. NOTE: Key bindings: g: BGR->RGB f: vertical flip d: horizontal flip esc: quit ''' import cv2 import numpy as np c...
cb2cab044509d2dc344c4a3faa162ef432233bdc
brendon977/programas_Python
/imc_comstatus.py
1,335
4
4
#Desenvolva uma lógica que leia o peso e altura # de uma pessoa, calcule seu IMC e mostre seu status #de acordo com a tabela abaixo: #-Abaixo de 18.5: Abaixo do peso # Entre 18.5 e 25: Peso ideal #25 ate 30: Sobrepeso #30 ate 40: Obesidade mórbida #Validação de dados inclusa valid_peso= False while valid_peso == ...
037f40f144c471fe6ac96b6ac387d2ff2d6eb242
brendon977/programas_Python
/jogo_jokenpo.py
1,599
3.921875
4
#Crie um programa que faça o computador #jogar jokenpo com voce. from random import randint from time import sleep # para colocar timer no programa valid_jogador = False itens = ('Pedra', 'Papel','Tesoura') computador = randint(0,2) print('''Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA''') while valid_jogador == Fals...
c41b853bc0869c6cbda8438edbbed46954673d47
Ping-ChenTsai417/Astroid-impact-armageddon-itokawa-acse4
/armageddon/Optimisation.py
4,854
3.671875
4
import scipy.interpolate as intpl import pandas as pd import matplotlib.pyplot as plt import numpy as np ''' Optimization problem ''' def meteor_data(file): """ The given results of the meteor event. Parameter ----------- file: file path """ data_csv = pd.read_csv(file) df=pd.DataFrame(dat...
7afbbb718239098a4f64aacab5efd56b45c27370
u-ever/JavaScript_Guanabara
/aula14ex/ex017/testetabuada.py
109
3.703125
4
mult = int(input('Digite um número: ')) for c in range (1,11): print(f'{mult} x {c} = {mult * c}') c += 1
e8019a0d7da90f1633bd139a32ca191887b08c10
naroladhar/MCA_101_Python
/mulTable.py
1,074
4.125
4
import pdb pdb.set_trace() def mulTable(num,uIndexLimit): ''' Objective : To create a multiplication table of numbers Input Variables : num : A number uIndexLimit: The size of the multiplication table Output Variables: res : The result of the product return value...