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
e88e50426cddacc96bb640509467d154d3a479cf
G0nov4/Programacion
/Python/Codeforces/4A_Watermelon.py
288
3.71875
4
n = int(input()) if n % 2 == 1 or n==1 or n==2: print('NO') elif (n/2) % 2 == 0: print('YES') else: s = (n/2)+1 s1 = (n/2)-1 if (s+s1)==n and s % 2 == 0 and s1 % 2 == 0: print('YES') else: print('NO')
db2ef3de811092b4553f42147f277492ec2c3c80
G0nov4/Programacion
/Python/Algoritmia/Metodo_de_Seleccio.py
642
4.15625
4
''' Ordenamiento por seleccion Es un algoritmo que consisite en ordenar los elementos de manera ascendente o desendente Funcionamiento: -Buscar eldato mas pequeño de la lista - Intercambiarlo por el actual - Seguir buscando el mas pequeño de la lista - Intercambiarlo por el actual - Esto se repite sucesivamente ''...
56a7bbd4a6c39c59e1411429a9dd9a3e2e5ab274
G0nov4/Programacion
/Python/UrionlineJudge/1010_Calculo_Simple.py
181
3.5
4
producto_1 = input().split() producto_2 = input().split() total=int(producto_1[1])*float(producto_1[2])+int(producto_2[1])*float(producto_2[2]) print('VALOR A PAGAR: R$ %.2f'%total)
2c84b0a5917d0243d439af8981280fb55a1f6400
fealho/practice-codes
/beginner.py
1,094
3.953125
4
from sys import stdin #Prints the number of necessary leds to implement a number, #where each number needs a certain amount of leds according to the list: #[6, 2, 5, 5, 4, 5, 6, 3, 7, 6] #param: x string with the number to be converted #return: num of LEDs to implement the number def numLEDs(x): LEDperDigit = [6, 2,...
caf7c9846f720f7ba7e528ba510a64719db787dc
tianyuemylove/yue
/p1月.py/suanshu.py
664
3.59375
4
print("欢迎使用小唯 计算器") def jia (a,b): c = a+b return c def jian (a,b): c = a-b return c def cheng (a,b): c = a*b return c def chu (a,b): c = a/b return c a = int(input("请输入数字>>")) while True: d = input ("请输入 + - * / ") if d == 'q': print (d) break b = int(inp...
4d78de1218488474f9ae572c48e680b45de47e80
tianyuemylove/yue
/p1月.py/weixin.py
288
3.65625
4
while True <= 5: def lll(user,passwd): a = input("请输入用户名:") b = input ("请输入密码:") if user == a and passwd == b: print ("欢迎进入,登录成功") else: print ("请重新输入") lll("tian",123)
f3b290d99444aec84c1fefd9e500ed894fc52b72
tianyuemylove/yue
/p1月.py/mingpian3.py
845
3.5625
4
listt = [] def cc(): print('*'* 40) print('欢迎使用名片管理系统 v1.0') print('1.新建名片') print('2.显示名片') print('3.查询名片') print('4.删除名片') print('5.退出系统') print('*'* 40) cc() ''' def vv(): print('请输入姓名>>') print('请输入公司>>') print('请输入年龄>>') print('请输入电话>>') print('请输入性别>>') prin...
4aa7184a79a5b28186ff3dc1a4f5f01264d62b53
kd1726/Data-Structures
/Arrays/Static_Array.py
818
3.671875
4
import ctypes class StaticList: def __init__(self,size=10): self.n = 0 self.size=size self.array = self._make_array(self.size) def length(self): return self.n def get_item(self,index): if not 0<index<self.size: return "IndexError(Index is out of range)" ...
32be980f66ee4cf0a600dab113e4a33b420a6678
kushalbhola/MyStuff
/Practice/PythonApplication/LeetCode/Array/448.py
452
3.640625
4
def main(): input = [1,1] output = findDisappearedNumbers(input) print(output) def findDisappearedNumbers(nums): if len(nums) == 0: return [] hash = {} for n in nums: if n in hash: hash[n] += 1 else: hash[n] = 1 output =[] for i in range(1,...
d2da14c79691ffc684481d9e37bbdcc4cf93eb09
kushalbhola/MyStuff
/Practice/PythonApplication/LeetCode/Array/977.py
327
3.609375
4
def main(): input = [-4,-1,0,3,10] output = sortedSquares(input) print(output) def sortedSquares(A): newArr = [] for a in A: newArr.append(abs(a)) newArr = sorted(newArr) output = [] for n in newArr: output.append(n * n) return output if __name__ == '__main__': ma...
01807a39d4beda122de756c6c5f262e8767b9116
kushalbhola/MyStuff
/Practice/PythonApplication/PythonApplication.py
455
3.53125
4
def tri_recursion2(k): if(k>0): a = tri_recursion2(k-1) result = k + a print(result) else: result = 0 return result #print("\n\nRecursion Example Results") #tri_recursion2(6) import json with open('google-resp.json') as json_file: data = json.load(json_file) s = '' for row in data['reports']: ...
46afa89ab63505e4782ad5e9e848d6ec34c674b6
1816357/Homework-2
/Lesson 2 Homework.py
2,708
3.859375
4
# Lists # # myList = [5, "Salah", [3,4]] # 0 1 2 # print(myList) # print(len(myList)) # # myList = [5, "Salah", [3,4]] # newList = myList + [10, 34] # newList.append("Hello") # newList.insert(2, "Mohamed") # newList.insert(2,"Ahmed") # newList.extend(["One", "Two", "Three"]) # newList.extend(["Four",...
2f70cff296def38a06a422a7ae87b4bb6be46e0f
turtlefish/Sokoban
/Warehouse.py
4,604
3.671875
4
import os import MapReader import platform class Warehouse(object): def __init__(self, player_start, goals, game_map): self.player_x = player_start[0] self.player_y = player_start[1] self.goals = goals self.game_map = game_map # [y][x], y before x def __str__(self...
39b37bb21f69b4ea7cbc158a29897f7a59103796
zekeo/fun_times
/Icanreadyourmind.py
961
4.09375
4
import random import time guess = (random.randint(0, 100)) print("I bet I can read your mind. Pick a number up to 100!") time.sleep(1) print("I need a little help though: please respond with higher, lower, or correct (or h, l, or c).") time.sleep(1) print("do you have your number?") time.sleep(2) print(guess) h = "h...
34a4f522caf4276a1f91c2dc7c5e55bdeebeb998
stijnnaus/advent_of_code_2020
/day3.py
1,114
3.828125
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 3 20:19:21 2020 @author: stijn """ def readTreeMap(): fname = "input/input_day3.txt" with open(fname,'r') as f: treeMap = f.read().split() return treeMap def countTreesInDescent(treeMap, stepSize): stepRight, stepDown...
718f1ba4cc9e1aeaa46944e0ac16c2b4290a20d5
thminh179/TruongHoangMinh-Fundamental-C4E18
/Session 5/Homework/2.py
357
3.921875
4
number = [1, 6 ,8, 1, 2, 1, 5, 6] #with count() # n = int(input("Enter a number: ")) # count = number.count(n) # print ("{0} appears {1} time(s) in my list".format(n, count)) #without count() n = int(input("Enter a number: ")) count = 0 for i in number: if (i == n): count += 1 print ("{0} appears {1} t...
095828eeba11c66985b72b2b83f3f4402e3ab17a
thminh179/TruongHoangMinh-Fundamental-C4E18
/Session 5/Homework/3.py
272
4.0625
4
bacteria = int (input("How many B bacterias are there? ")) time = int (input("How much time in minutes will we wait? ")) if time % 2 != 0: time = time - 1 replicate = bacteria * time print ("After {0} minutes, we whould have {1} bacterias".format(time, replicate))
ba36a964c8dfffc1fe5a02f44e5a8001c72d45b7
AnchalChandraGupta/labAssignmentSolution
/labs/py3/decorators/memoize_extra.py
2,109
3.859375
4
''' >>> f(2) CALLING: f 2 4 >>> f(2) 4 >>> f(7) CALLING: f 7 49 >>> f(7) 49 >>> f(9) CALLING: f 9 81 >>> f(9) 81 >>> f(7) 49 >>> f(2) CALLING: f 2 4 >>> g(-6, 2) CALLING: g -6 2 4.0 >>> g(-6, 2) 4.0 >>> g(-6, 2) 4.0 >>> g(6, 2) CALLING: g 6 2 -2.0 >>> g(6, 2) -2.0 >>> g(-6, 2) 4.0 >>> g(12, -2) CALLING: g 12 -2 5.0 >...
d0f9648fbcb88141bba1cb89544380e867062f4b
AnchalChandraGupta/labAssignmentSolution
/TrelloComprehensionExercises/linuxtopia3.py
576
3.8125
4
def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: try: initializer = next(it) except StopIteration: raise TypeError('reduce() of empty sequence with no initial value') accum_value = initializer for x in it: accum...
e88f09ddae400b60460ef0cc06017a66fc0ea53e
ventureit/HW5
/hw5p8.py
2,762
3.921875
4
import numpy as np import matplotlib.pyplot as plt def make_weights_for_fx(): # this is a random f(x) line function. Creates the d=2 weight vector for f(x) from the random two points selected. #Returns: a tuple 2-items tuple representing (intercept, slope) point1 = np.random.uniform(-1, 1, (1, 2))[0] ...
92ff136dd79023e86dcb70631d9bd5c149c1af13
andrei-radu/ECCPR-Python
/cenzura/cenzura.py
453
3.59375
4
#citire text=input() n=int(input()) cuvinte=[] #vector pentru cuvintele ce trebuie cenzurate lin=input() lin=lin.split() for element in lin: cuvinte.append(element) #prelucrare i=0 for cuvant in cuvinte: cenzura='' for litera in cuvant: cenzura+='*' #pentru fiecare litera din cuva...
c2e9f88ac093a8ef1a68623e97ee115973701bc8
andrei-radu/ECCPR-Python
/aranjamente produse/aranjamente produse.py
393
3.734375
4
from math import factorial #citire [k,M]=input().split() #prelucrare def Aranjamente(n,k): #suprogram care returneaza nr de Aranjamente return factorial(int(n))/factorial(int(n)-int(k)) n=int(k) maxim=0 while Aranjamente(n, k)<=int(M): #cautam nr maxim care respecta conditia if Aranjamente(n,k)<=in...
19d70c7e86f6d2d38f363dbe7984c0839a5b5236
andrei-radu/ECCPR-Python
/autogara/autogara.py
597
3.546875
4
def FormOra(ora): #subprogram care transforma ora in int ora=ora.split(':') return 100*int(ora[0])+int(ora[1]) #citire OraSosire=input() OraSosire=FormOra(OraSosire) n=int(input()) Autobuze=[] for i in range(n): linie=input().split() if FormOra(linie[0])>OraSosire: linie[0]=FormOra(...
8ea491080c3b37d1042d9d0021aa574d827740f7
barathkumarking/calculator-Tkinter-python
/calculator tkinter-python.py
1,357
3.5625
4
from tkinter import * from tkinter import messagebox window=Tk() window.title("Calculator") window.geometry('550x310') l1=Label(window,text="Enter the first value: ") l1.grid(column=1,row=1,padx=10,pady=10,sticky="W") e1=Entry(window,width=20) e1.grid(column=2,row=1,padx=10,pady=10) l2=Label(window,text="Ent...
bca0013607d8c4c32231a5c3db2f4436a9ecf788
Andy-Lv/Python-Learning
/06_语法进阶/04_多值参数.py
446
3.9375
4
# 参数名前加“*”可以接收元组 # 参数名前加“**”可以接收字典 def demo(num, *nums, **person): print(num) print(nums) print(person) demo(1) demo(1, 2, 3, 4) # num=1,其他的是元组 demo(1, 2, 3, 4, name="xiaoming") # num=1,其他的数字是元组,最后是字典 # 多值参数求和 def sum_num(*args): num = 0 for n in args: num += n return num result ...
d233873392cb5b776f7541488464c8c2604aebe0
Andy-Lv/Python-Learning
/04_高级数据类型/02_元组.py
275
3.984375
4
info_tuple = ("zhangsan", 18, 1.75) print(info_tuple[0]) # 取值 print((info_tuple.index("zhangsan"))) # 取索引 print((info_tuple.count("zhangsan"))) # 统计计数 for my_info in info_tuple: print(my_info) print("%s的年龄是%d,身高是%.02f" % info_tuple)
5b8cf851dff26a603f872f81058b0846e8582fa4
Dhruvin1/covid19
/random_walk.py
1,299
4.1875
4
from random import choice import settings class Randomwalk(): """ A class to generate random walks.""" def __init__(self, x=0, y=0): """Initiate attributes of a walk""" # All walks start at (x,y) self.is_infected = False self.x_values = [] self.y_values = [] s...
2cdc5ce6d4f8b267368670bae41fc5bb04eb626c
dxt5754/Python-Labs
/Lab02-master/src/sunstar.py
3,057
4.34375
4
""" CSapx Lab 2: sunstar.py A program that draws a pattern in the turtle window using recursive techniques $ python3 sunstar.py The side length and levels are gotten from standard input. author: Dean Trivisani """ import turtle import math def draw_side(length, level, angle): """ Draws a side of a sunstar...
51cc341c93b44eb0aa93579c371e99894b1e6552
VNOpenAI/Algorithm
/day1/ex.py
2,287
3.625
4
''' 1. Cho danh sách học sinh lớp A biết chiều cao và cân nặng của n bạn học sinh, sắp xếp danh sách học sinh theo thứ tự tăng dần chiều cao, trong trường hợp chiều cao bằng nhau thì sắp xếp theo cân nặng ''' from sort import CustomSort import numpy as np def sort_height_weight(arr): # repeat n-1 iter fo...
e3834d36d33cbd2df23adcd18dce777b96086b86
VNOpenAI/Algorithm
/day7/quicksort.py
521
3.578125
4
def quicksort(a,first,last): i=first j=last k=a[(i+j)//2] while i < j : while a[i] < k : i+=1 while a[j] > k : j-=1 if(i<=j): a[i],a[j]=a[j],a[i] i+=1 j-=1 if(i<last) : quicksort(a,i,last) # i với cuối if(j>first) : quicksort(a...
e48483a32ee379e8de092773619d3d7ee9d01698
fahedworks-24x7/Socket-Quiz-Python
/server.py
8,183
3.625
4
import socket import sys import time import select Questions=["1. Which city is situated on two continents?","2. Which continent is most populous?","3. Which country is the second biggest in the world?","4. Which country in the European Union has the biggest population?","5. Which is the largest capital city in the wo...
1ae3472874cb07a390a0cbad1ac7d27c44dccc2b
hseling/hseling-api-universal-dependencies
/hseling_api_universal_dependencies/conllu_parser.py
4,837
3.5
4
class Sentence: def __init__(self, blokk): self.spans = {} # keyed on the first token in the span self.empties = {} # keyed on the token in the span self.tokens = [] # only legit tokens ... 11-tuple or list self.comments = [] # list of comments for line in blokk.split('\n'): if line == '': continue i...
168506d24d0179f048ae3ad24bbfa90085d064a4
Matvakama/PYTHON_iSA
/Day6/Day_6_Homework/Homework_Training.py
2,116
3.671875
4
# 1: Obliczanie czy rok jest przestępny. def calc_step_year(): rok = int(input("Podaj rok (w cyfrach): ")) if rok % 4 == 0: return f"Rok {rok} jest rokiem przestępnym." else: return f"Rok {rok} nie jest rokiem przestępnym." # 2: Czy da się narysować trójkąt? def check_triangle(): a = i...
59305ff5094a45353752bb9b94a80e8a4be4a9e0
Patiphan60/TestCodium
/TestCodium3.6.py
815
3.75
4
# 3.6 numbers = int(input("Enter a number : ")) spaceAB = numbers - 1 space_in = -1 part_one = numbers for row in range(part_one): txt = "" for space_A_do in range(spaceAB): txt += "A" txt += "+" for space_inside_do in range(space_in): txt += "E" if row > 0: txt += "+" ...
a09d58137acb0d8e6e8b2597f692e8935a250d24
PallaNagadevi/dsp-programs
/matrix_multiplication.py
1,035
3.984375
4
def matrix(m,n,a,b): r = []; columns = [] for i in range(0,m): r += [0] for j in range (0,n): columns += [0] for i in range (0,m): r[i] = columns print (r) g = []; t = [] for i in range(0,a): g += [0] for i in range (0,b): t += [0] for i in range (0,a): g[i] = t print (g) ...
76500fc60fa112c262a5bdb07ce4dbf58253b52e
sammykol83/UdacityDataScienceNanoDegree
/ETL pipeline final exercise/ipynb.py
11,769
4.09375
4
#!/usr/bin/env python # coding: utf-8 # # Final Exercise - Putting it All Together # # In this last exercise, you'll write a full ETL pipeline for the GDP data. That means you'll extract the World Bank data, transform the data, and load the data all in one go. In other words, you'll want one Python script that can do...
35d5d060f6e0d2db5971a5a3938634aa45cd7adc
yurenwang/Leetcode-Solutions
/850. Rectangle Area II.py
2,634
3.5
4
class Solution: def rectangleArea(self, rectangles: List[List[int]]) -> int: # Line sweep # Imagine we have a horizontal line starting from the x axis, and moving upward. For each line at height y, we # calculate the total width of covered area, and add it to the result. For each rectangle...
ac788d99d961ffe18412c2f3d314ae521ecc4754
dbielecki21/Python
/movie_tickets.py
320
3.953125
4
prompt = "\nHow old are you? " prompt += "\nEnter 'quit' when done " while True: age = input(prompt) if age == 'quit': break elif int(age) < 3: print("That ticket will be free") elif (int(age) >= 3) & (int(age) <= 12): print("That ticket will be $10") elif int(age) > 12: print("That ticket will be $15"),
c33f9796bfa3a4a37f3c65be27154a8d2532a597
dbielecki21/Python
/guest.py
105
3.6875
4
name = input("Whats your name? ") filename = 'guests.txt' with open(filename, 'w') as f: f.write(name)
edc7f17229bf668f311110a1e6998cb81905d585
dbielecki21/Python
/pizza_toppings.py
250
3.859375
4
prompt = "\nWhat toppings would you like on your pizza? " prompt += "\nPlease type 'quit' when you are finished " while True: toppings = input(prompt) if toppings == 'quit': break else: print(toppings.title() + " will be added to the pizza")
e1fcfa405f7c0e2e2eb90e7924a80a75595f56e2
wesley-smith/mllib
/loaders.py
4,290
3.5
4
"""Data loading routines Sources: - https://www.valentinmihov.com/2015/04/17/adult-income-data-set/ """ import os import glob import numpy as np import pandas as pd from sklearn.datasets import fetch_mldata from sklearn.preprocessing import LabelEncoder def load_adult(preprocess=False): df = pd.read_csv( ...
d22d27eddc509404b4e15a97edee44d2eaac8330
Shiven004/learnpython
/Numbers/fibonacci_value.py
585
4.46875
4
#!/usr/bin/env python3 # Fibonacci Value # Have the user enter a number # and calculate that number's # fibonacci value. def fib(x): """ Assumes x an integer >= 0 Returns Fibonacci value of x """ assert isinstance(x, int) and x >= 0 n_1, n_2, i = 1, 1, 2 while i <= x: n_new = n...
1497b105f9f9c9572b4865dc9c6969f0ac2f4329
kkraft7/Scripts
/InterviewProblems/Rentrack/intersect.py
1,118
3.9375
4
#!c:/python2.4.1/python.ex # # intersect.py: # 1. What does the code below do? What is its big-O performance? # 2. Re-write the code. What is the big-O performance of your solution? # Toy Problem #4 from Rentrack # # 1. This code returns the intersection of lists a and b. # It's big-O performance is O(n^2) def who_...
6a2935736edafb3a5c187763f3c6217afc61ca0a
mauro39ar/Programacion_1
/primer cuatrimestre/unidad_2/ejercicio_6.py
130
3.84375
4
#!/usr/bin/python leia=input("ingrese numero: ") if leia % 6 == 0: print "es divisible" else: print "no es divisible"
36ff02c135595e396e48d1603276ec1aeb221d9f
jacobastern/radio-denoiser
/data_collection/data_utils.py
838
3.796875
4
from datetime import datetime import os def get_file_path(genre, dest, audio_type, ending): """Generates a valid path for a song name. Args: genre (str): the genre of music dest (str): the destination for the song files audio_type (str): the type of audio (['radio', 'stream']) e...
04b8789692ce0274401697ceb7a5ecc2a44ce030
JakeTheLion89/portfolio
/Python/word_scram.py
2,507
4.125
4
# July 23 # Learning python # Excercise in "random" module import random def wordScram(): print """Welcome to Word Scram. Choose a difficulty and unscramble 10 words! """ ## Game Dictionaies and Variables game = { "EASY" : ["night", "quill" ,"book", "wine", "grass", "fill","quilt","kind","public"...
1d2d2af275af57b22917fc9133c344dbf6dae9ad
chesterqualls/DS_Class
/Python Code Assignments/Assign12dot2.py
477
3.75
4
# Note - this code must run in Python 2.x and you must download # http://www.pythonlearn.com/code/BeautifulSoup.py # Into the same folder as this program import urllib #import BeautifulSoup from BeautifulSoup import * url = raw_input('Enter - ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html)...
e65b1655038a394d172d4c420effd563196f983d
ItzShekhawat/Holidays_System_HomeWork_2020
/Liste_Cap10/Ex_10/find_word.py
1,756
4.03125
4
""" Esercizio 10.10. Per controllare se una parola è contenuta in un elenco, è possibile usare l’operatore in, ma è un metodo lento, perché ricerca le parole seguendo il loro ordine. Dato che le parole sono in ordine alfabetico, possiamo accelerare l’operazione con una ricerca binaria(o per bisezione), che ...
f8f9c14e677540c46d9ed35100c6f10167adb041
ItzShekhawat/Holidays_System_HomeWork_2020
/Liste_Cap10/Ex_07/Lista_07.py
725
3.84375
4
""" Esercizio 10.7 Scrivete una funzione di nome ha_duplicati che richieda una lista e restituisca True se contiene elementi che compaiono più di una volta. Non deve modificare la lista di origine. """ def ha_duplicati(li): for index in li: count = 0 for i in range(len(li)): ...
f30ee406e79c53ed3fa0def53e05a8d4b1602118
ItzShekhawat/Holidays_System_HomeWork_2020
/Exercise/Dizionari_Cap11/Ex_03/Ex_03_Diz.py
478
3.890625
4
""" Esercizio 11.3. Applicate la memoizzazione alla funzione di Ackermann dell’Esercizio 6.2 e provate a vedere se questa tecnica rende possibile il calcolo della funzione con argomenti più grandi. """ # La risposta è no!! def Ackermann(x, y): if x == 0: return y + 1 elif x > 0 and ...
387be8509e6cc6ed91ac3d60a1ec7bfa1bfaddf0
MiguelSenChi/IntroPython
/IngresoValores.py
261
4
4
#nombrevariable = input('mensaje') nombre = input('Ingrese el nombre: ') edad = int(input('Ingrese la edad: ')) estatura = float(input('Ingrese la estatura: ')) print('Hola mi nombre es: {}, tengo {} años y mido {} metros'.format(nombre,edad,estatura))
0685c2c83bb8136e74b08667ac7e73ad86269eb3
ParthShinde2004/PythonChallenges
/RandomPseudocodeQuizGenerator.py
3,110
4.03125
4
import datetime import string import random import time #Important Variables and Constants Lives = 5 Score = 0 Boolean = "TRUE", "FALSE" RandString = random.randint(2,10) #Actual Quiz Game def game(): RightWrong = 0 Question = random.choice(Choice) print(Question) Answer = input("What is the data type? (all l...
2f4a3ce85d1d9838e603945a68f020568ee60069
ParthShinde2004/PythonChallenges
/RomanNumeralConvertor.py
1,304
4
4
"""This is a Roman Numeral and Integer converter that can convert number from roman to denary and back from 0-3999""" RomanValues = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, } def roman_to_int(str): total = 0 i = 0 while (i < len(str)): s1 = RomanValues[str[...
5d6afa46a2c08a8462aa5f63ad54e2ee53e5e784
YHGui/CS61ASp18
/Lab/lab01/falling.py
331
4.15625
4
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 """ sum = 1 while k > 0: sum = sum * n k = k - 1 n = n - 1 ...
d908eefb00b653616712bccca564ee4e4b4aee3b
YHGui/CS61ASp18
/example/Lab06/ex.py
444
3.546875
4
class Bear: """A Bear""" def __init__(self): self.__repr__ = lambda: 'oski' self.__str__ = lambda: 'this bear' def __repr__(self): return 'Bear()' def __str__(self): return 'a bear' oski = Bear() print(oski) print(str(oski)) print(repr(oski)) print(oski.__str__()) print(oski.__repr__()) def repr(x): r...
d14df0a00cf5c88d9d398263546c7eb3c536e5a4
Quoly/Algorithms_from_Coursera
/Week 7/min_weight_sum_diff.py
1,650
3.546875
4
def merge_inverse_sort(array): if len(array) == 1: return array middle = len(array) // 2 return merge_inverse(merge_inverse_sort(array[:middle]), merge_inverse_sort(array[middle:])) def merge_inverse(array1, array2): infinity = 10000000 array1.append(infinity) array2.append(infinity) i1 = 0 i2 = 0 merged_ar...
4183f9e1d1c5afe40a226770e4abe8149b0e8a4c
Quoly/Algorithms_from_Coursera
/Week 6/median_maintenance.py
969
3.53125
4
def partition(lst): global res length = len(lst) pivot = lst[0] k = 1 for i in range(1, length): if lst[i] < pivot: lst[i], lst[k] = lst[k], lst[i] k += 1 res += length - 1 lst[k - 1], lst[0] = lst[0], lst[k - 1] return (lst[:k - 1], [pivot], lst[k:]) def quicksort(lst): if len(lst) < 2:...
b97bf6788fb11ed82805b7b947708f9b04de774d
katzaz10/HackerRankSolutions
/Arrays/2DArray-DS/solution.py
422
3.75
4
def hourGlassVal(arr, x, y): #gets the value of an hourglass, based on the given x and y coordinates as the top-left most corner return sum(arr[y][x:x + 3]) + sum(arr[y + 2][x:x + 3]) + arr[y+1][x+1] def hourglassSum(arr): max = None for x in range(4): for y in range(4): sum = hour...
9f11c3e6a83b0d7a0e82fb2502fb4c3c2ae7d852
katzaz10/HackerRankSolutions
/StacksAndQueues/CastleOnAGrid/solution.py
2,182
3.5625
4
def rightmoves(grid, start_x, start_y, hit): '''finds all possible moves to the right''' moves = [] row = grid[start_x] for y in range(start_y + 1, len(row)): if not hit.get((start_x, y), False): if row[y] == 'X': break else: moves.append((...
ccdebc7b2dc593443b32343663ade9efe2bc5956
AntonioRoye/Beginner_Python_Projects
/madlibs.py
1,085
4.15625
4
adjective1 = str(input("Enter an adjective: ")) noun1 = str(input("Enter a noun: ")) verb1 = str(input("Enter a verb (past tense): ")) adverb1 = str(input("Enter an adverb: ")) noun2 = str(input("Enter a noun: ")) noun3 = str(input("Enter a noun: ")) adjective2 = str(input("Enter an adjective: ")) verb2 = str(input("En...
ec887e81201290aacc2a59f578388d11cb2d9301
Repidus/python-and-ruby
/Function/1.py
282
3.859375
4
def login(id): members = ["Albert", "Bethany", "Charles"] for member in members: if member == id: return True return False input_id = input("Enter the ID: ") if login(input_id): print("Welcome, " + input_id + "!") else: print("Who are you?")
c235ad0774ff10ece5f1f7e0c90f3c03a89a0d66
JessicaReay/compound_interest_app
/calc.py
541
4.25
4
# App: compound interest calculator # Fuction: calculates monthly compound interest for custom user inputs # Author: Dan & Jess def monthly_compounding(initial, monthly, years, annual_rate): sum = initial months = years *12 #iterate through months for month in range(int(months)): # apply annua...
762a6ea787bc48a3a2bdde25210ca6c6805caed9
dlxj/doc
/lang/programming/pytorch/Titanic生存率预测/titanic.py
1,487
3.59375
4
""" https://zhuanlan.zhihu.com/p/53176091 """ #导入包 import numpy as np import pandas as pd import os #导入数据 train = pd.read_csv("./data/train.csv") test = pd.read_csv("./data/test.csv") # 训练数据集大小: (891, 12) # 测试数据集大小: (418, 11) print('训练数据大小:',train.shape) print('测试数据大小:',test.shape) # 训练数据比预测数据多了一列:即标签"result" print...
233fb4ec86a38e68c205d04fb521b84854657bc8
porcobosso/ToyCode
/推荐系统实践代码/3.3/SelectProduct.py
2,373
3.625
4
# coding=gbk ''' ѡûƷ >3Ϊϲ ''' import pandas as pd import numpy as np import copy #ȡֶ def getDiff(userRates,movie): like=dict() dislike=dict() unknown=dict() likeArray=[] dislikeArray=[] unknownArray=[] for user,ratings in userRates.items(): if movie not in ratings: ...
fa321adeb4befac49d8af6007d4bbec9bdbe3782
asmuelle/UdemyTF
/Chapter2_Python/ListIterating.py
749
3.8125
4
#### Schleifen (für Listen) in Python #### noten = [1, 1, 3, 4, 5, 6, 2, 1] for i in noten: print(i) print("\n") # len(noten) = 8 # range(8) for i in range(len(noten)): print(noten[i]) print("\n") noten = [1, 1, 3, 4, 5, 6, 2, 1] fächer = [ "Mathe", "Deutsch", "Englisch", ...
4c94da2f965d99e1930a5c56ed2e25fe7d1ac92c
stellakaniaru/bootcamp
/assignment/loop.py
198
3.71875
4
f = [(10, 20, 40), (10,40), (4, 5, 50)] ''' x:10, y:20, z:40 x:10, y:40 ''' for i in f: if len(i) == 3: print "x : {}, y : {}, z : {}".format(*i) else: print "x : {}, y : {}".format(*i)
95ba9c78de1f6d7be74bba0ece2ec0d2710d70da
stellakaniaru/bootcamp
/day_3/data_types.py
765
4.3125
4
def data_type(x): ''' takes in an argument, x: -for an integer, return x ** 2 -for a float, return x/2 -for a string, return "hello" + x -for a boolean, return "boolean" -for a long, return squareroot(x) ''' #cheking for integers if type(x) == int: return x ** 2 #checking for float elif type(x) == float: ...
2e56ee5bb3cbcf43daeb4524d2c314904121953e
nienkelegemaate/rosemary.py
/bonus.py
1,222
3.890625
4
from kitchen import Rosemary from kitchen.utensils import Pan, Plate, Bowl from kitchen.ingredients import Flour, Egg, Milk, Butter, Salt def pancakes(number): #number of portions of pancakes #grab the bowl bowl = Bowl.use(name='batter') #add the ingredients (250 grams of flour, salt, 2 eggs, and 500 mL m...
82c3aafc7d1790b02b4f3dd7bbabce51df708820
MesutCevik/adventcalendarPython
/impl/CompetitorsList.py
1,334
4.15625
4
from typing import List from impl import Competitor class CompetitorsList: competitors: List['Competitor'] = [] def add_competitor(self, competitor: Competitor): self.competitors.append(competitor) def __str__(self) -> str: competitors_in_string: str = "" for competitor in self....
bb4fe780957251e8946d9dea16683f51281ed967
whiteice-c/Python
/BaseLearning/myTest/word_game.py
307
3.765625
4
print('first test---------word') temp = input("不妨想一下我现在在想的数字:") guess = int(temp) if guess == 8: print("我擦,你是我心里的蛔虫么!?") print("哼,没有意思。") else: print("猜错了,我现在想的数字是8") print('---------end------------')
11c584a27e7e2032e091d94b62af615c613b953c
whiteice-c/Python
/BaseLearning/myTest/hanoi.py
280
3.9375
4
#汉诺塔问题 def hanoi(n,a,b,c): if(n == 1): print(a,'--> ',c) else: hanoi(n-1,a,c,b) hanoi(1,a,b,c) hanoi(n-1,b,a,c) n = int(input('请输入汉诺塔的层数:')) hanoi(n,'a' , 'b' ,'c')
490796b7222b883a0f124e05a5014380d914a649
whiteice-c/Python
/BaseLearning/myTest/fab_reverse.py
746
3.9375
4
#斐波那契数列 '''来源:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?   兔子的规律为数列 1,1,2,3,5,8,13,21,34,55,89,144.... 规律:前两个月兔子对数为1,从第三个月起,每个月的数量为前两个月的数量之和 ''' def fab(n): if(n < 1): print('输入的月份数值有误') return -1 elif(n == 1 or n == 2): re...
b87475dfc2aac8167f816ad58737346b10d5572e
Emilly-horta/Scraping-
/bs4/bsregex3.py
407
3.5
4
from urllib.request import urlopen, Request from bs4 import BeautifulSoup import re # Quero só os links do folha.uol do mês 11 de 2017, da categoria mercado html = urlopen("https://www.folha.uol.com.br/") soup = BeautifulSoup(html, "html.parser") links = soup.findAll("a", {"href":re.compile(".*\.folha\.uol\.com...
9468b0aeaafa8b633806cf59e7e66b276c14e9eb
Emilly-horta/Scraping-
/bs4/beautiful-aula5.py
1,383
3.671875
4
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://localhost:8080/site.html") soup = BeautifulSoup(html, "html.parser") # O método prettify "embelezar" organiza # o conteúdo do parser mostrando # uma árvore com as tags HTML/XML print("Veja o conteúdo com o prettify") pri...
0f422f4c600a755b0a958e9589135652ef3dc8ed
dagongji10/LeCode
/scripts/48.py
1,920
3.703125
4
""" Created on Sun Jan 12 14:39:14 2020 @author: 短腿伊斯科22 """ # -*- coding: utf-8 -*- ''' 题目: 将矩阵顺时针旋转90度 分析: (1)首先,顺时针旋转90度以后,元素的索引值是怎么变化的? 假设以矩阵中心((n-1)/2, (n-1)/2)为坐标原点,旋转前元素的位置为 (x,y),那么旋转之后的坐标应该是 (x, y) >> (y, n-1-x) (2)如何在原始矩阵上交换元素的值? 考虑按照一层层的方式交换,从最外层逐步向最里层发展,每次旋转时可以同时交换四条边上的对应元素(根据...
ce59057276bd2d704e7508be4a950e5b3f5894bd
dagongji10/LeCode
/scripts/1.py
478
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 26 09:59:21 2019 @author: Administrator """ def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i,num in enumerate(nums): other = target - num left = nums[...
a065f79b5cb0550b9ebf859d8faaa89bd2802df2
dagongji10/LeCode
/scripts/50.py
1,414
3.53125
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 17 15:03:14 2020 @author: Administrator """ ''' 题目: 计算 pow(x, n) 分析: (1)用递归:f(x, n)=x*f(x, n-1) (2)pow(3, 10)=pow(pow(3, 5), 2),启发:将 n 除以2,只需先计算 pow(x, n/2),然后将结果平方,减少递归的次数 (3)利用二进制:将 n 表示为二进制的形式,从低位到高位一步步计算 举例:pow(2, 10) 10 的二进制表示:1010,也就是说 pow(3,...
6da0b0accbfc368956e175abfc8956373d3c0299
juanmal/Puzzle8
/Puzzle.py
5,976
3.5
4
import copy class Puzzle: def __init__(self, args): self.matriz = [[0 for i in range(3)] for i in range(3)] self.profundidad = 0 self.padre = None self.coste = 0 self.x, self.y = 0, 0 i, j = 0, 0 if args is not None: for val in args: ...
c7d4d05a6be0cd48461ac1857e0b4b6bb929763e
KhoaVT/COP5930FAU
/EncryptDES_v01/ClassProcess.py
11,768
3.515625
4
import numpy as np from bitstring import* import binascii class KeyProcess(object): """ This class contain all the functions to process the key""" def ReadFile(self,filename): with open(filename) as file: array2d= [[int(value1) for value1 in line.split()]for line in file] TablePC =...
31f33cbd47d86ee1af3dc6f9bf1ecd0332409ae1
drewdoescode/bin
/hi
136
3.921875
4
#!/usr/bin/env python3 import colors as c print(c.red + ' what is your name? ') name = input('> ') print('hi nice to meet you',name)
d7361362370a04b4a36942d2b57916eec5b573da
amarjotgill/Python-mini-problems
/find_the_way.py
3,625
4.53125
5
""" File: find_the_way.py Author: Amarjot Gill Date: 11/16/2020 Lab Section: 44 Email: agill3@umbc.edu Description: This program will use recursion to check and see if their exist a way to exit the map from the starting location, it will keep track of places it has move with "x" """ import sys import r...
5de82f7599b605b218944455835ecc9f295d0e02
amarjotgill/Python-mini-problems
/files_and_folders.py
6,642
3.734375
4
""" File: files_and_folders.py Author: Amarjot Gill Date: 12/10/2020 Lab Section: 44 Email: agill3@umbc.edu Description: This program will use Classes to mimic the UMBC Gl server. It can create directories and files and navigate through them using cd. It can also write to files only if they are open. """ ...
d4ad647979d37fc90ff8ea4b1d6cd3c64ba66286
JRoehrig/caeli
/caeli/time_series.py
19,637
3.609375
4
import calendar import pandas as pd from datetime import datetime from dateutil.relativedelta import relativedelta # ======================= YEAR ================================================ def replace_year(dt, year): """Replace the year in ``dt`` by ``year``. If dt has the last day in the month, keep also t...
473728f070fdd1752579caa010f919cf414c69e1
Kawaiivee/CodingSnippets
/PythonSnippets/ReadWriteAppendExample/FileEditor.py
1,059
3.875
4
fileName = "data.txt" modeDict = {'r':'READ','w':'WRITE','a':'APPEND','r+':"READ+WRITE"} print("Enter mode: ", modeDict) fileMode = input() while fileMode not in modeDict: print("Enter a valid mode: ", modeDict) fileMode = input() print("Opening file in", modeDict[fileMode], "mode") try: print("Trying to open fil...
ddaae85b02c5386c0a03f1e6ba7dafce8da3a10a
Kawaiivee/CodingSnippets
/PythonSnippets/Classes/Person.py
3,147
3.78125
4
class Person(object): def __init__(self, fn="First Name", ln="Last Name", a="Age", g="Gender", i="ID"): self.firstname = fn self.lastname = ln self.age = a self.gender = g self.id = i def __repr__(self): return str(self.firstname + "/" + self.lastname + "/" + str...
29fb702ca521ab265d16d6c45d223074d614bf85
dipenR/Boston-housing-analysis
/Summary.py
704
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 5 23:28:00 2020 @author: Dipen Rupani """ import numpy as np import pandas as pd import statsmodels.api as sm from sklearn.model_selection import train_test_split boston = pd.read_excel('BostonHousingData.xlsx') # loading in the data X = pd.DataFrame(np.c_[boston['IND...
3e044bc20aef927db191accae171047ce7b3840f
ondreali/module11
/employee.py
2,918
4.03125
4
""" program: Inheritance Author: Ondrea Li Last date modfied: 07/5/20 The purpose of this program is to write information about employee """ class Employee: def __init__(self, lname, fname, addy, phone): ''' :param lname: represents last name :param fname: represents last name ...
d7e4d9ab154364d4e344d95a9ebbb68124ecb616
epictomkat/RockSniffer-GuessingGame
/lib/RockSniffer_GuessingGame.py
1,960
3.5
4
import time class GuessingGame(object): def __init__(self, log, storage): super(GuessingGame, self).__init__() self.Log = log self.Storage = storage self.Running = False self.Completed = False self.Guesses = list() self.StartTime = time.time() self...
133ac2ed1c2c6ae51d7fe00739269ecd6e62f361
Enmin/Coursework
/Data1050/final-exam/5.py
607
3.96875
4
def parent(i, n): # time complexity O(1): space: O(2) # return None if it is the root # else track the children by index in the mathematical formula if i == 0: return None elif i // 2 == 0: return (i-2) / 2 else: return (i-1) / 2 def left_child(i, n): # time complexi...
45b76220c7a14e663f9ddf6c1a7aaa27af964433
Enmin/Coursework
/CS1430/homework2_localimagefeatures-Enmin/questions/plot_corners.py
1,176
3.53125
4
""" This code adapted from scikit-image documentation http://scikit-image.org/docs/dev/auto_examples/features_detection/plot_corner.html For CSCI1430 @ Brown University Spring 2019 """ """ ================ Corner detection ================ Detect corner points using the Harris corner detector and determine the subpi...
b876964433707b9b30ea18c60f771e09750eda3b
Enmin/Coursework
/CS1430/homework5_cnns-Enmin/code/models.py
7,371
3.6875
4
""" Project 4 - CNNs CS1430 - Computer Vision Brown University """ import tensorflow as tf from tensorflow.keras.layers import \ Conv2D, MaxPool2D, Dropout, Flatten, Dense, BatchNormalization from tensorflow.python.keras.layers.core import Activation from tensorflow.python.keras.layers.pooling import GlobalAverage...
5c5350dede6d5eff6119c0665f5e4128736f9ad8
amrit999/LeetCode
/203-Remove Linked List Elements.py
836
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode ...
ab0a9bc482e0034a83e008318732b818c757aa0b
smreferee/Lame-Game
/Lab2_Richard_Nolan.py
823
4.34375
4
################################################ #This is Lab 2 for COSC 1336 by Richard Nolan # #The program will display program information, # #ask and display the user name, display a menu,# #and finally confirm the menu choice. # ################################################ #Introduction to...
2ff7c2cc27c224f6f16ac6edad5bbbd83677521e
mritunjaysingh07/visualization_matplotlib_project
/q04_plot_runs_by_balls/build.py
391
3.53125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt def plot_runs_by_balls() : ipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None) plt.scatter((ipl_df.delivery.apply(np.int64))*10, (ipl_df.total.apply(np.int64))*10) #plt.title('NYC House pricing') plt.xlabel('Count of Balls P...
1877755ebb80d480bf4ca792eaa7a057b06f5578
shanwenqian23/Samples
/Analytical Modeling/pulp linear optimization.py
8,673
3.90625
4
# -*- coding: utf-8 -*- # Homework 11 - ISYE 6501 # Part 1 ---------------------------------------------------------------------- # Formulate an optimization model (a linear program) to find the cheapest diet # that satisfies the maximum and minimum daily nutrition constraints, and solve # it using PuLP. Turn in ...
0479d33117fff1c877c2f3d1d533b68ffa1b0b8b
pjeje323/Coding_Practice
/2016.11.21.py
887
4
4
# -*- coding: utf-8 -*- # 2016-11-21 # Find the Difference! # Given two strings s and t which consist of only lowercase letters. # String t is generated by random shuffling string s and then add one more letter at a random position. # Find the letter that was added in t. # EX) input : s = "abcd", t = "abcde" / out...
63088646bb6ab40b906be8ed928b07443c6817bd
pjeje323/Coding_Practice
/2016.11.18.py
1,067
3.703125
4
# -*- coding: utf-8 -*- # 2016-11-18 # 1. 첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제 def print_stars(x): for i in range(1,x+1): print '*'*i print_stars(5) # 2. 첫째 줄에는 별 N개, 둘째 줄에는 별 N-1개, ..., N번째 줄에는 별 1개를 찍는 문제 def print_stars_reverse(x): print '*'*x if x-1 == 0: return '*' ...
a8342b4ca7b22ffd40ccf7a341b705a5fae9afd8
pisalsaurabh/PythonProject
/Main.py
4,918
3.890625
4
from __future__ import print_function import random import os def fullboard(board): x=0 for pointer in xrange(1,10): if board[pointer]!=' ': x+=1 if(x==9): return True else: return False # from IPython.display import clear_output def sp_choose_sym...
f11845068cd5de1c652f69398b0fa0e8ae5c226d
weirichd/ProgrammingClass
/bool.py
233
3.640625
4
bool1 = False bool2 = True bool3 = True bool4 = True if not bool1: print('Dinosaurs') if bool2: print('Pizza party!') if bool1 and bool2: print('I think this is just fine.') if bool3 or bool4: print('Ok!')
833d9556349aea107c70427066feef47892274c6
weirichd/ProgrammingClass
/mistake.py
245
4.0625
4
name = input("what is your name? ") if name == 'David': print('Hey') elif name == 'Paul': for i in range(10): print(i) print('Blastoff!') else: print('Ok') for d in range(19): if d == 8: print('It is 8')