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
6a5a91c53f9c774410242c4140adba9634af99fd
jarehec/holbertonschool-webstack_basics
/0x01-python_basics/105-best_score.py
374
3.890625
4
#!/usr/bin/python3 """ module containing best_score function """ def best_score(my_dict): """ returns a key with the biggest integer value @my_dict: dictionary with integer values """ if my_dict is not None and len(my_dict) > 0: val = max(my_dict.values()) for k, v in my_dict.items...
e90cfacd47c60099592b03dba2948da5dca2d141
jarehec/holbertonschool-webstack_basics
/0x01-python_basics/101-print_diagonal.py
261
4.15625
4
#!/usr/bin/python3 """ module containing print_diagonal function """ def print_diagonal(n): """ draws a diagonal line @n: integer:q """ if n <= 0: print() else: [print(' ' * i + '\\') for i in range(n)] print()
41d7bcfc6333eb08c436b8682aaa3a398a3f20bb
banmedo/WumpusWorld
/src/agent.py
1,476
4
4
class Agent: """This is the Agent that will traverse through the environment. His goal is to pick up the gold and climb out. """ # The names mapping array of facing to directions __DIRECTIONS = ["N", "E", "S", "W"] # starting parameters for a new agent arrows = 1 gold = False facing...
763426755133108ea2269ce9cc4f6db3e2d573dc
diffusioned/Python-Code
/Scipy NLLS Curve Fit Demo.py
9,767
3.5625
4
# Scipy NLLS Curve Fit Demo.py by Ned Charles, February 2020 # An example Python script that walks through how to do a nonlinear, least squares (NLLS) regression fit on simulated data. # Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit ###########...
e2640b0ce44677802b3244e8c0acfb82af4cce6f
Manovah/guvi
/code kata/count_num_of_digits_in_an_integer.py
59
3.5625
4
x=int(input()) y=0 while (x>0): y=y+1 x=x//10 print(y)
1ffd05791c72509f72a502560c9dd10fe7e8bd9d
albertopeces2000/Ejercicios
/Ejercicio1.py
1,101
3.78125
4
lista_nombres = ['Alberto','Maria','Estela','Celia','Carla','Alicia','Ainhoa'] lista_datos = [[500,100,1400],[153,345,974],[298,8974,4540],[123,3490, 30],[2343,34,504],[1609,56,500],[1056,98, 950]] dict_datos = dict(zip(lista_nombres,lista_datos)) print(lista_nombres) nombre = input('Introduce el nombre de un tra...
9dd9e8c4d359049f4e2a62973d36447259ef0f97
kinoanh/thuhong-fundamental-c4e21
/session1/homework 1/area.py
88
3.90625
4
r = int(input("What is your radius? ")) p = 3.14 area = p * r ** 2 print("Area=", area)
a81db6e82d2570876b487af136d136809752c311
browngirlangie/Unit3LEsson16
/Problem 1/problem1.py
2,128
3.875
4
import random import time print() print('*' * 100) print("A wild Eevee appears!") print() time.sleep(1) print('You only have one Pokemon, Squirtle.') print() time.sleep(1) squirtle_hp = 300 eevee_hp = 100 print(">> squirtle has " + str(squirtle_hp) + " HP.") print(">> eevee has " + str(eevee_hp) + " HP.") print()...
efe33f122768ef7fd8c149225f0be649b37546d6
thamvmk/csm-language-translation
/split_long_text.py
1,539
3.71875
4
#!/usr/bin/python3 def split_long_text( content ): "This prints a passed info into this function" import re print ("content = %s" % content) m = re.split(r'(?<=[^A-Z].[.?]) +(?=[A-Z])', content) sentences = [] t_ele = 0 max_words = 20 for i in m: print (i) t_ele = len(s...
8f1203462ef5a263f507e383c094dff76f9230ee
gamerkhang/Infx122-Board-Game-Server
/test/newclient.py
1,480
3.5
4
import socket import sys HOST, PORT = "localhost", 9999 # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to server and send data sock.connect((HOST, PORT)) print("::CONNECTION SUCCESS\n") # get player information--change this ...
4ca28cd48dfe13785f6941eca312680dd84b1448
pixelperfect3/PyOpenCLBezier
/method2.py
5,937
3.625
4
################### ## This is a simple PyOpenCL example ## ## The purpose is to evaluate Bicubic Bezier surfaces on the GPU, ## AUTHOR: Shayan Javed ## import sys import pyopencl as cl from numpy import * import numpy import time # Global variables degreeU = 0 degreeV = 0 detail = 0.0 # class definition begins he...
6e82d06f1d1e74573a41141beab75e43f7c3c94c
matias-hc/ayudantia-paradigmas
/ejercicios_ayudantia-2020/mati_ejer/2020-08-13/problem1.py
8,319
3.640625
4
# Tenemos dos opciones, guardar las aristas como matrices o como lista de adyacencia, # para esta implementacion se hara algo asi como un mixto, con listas de adyacencias # pero para cada vertice, en un diccionario con la key siendo cada vertice y la lista # el value correspondiente, por lo que se recorre por vertice-k...
91127bb8a227de3872000800c5c3911ea4b6426b
amaurirg/Lives_Edu
/Testes/teste_com_unittest02.py
665
3.84375
4
from unittest import TestCase, main def eh_par(val): return True if val %2 == 0 else False def eh_bool(val: int) -> bool: """ Função que verifica se o número é par. Arg: - val: Valor de entrada do tipo inteiro. """ if isinstance(val, int) or isinstance(val, float): return True if val % 2 == 0 else False ...
67a4df24261fe1f11c95358a728d4942191f809f
Shamaun-Nabi/Basic-Problems-
/Lab test 2/myfriendschoices.py
715
3.5625
4
def generateCommonChoices(filename1,filename2): file1=open(filename1) file2=open(filename2) friend1_lines=file1.readlines() friend2_lines=file2.readlines() #remove new line from friend 1 for i in range(len(friend1_lines)-1): friend1_lines[i]=friend1_lines[i][:-1] #remove new line from ...
b689d8c576b9731b116d987bb1282437803f63a9
onatsahin/ITU_Assignments
/Artificial Intelligence/Assignment 2/block_construction_constraint.py
2,980
4.125
4
#Onat Şahin - 150150129 - sahino15@itu.edu.tr #This code include the Block class and the constraint function that is used for the csp problem. #This code is imported from csp_str_1.py and csp_str_2.py which create the model and solve the problem. blocklist = [] #A list that holds block objects. Filled in the other co...
d2aa15a46c7cd6fde2fe4f9708b2b5ac7f5fdf45
onatsahin/ITU_Assignments
/Signal and Systems/Assignment 3/q3.py
1,046
3.75
4
# # Onat Şahin - 150150129 # Question 3 code # The code is mostly taken from https://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/ # Comments and explanations are written by me # import numpy as np def FFT(x): """A recursive implementation of the 1D Cooley-Tukey FFT""" x = np.asarray(x, dtyp...
54286be87be487256cf4be862e4d196d3cddbc85
BrandonEkins/dailyPythonChallanges
/357KalakoskiSequences/357KalakoskiSequences.py
648
3.578125
4
number = input("input number") def flip(x): if x == 1: return 2 else: return 1 def KalakoskiSequence(x): kSequence = [1,2,2] kIterator = 2 flipper = 1 t = 3 while t != (x): if kSequence[kIterator] == 1: kSequence.append(flipper) ...
43975bc4c32874736c827dfa6f99728a32ce1c5e
BrandonEkins/dailyPythonChallanges
/321TimeChallange.py/321TimeChallange.py
789
4.03125
4
from datetime import datetime digits = ["oh", "one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","forteen","fifteen","sixteen","seventeen","eighteen","nineteen"] tens = ["","","twenty","thirty","forty","fifty"] hour = "" minute = "" def convertTime(currentTime): if cur...
923cdef82eb7369f51b6c9507d1c117b193c6546
walkerzjs/COMP9321_Group_Project_TwoTier_DataAnalysis_Platform
/Data_mashup_application/happiness_ranking_by_country/models/happiness_ranking_model.py
790
3.765625
4
import requests # year is str type # year must be in [2015, 2016, 2017] # returns the data dict which can be directly converted back to DataFrame. def get_happiness_by_year(year): url = 'http://127.0.0.1:1234/api/world_happiness/' + year response = requests.get(url) if response.status_code == 200: ...
35df74429dfbfd6877a37517c41aad1aee7b9046
ankita2002/Digital-Cororna
/Digital Corona.py
392
3.515625
4
import turtle t = turtle.Turtle() s = turtle.Screen() s.bgcolor('white') t.pencolor('red') t.pensize(10) a = 0 b = 0 t.speed(1) t.penup() t.goto(0,200) t.pendown #if(ASA()==True): # ASA() def ASA(): global a,b t.forward(a) t.right(b) a=a+3 b=b+1 #if b==210: #...
c33f48f59ea648b26ce0246b7bae046cde444160
thomasplantin/Pyvity
/settings.py
1,847
3.53125
4
import pygame import math import constants class Ball: def __init__(self, color=(0, 0, 0), center=(400, 250), radius=20): self.color = color self.center = center self.radius = radius def draw(self, window): pygame.draw.circle(window, (0, 0, 0), self.center, self.radius) ...
e3384ef38a44ff7d60fef8f76068f250b266790a
Sdeepak2017/Pythonrepo
/for.py
179
3.875
4
str='Hello World' count=0 findChar = 'h' for i in range(len(str)): if(str[i].lower()==findChar.lower()): count+=1 print('number of iterations ' + findChar + ' char is ', count)
c78df01237ffc36f9aabdbf35f686c0cd79a7910
vipulx44/Spoj-problems
/fact.py
157
3.609375
4
n=int(input()) for i in range(n): v=int(input()) if v==0: print(1) fact=1 for j in range(1,v+1): fact=fact*j print(fact)
aad463df3a10da98bf9fba7dbd6217eec1be79b2
vipulx44/Spoj-problems
/rt.py
396
3.875
4
import random a=int(input("Enter Lower Bound: ")) b=int(input("Enter Higher Bound: ")) val=int(input("Enter your Value:")) print("Your Value is %s" % val) while True: guess=int((b+a)/2) inp=input("Is the value %s? : " % {guess}) if inp=='Yes' and val==guess: print("I am the best") break ...
2f3d0d0c819ec10a80cd7cfd8c27d1b2ab64205e
johndoe133/SAheartdisease
/graph.py
1,078
3.59375
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import dataextraction X = dataextraction.X attributeNames = dataextraction.attributeNames df = dataextraction.df N, M = X.shape # 0: sbp, 1: tobacco, 2: ldl, 3: adiposity, 4: famhist, 5: typea # 6: obesity, 7: alcohol, 8: age, 9: chd # Select whi...
c80546f56dc950ef8f9f4f698d65e53d51335c28
jumpingtheshark/ttt_py
/victory_vertical.py
384
3.6875
4
board = [["*","#","$"],["*","#","$"],["*","#","$"]] game_over=False def all_same (cells, symbol): rval = True for i in range (0,3): if cells[i] != symbol: rval = False return rval #check columns l=[] for i in range (0,3): l=[] for j in range(0,3): l.appen...
be68435e3e2cb97f8f405b141d13f5dfe75864d4
CreativePhilip/applied-computer-science-discord-bot
/applied_computer_science_discord_bot/permissions.py
1,366
3.671875
4
from discord import Message, Member def has_role(role): """ Method for performing permission checking :param role: string or a list of strings representing a role name """ def _has_role(func): def wrapper(self, *args, **kwargs): msg: Message = kwargs['message'] auth...
38afe21e867218487dccdc7c71ee3211f111ced6
pritesh-1998/Automations
/excel_operations/excel_op.py
1,164
3.6875
4
import openpyxl # Creation of workbook object # openpyxl.workbook() wb=openpyxl.load_workbook(r"C:\Users\plath\Documents\programming codes\Python automations\Automations\excel_operations\sheet.xlsx") #print sheets name print(wb.sheetnames) data_sheet=wb["Sheet1"] # accesing the cells # here a=column and 1=row number ...
1abc7c75753f9b76efc7af9c0a1508c9343baa7d
pat-hare/Udacity_AI_Trading_Momentum
/Momentum_Trading/test_stat_significance.py
803
3.703125
4
import pandas as pd import numpy as np import scipy.stats as stats def analyze_returns(net_returns): """ Perform a t-test, with the null hypothesis being that the mean return is zero. Parameters ---------- net_returns : Pandas Series A Pandas Series for each date Returns -...
476281dd140d01995c39816be64f4687cee83748
KenyStev/Metodos_Numericos_1erParcial
/punto_fijo.py
466
3.875
4
from math import * def f(x): return eval(ecuacion, {'x' : x}) ecuacion = raw_input('Ingrese la funcion a resolver: ') p0=float(raw_input('Introduce el valor de inicio p0: ')) tol=float(raw_input('Introduce el error ')) n0=int(input('Ingrese el maximo de iteraciones a realizar: ')) i=1 while i<=n0: p=f(p0) if abs(...
d3ccd818dd34bb0e2f5de58390d83fa936747b34
nikraina/python
/inheritance.py
435
3.546875
4
__author__ = 'nikhil' class parentClass: def setName(self,name): self.name = name def getName(self): print self.name class childClass(parentClass): pass class childClass2(parentClass): def getName(self): print "this is child class 2" print self.name obj = childClass()...
a9e7012dba42f79ed68733bb358ded2086b178ac
nikraina/python
/basic_class.py
267
3.6875
4
__author__ = 'nikhil' class sampleClass: name = "" age = 0 def printInfo(self): print "printing from class method" print self.name print self.age obj = sampleClass() print obj.age obj.name = "python" obj.age = 22 obj.printInfo()
28e3113c08178de77a32b8427346880f8479536e
huginngri/TitleTraveler
/V2.py
1,563
3.921875
4
def possiblem(x , y): attir = "(S)outh (N)orth (W)est (E)ast" s, n, w, e = attir.split() if y == 1: return n + "." elif x == 1: if y == 2: return n + " or " + e + " or " + s + "." if y == 3: return e + " or " + s + "." elif x == 2: if y == 2: ...
41eec34b60ce8f0152543d9464e064039a974cae
sebutz/python101code
/Chapter 4 - Conditionals/conditionals.py
2,148
4.34375
4
# a simple if statement if 2 > 1: print("This is a True statement!") # another simple if statement var1 = 1 var2 = 3 if var1 < var2: print("This is also True") # some else if var1 > var2: print("This should not be printed") else: print("Ok, that's the good branch") # -1 -----0 ----...
6c1ebad77338e686a2648f145f18b34b6c8c90ff
sebutz/python101code
/Chapter 10 - Functions/10_6_pkw_func2.py
263
3.609375
4
def mixed_function(a, b=2, c=3): return a+b+c # call the function with one argument and 2 keyword arguments res1 = mixed_function(1, b=4, c=5) print(res1) # call the argument with just the required argument res2 = mixed_function(1) # b =2, c = 3 print(res2)
f3c2e49c47f8c3c1b9d1fcd8c17f28aaf620beae
jeffersonchaves/Python
/lista01.py
8,427
4.21875
4
# Faça um Programa que leia uma lista de 5 números inteiros e mostre-os. #MANEIRA 1 print('QUESTAO 01') lista = [1, 2, 5, 78, 9] print ('LISTA =',lista) print('\n') #MANEIRA 2 lista = [] for inicio in range (5): lista.append(int(input('Digite um numero:'))) print ('LISTA =',lista) '''----------------------------...
ca41c86dacec11153e25493e6b3d7473d53d4f5f
kanishkcoe/MLPractice
/gradientDescentmulti.py
1,971
3.8125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plot from sklearn import datasets def errorFunction(b, m, points, target): totalMterms = m * points y = target msum = totalMterms.sum() error = y - msum return error def compute_error_for_given_points(b, m, points): totalErro...
adb80a254149758b92a8f5ff1fb49000e00c43d4
jaimebunay/python_homework
/PyRamen/main.py
2,313
3.71875
4
# Lets import the libraries we will use from pathlib import Path import csv # Set file path to read menu and sales data from .csv files sale_data_path = Path("Resources/sales_data.csv") menu_data_path = Path("Resources/menu_data.csv") # Initialize and empty menu list menu = [] # Use with statement to open the file me...
55a3535a2143dd92318739d598099c10d1379a50
tClown11/Python-Student
/test/Python高级编程/all_is_object.py
285
3.6875
4
def ask(name="Clown"): print(name) class Person: def __init__(self): print("Clown1") def decorator_func(func): return ask my_ask = decorator_func(ask) my_ask('tj') obj_list = [] obj_list.append(ask) obj_list.append(Person) for item in obj_list: print(item())
71c113d7bed0252e2d73c95c3af0c323fcb55153
tClown11/Python-Student
/test/hanshu.py
192
3.5625
4
def test_name(): new_name = input("请输入您的名字:") print(new_name) def test_age(): new_age = input("请输入您的年龄:") print(new_age) test_name() test_age()
4f4028ebe38ac654f99b4f803a914458f13ab5a3
tClown11/Python-Student
/test/textday/imooc练习/reduce()函数.py
304
3.671875
4
#coding = utf-8 __author__ = "keynote" from functools import reduce #python内置了求和函数sum(),但没有求积的函数, 请利用reduce()来求积: #输入: [2, 4, 5, 7, 12] #输出2*4*5*7*12的结果 def prod(x, y): #print(x*y) return x*y print(reduce(prod, [2, 4, 5, 7, 12]))
fe6330c4f9c58a06e07d1744568b31808947f5b3
geekjeongjin/Python
/Module/5.py
146
3.71875
4
import auth input_id = input("Please input your ID.\n") if auth.login(input_id): print('Hello, ' + input_id) else: print('Who are you?')
e5b3ddadb3f252d05fc7aebf77ad5dd1da8c40ba
alercelik/Computer_Vision
/kodlar/3/canny.py
928
3.5
4
import cv2 import numpy as np import imutils image = cv2.imread("../images/example_02.png") image = imutils.resize(image, width=800) # resizing with imutils is much easier than OpenCV cv2.imshow("image", image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("gray", gray) canny_image = cv2....
195ba4bcaabba0c8e799dd5a344fa7d7e9817ae5
alercelik/Computer_Vision
/kodlar/3/corner.py
1,167
3.59375
4
import cv2 import numpy as np import imutils filename = "../images/chessboard.jpg" image = cv2.imread(filename) image = imutils.resize(image, width=600) # resizing with imutils is much easier than OpenCV gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = np.float32(gray) corner_image = cv2.cornerHar...
1d76d63c49fba58705754cb77cc6228a3bb891c0
isaiahb/youtube-hermes-config
/python_publisher/logs/logger.py
957
4.1875
4
"""This module creates a logger that can be used by any module to log information for the user. A new logger is created each time the program is run using a timestamp to ensure a unique name. """ import logging from datetime import datetime class Logger(): """Creates a timestamped log file in the logs/ directory a...
78aff1c52f20429b530a405cb9eeac1647c65e33
Quiltic/CS2021
/Week 5/Shake.py
1,765
3.953125
4
import random def random_tweet(table): #import random return construct_tweet(random.choice(table['.']), table) def shakespeare_tokens(path='shakespeare.txt', url='http://composingprograms.com/shakespeare.txt'): """Return the words of Shakespeare's plays as a list.""" import os from urllib.request ...
9e058b9cc499a5cf3fbde8669816cbc840c3a6da
a-l-orule/csc-201
/Orulebaja_prog_3#.py
5,803
4.125
4
#Abdul-Lateef Orulebaja #Program 3 #WHAT TO DO part 1 #TWO #2.1 sequence = "ACTGAT" #string used for executing mirror s = sequence #shorten variable for "sequence" to write more efficiently s = s.replace("A","x") #replacing for A and T s = s.replace("T","A") s = s.replace("x","A") s = s.replace("C","y") #replacing f...
9edbf7760f50590fed8ffdd8b4d20227dce22dc8
yr999/my-first-python-app
/app/my_mod.py
2,563
3.640625
4
# this is the "app/my_mod.py" file... # # We can define custom functions in a separate file (like this one), # ... and import these functions into other Python files (like my_script.py). # # The spreading of functionality into logically-related modules helps us stay organized when our apps become really big. # def t...
1fb0e4bdef7a759a36cee0d2706a9005fb7802a5
jk-jang/python
/Basic2/chap01_python_basic/step02_for_dict.py
989
3.734375
4
''' Created on 2016. 5. 26. list 내포 - list + for set/dict 자료구조 - set: {} -> 중복 data 불가능 - dict: {'key':'value'} ''' #1. list 내포 #형식 [결과값 for 변수 in 자료구조(list,tuple,set,dict)] #for문 예 values = [2,1,2,3,4,2] float_val=[] for v in values: float_val.append(float(v)) print(float_val) #...
0b8953dbaa9ba99c6d6dfc96944a8e049c328610
jk-jang/python
/Basic2/chap05_Pandas_DS/step02_DataFrame.py
3,041
3.6875
4
''' DataFrame 자료구조 특징 - DB Table과 유사한 자료구조 -> 서로 상이한 칼럼을 갖는다. - 2차원 행렬구조 갖는다. - python 기본 자료구조, Series, Numpy 이용 객체 생성 - R의 dataframe과 유사함 ''' import pandas as pd # 1. python 기본 자료구조 이용 객체 생성 # 1) list 객체 이용 name= ['홍길동','이순신','강감찬','유관순'] age = [35,45,55,25] pay = [350,450,500,250] addr ...
3ca9926ef1c98e197cdbabd8ef87b8f7322c26d1
dayyanobrien/stocks
/Combined/A453.py
21,292
4.0625
4
import math import sqlite3 import re totalprice = 0 #Sets the total price of the receipt to 0 since nothing has been bought yet db = sqlite3.connect(':memory:') db = sqlite3.connect('shop.sqlite3') #Creates a database named shop cursor = db.cursor()#Sets cursor for changing and creating tables around curso...
840f0d83d2996f40987f6408cd8350cd542fc76a
Ansen/Python_Learn
/readNwriteTextFiles.py
1,114
4.03125
4
'readNwriteTextFiles.py -- create and read text file' import os def CreateTextFile(): while True: fname = raw_input('Enter Filenane: ') if os.path.exists(fname): print "ERROR: '%s' already exists" % fname else: break all = [] print "\nEnter lines ('.' by its...
0fc0cb30a10f8cf8a76e842a4ade4af82ad49a78
Ansen/Python_Learn
/Hex2Ascii.py
397
3.890625
4
''' Hex convert to ascii''' import binascii def str2list(list): for i in range(0,len(list)-1,2): print '%s%s '%(list[i], list[i+1]), def Hex2ascii(char): value = [] for i in range(len(char)): b = binascii.b2a_hex(char[i]) b = chr(int(b)) value.append(b) return ...
759a5f83f7d7599c55c087bdbad1d2516d862866
Ansen/Python_Learn
/decorator.py
288
3.578125
4
def decorator(F): def new_F(a, b): print ("input:", a, b) return F(a, b) return new_F @decorator def square_sum(a, b): return a ** 2 + b ** 2 @decorator def square_diff(a, b): return a ** 2 - b ** 2 print (square_sum(3, 4)) print (square_diff(3, 4))
acc48f53571f3031f4658e73840d534ad7633d8d
ankit039/Competitive_Programming_Solutions
/Python/subtree_size_by_stack.py
1,424
4.09375
4
''' Calculate the subtree size of each node of a tree rooted at node 1 ''' import copy def calculateSubtreeSize(root, no_of_nodes): # Store size of subtree of each node 'i' subtree_size = [0 for _ in range(no_of_nodes + 1)] # Boolean array to check if a node is already visited or not visited = copy.co...
666550e421b1f5372dd3a5fab0c9cbce24a4ac4c
issasalman/math-series
/math_series/math_series.py
1,077
4.03125
4
# series=input(" Please enter fibonacci or lucas > ") # terms=int(input(" number in series>")) def fibonacci(n): """ The function was created to take number that its length of index given and it will start from 0 and 1 """ if n <= 1: return n else: return(fibonacci(n-1) + fib...
33a2f7dfce0555a052e5adc82b3e28f16357b117
amnlo/ML_Project
/final_zip/src/knn/helper_knn.py
11,840
3.5
4
# -*- coding: utf-8 -*- '''Helper functions for the KNN algorithm''' import pandas as pd import numpy as np import itertools from DataSciPy import splt_str from sklearn.preprocessing import OrdinalEncoder from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.model...
0c327acae12576e038d694f4ca6c2d2065483b1c
peter-gelgor/CreationCamp-Auto-Emailer
/calendar_stuff.py
3,256
3.5
4
from datetime import datetime, timezone CLIENT_SECRET_FILE = 'client_secret_file.json' API_NAME = 'calendar' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/calendar'] #gonna need to change this to whatever ur calendar id is, u can google how to get that #i don't think it'll necessairly be ur email, so ...
88db0c1b06e73c665c536913b3695210565824b0
kamoewa/pwmanager
/main.py
4,959
3.59375
4
from tkinter import * from tkinter import messagebox import random import pyperclip from datetime import datetime import json DARK_GREY = '#242424' GREY = '#bbbbbb' BEIGE = '#ffe3d8' # ---------------------------- PASSWORD GENERATOR ------------------------------- # def random_password(): letters = list('ABCDEF...
3b948550395fbea484b40c38e4c0fbccb1ad33d9
camcam1773/AI_ML_Lab2
/path_planning.py
7,144
3.703125
4
import random import numpy as np import matplotlib.pyplot as plt # sizeOfMap2D = [100, 50] # percentOfObstacle = 0.9 # random.randrange(70, 90)/100.0 # 30% - 60%, random # Generate 2D matrix of size x * y # starting Point and Ending Point def generateMap2d(size_, percentOfObstacle = 0.9): # Generates a random...
7f96180ad9a43fe47339286c0fc0105a5abb4a75
AngusP/Khepera-II-IAR
/astar_pseudo.py
1,258
3.5
4
# add starting cell to open heap queue heapq.heappush(self.opened, (self.start.f, self.start)) while len(self.opened): # pop cell from heap queue f, cell = heapq.heappop(self.opened) # add cell to closed list so we don't process it twice ...
c612b4a211b499b4aa59d0bcdb2a8ba5bd406d41
jbaniya/kattis
/kattis/reversebinary.py
114
3.640625
4
input = int( raw_input() ) bin_string = "{0:b}".format(input) reverse = bin_string[::-1] print int(reverse, 2)
6d01765852f6e4568557be02c4cf85d33d8ea4be
francocoin1701/pythonPOO
/serializacion.py
524
3.5625
4
import pickle # creamos un fichero con una lista de nombres lista_nombres = ["pedro","sorangel","patricia","lina"] fichero_binario = open("lista_nombres", "wb") pickle.dump(lista_nombres, fichero_binario) fichero_binario.close() del(fichero_binario) # leemos el fichero con la lista de nombres que se encuentra en ...
c3298fa7e323160b821295148c7e7094e9d47364
lradebe/simple_programming_problems
/largest_element.py
219
4.1875
4
def largest_element(mylist): largest_element = 0 for element in mylist: if element >= largest_element: largest_element = element print(largest_element) largest_element([1, 2, 3, 4, 5])
c474292678edf882a853a0a039bbf5467c794e3b
lradebe/simple_programming_problems
/prime_numbers.py
374
3.90625
4
def prime_numbers(number): primes = [] for num in range(1,number+1): if num > 1: for integer in range(2, num): if num % integer == 0: break else: primes.append(num) print(f'The following is a list of prime numbers derived f...
0177a475d7829b46e61a98456b99d438e3250bb8
lradebe/simple_programming_problems
/find_intersection.py
726
4.375
4
def find_intersection(Array): '''This function takes in a list with two strings \ it must return a string with numbers that are found on \ both list elements. If there are no common numbers between \ both elements, return False''' first = list(Array[0].split(', ')) second = list(Array[1].split(', ')) s...
75b3291d3896b4f1adca2395879097b999ebaa0c
lradebe/simple_programming_problems
/number_pattern.py
183
3.703125
4
def number_pattern(number): for num in range(number): print(str(num) * len(range(num))) print() if __name__ == '__main__': number = 4 number_pattern(number)
6de35e08005f4e36480fb649e1e7d97fec26a395
Wendy1127/data_practice
/20171116/func/func_3.py
1,279
4
4
#coding:utf-8 #无参数 #(1)列表 # print lambda :range(10) # # #有参数 # def a(x,y): # return x+y # print lambda x,y:x+y #遍历列表,然后每个元素乘方 def each_list(list1): sum=0 for item in list1: sum+=item**2 return sum #1.对于序列中的item顺序迭代调用function,并进行迭代运算(reduce)lambda x,y:x+y #2.对于序列逐个执行函数,并作运算并返回相应结果(map) each_li...
101f5cfb52139639fbed2060966ac85c3fffb330
Wendy1127/data_practice
/O2O-2-1122/re_2.py
1,023
3.75
4
#coding:utf-8 import re #(1) # string='hello world hello world' # pattern=re.compile(r'(\w+)+') # #匹配整个字符串,类似于match # result=re.search(pattern,string) # print result # if result: # print result.groups() # # # (2)split,以匹配到的内容进行字符串的切割 # string='hello world world' # pattern=re.compile(r'l') # result=re.split(pattern,...
563bc27cc6b692a6c54ba73278c89040cf9e3848
Wendy1127/data_practice
/20171114/if_3.py
685
3.65625
4
#coding:utf-8 #四则运算 #1.输入三个值 first_num = input(u'请输入第一个数字:') opa = raw_input(u'请输入+-*/任意一个符号') second_num = input(u'请输入第二个数字:') #2.判断符号 if opa =='+': print '%d+%d=%d' % (first_num,second_num,first_num+second_num) elif opa =='-': print '{0}-{1}={2}'.format(first_num,second_num,first_num-second_num) elif opa =='...
4fbcd6ccb8dd743b39ec8d7d14f61cfbe472f3e1
Wendy1127/data_practice
/20171115/fun_3.py
201
3.75
4
# coding:utf-8 # 不可更改参数 b = 2 def get_num(a): a = 10 get_num(b) print b # 可更改参数 list1 = [1, 2, 3] def set_list(list2): list2.append([1, 2]) set_list(list1) print list1
bded7b72b9f01f5c52a06d43d33b5e1fc772977d
Wendy1127/data_practice
/O2O-2-1122/re_1.py
699
3.875
4
#coding:utf-8 import re #python正则表达式模块 #生成一条正则表达式,匹配以h开头的字符串 # pattern=re.compile(r'^h*') # pattern=re.compile(r'^h+') # pattern=re.compile(r'^(h)+.*o$') # #匹配,match执行正则表达式的匹配,从开头进行匹配,匹配不到返回Null # result= re.match(pattern,'hello') # if result: # #使用mathch对象取得分组信息 # print result.group() # else: # print 'Nul...
9af96fdcefff455cf4f7e1056a1b7e30e11e74a7
EmmanuelDoumard/BDA
/BDA/Projet/vocabulary.py
6,899
3.734375
4
#!/usr/bin/python """ This file contains the defintion of the classes needed to store a vocabulary - only numerical attributes are considered in this version (values in the csv file casted to floats) """ import sys import os class PartitionElement: def __init__(self,lab,a,i,ia=1): self._label=lab self._attribu...
255c5dc5e974c9752d97e4e180cc84a20a1b38f4
GaloMaldonadoC/trabajo-en-clase
/ejer2.py
290
3.75
4
firstName= input("cual es tu primer nombre") lastname= input("Cual es tu segundo nombre") location= input("Donde se encuentra") age= input("cuantos años tienes") space=" " print("Hola"+space+firstName+space+lastname+space+"Estas en"+space+location+space+"y tienes"+space+age)
361d5439ded4c00ad770618c6c99cf927c8117a7
Harsh-Modi278/dynamic-programming
/Fibonacci Sequence/solution.py
534
4.3125
4
# Initialising a dictionary to store values of subproblems memo_dict = {} def fibonacci(n): # If answer to the nth fibonacci term is already present in the dictionary, return the answer if(n in memo_dict): return(memo_dict[n]) if n <= 2: return (1) else: # Store the answer to t...
c4e04a18e2bc139599c154b73c2d07e14407cc6c
duyt1001/SciFair2018
/test.py
1,028
3.734375
4
from random import * print('''TWENTY ONE 22222222222222222222222222222222222222222 Try to score 21 points!! (DUDE, ur supposed to be elatedly happy!) y''') playing = True score = 0 while playing == True: num = randint(1,10) score = score + num print("Here. Take it. It's ur new number!",num) print(...
414fda19233faa82b98704c15a5ca65a77d7c867
tanistra/data_generator_pyqt
/src/data_generator.py
873
3.65625
4
import random import string def generator(data_type, size, upper=True): if len(size) == 0: raise ValueError('Field length cannot be empty') size = int(size) choice_int = '' choice_str = '' choice_special = '' if data_type == 'str' or data_type == 'all': choice_str = string.asci...
c304bbb291d7c5cc518162a21fda30975d616c24
Bearlock/python
/ex2.py
1,713
3.703125
4
def charShift(c): # List of punctuation checked in the if statement, returns punctuation if true punctuation = ["!", "@", "#", "$", "%", "^", "*", "(", ")", ".", "?", "'", " ", ",", "/"] if c in punctuation: return c else: # ord() takes a character and returns its ascii value ...
8a3e3f0ce64dabbd2ba0438a0a960d6b54a3a37a
sisfm/scripts
/basket.py
5,159
3.71875
4
import copy stock={"PEN":["Lana Pen",5], "TSHIRT":["Lana T-Shirt",20], "MUG":["Lana Coffee Mug",7.5]} basket={} #Set empty Basket def addItem(basket,stock): error=None enterId=str(input("Enter id to buy: ")) if enterId in stock: if enterId in basket: ...
45810f12c10fbab18e76420e61fc91274a5603be
Supriya105/Python
/Desktop/PYTHON/assignment2.py
2,685
3.984375
4
#Task2 i=9 if i%3==0: print("Consultadd") if i%5==0: print("c") if i%3 == 0 and i%5==0: print("Consultadd Training") ##2nd question x=int(input("Enter any number between 1 to 5")) if x==1: first = int(input("Enter any number")) second = int(input("Enter an another number")) res = first+second ...
47e92c0e63a0106219e4cdfaef0782f084e367b6
imguf/game
/game_files/highscore_window.py
4,788
3.921875
4
from kivy.graphics import * from kivy.uix.label import Label class Highscore_window: """ this class describes how the highscore window will look like and function""" def __init__(self): """ constructor takes the width and height of the screen and sets the values to the argum...
2b1db4f0962841af5e7edb8fd75e0c7dd80c855c
greendwin/puzzles
/ProjectEuler/Task024_LexicographicPermutations.py
1,310
3.75
4
""" Problem 24. A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120...
8a10c2f8deae04cee1e3e6ad653c4190d7bf56b1
JavierRodriguezM/Tarea3
/Tarea3/texto.py
2,746
3.5
4
#!/usr/bin/python from tabulate import tabulate import time import argparse # Función: Recibe un txt y genera otro txt con una tabla que tiene la palabra y el # de veces que se repite # Entrada: txt # Salida: txt con tabla que contiene la palabra y el # de veces que esta se repite # Instrucción para inicializar el ...
4d62ef22b6c3b3510c07ddcf7611619139f7f776
josh-bridge/mr-ransom
/mrransom/cipher/caeser.py
1,751
3.734375
4
# Caesar Cipher (slightly modified) # http://inventwithpython.com/hacking (BSD Licensed) VALID_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ 'abcdefghijklmnopqrstuvwxyz' \ '0123456789+/=' ENCRYPT = 'encrypt' DECRYPT = 'decrypt' class CaeserCipher: def __init__(self, key): sel...
ff45174dacc0319d4cb1faa28984f5ed10cf6662
TheBrockstar/Intro-Python
/src/days-1-2/fileio.py
468
4.1875
4
# Use open to open file "foo.txt" for reading foo = open('foo.txt', 'r') # Print all the lines in the file print(foo.read()) # Close the file foo.close() # Use open to open file "bar.txt" for writing bar = open('bar.txt', 'w') # Use the write() method to write three lines to the file bar.write('''"To be, or not to...
ff240b8b428a120c813a019b415f482792b82cc0
nicholasroethel/MachineLearningCarPrice
/rfe.py
1,226
3.5625
4
#Recursive Feature Elimination and Logistic Regression to get the most important attributes import numpy import pandas from pandas import read_csv from sklearn.feature_selection import RFE from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler import warnings with open('LA...
f1acef2e2802c79c6ffd74b1b357fb84aeaf2d26
Kyrylo-Kotelevets/NIX_python
/Trainee/9.py
762
4.46875
4
""" создайте функцию-генератор, которая принимает на вход два числа, первое - старт, второе - end. генератор в каждом цикле должен возвращать число и увеличивать его на 1 при итерации генератор должен начать с числа start и закончить итерации на числе end т.е. при вызове for i in my_generator(1, 3): print(i...
899ff27333c1927fc535d670fd4cf0dd4754ed9e
Kyrylo-Kotelevets/NIX_python
/Beginner/4.py
615
4.34375
4
""" Дан список из строк. Создайте однострочное решение (при помощи list comprehension), которое приведёт к верхнему регистру все строки, содержащие слово 'price') """ strings = ["Given a list of strings", "Create a one line solution", "(with a list comprehension)", "which will convert"...
d7283d06b2cbf3acc7897c51d65f157b8d0f0533
Kyrylo-Kotelevets/NIX_python
/Trainee/12.py
1,498
4.03125
4
""" создайте тестовую директорию с несколькими файлами разных названий при помощи модуля os создайте функцию для очистки директории от файлов определённого расширения, принимающую на вход: путь к директории, где нужно удалить файлы строку - формат файла, по которой будет определяться, нужно ли удалять файл пример вызов...
a155b2f5c0be4ab76913c11f6fad29e818605bff
Tandrac/CSCI4230-hw1
/hw1.py
6,619
3.546875
4
def tobits(s): #from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result def frombits(bits): #from ...
ac3e0974a676ea2cec4025da88171668aafa7062
mukesh25/python-mukesh-codes
/pattern/pattern9.py
332
4.1875
4
# 1 # 2 2 # 3 3 3 # 4 4 4 4 # No. of spaces in every row:(n-i-1) # which symbol: (i+1) # How many times: (i+1) # with in each row same symbol are taken # inside row symbol are not changing that's why nested loop is not required. n= int(input('Enter n value: ')) for i in range(n): print(' '*(n-i-1)+(str(i+1)+'...
055defeb4c3391a1f98108ff3b9dd7de457fbfc0
mukesh25/python-mukesh-codes
/stringpattern/strpattern12.py
261
3.59375
4
# write a program for the following requirement? # input = a4k3b2 # output = aeknbd s = input('enter some String: ') output='' for ch in s: if ch.isalpha(): output=output+ch x=ch else: d=int(ch) newc=chr(ord(x)+d) output=output+newc print(output)
6deaf076da11024f7585bae06db679642ed2f04d
mukesh25/python-mukesh-codes
/pattern/pattern19.py
297
3.65625
4
#- - - 1 #- - 1 2 #- 1 2 3 #1 2 3 4 #- 1 2 3 #- - 1 2 #- - - 1 n= int(input('Enter n value: ')) for i in range(n): print(' '*(n-i-1),end='') for j in range(i+1): print(j+1,end=' ') print() for i in range(n-1): print(' '*(i+1),end='') for j in range(n-i-1): print(j+1,end=' ') print()
55c3bccfa073b942813d86a3764aa4237e55486c
mukesh25/python-mukesh-codes
/stringpattern/strpattern5.py
333
4.21875
4
# write a program to REVERSE internal content of each word? # input = mukesh software solutions # output = hsekum erawtfos snoitulos s = input('enter some string to reverse: ') l = s.split() print(l) #['mukesh','software','solutions'] l1=[] for word in l: l1.append(word[::-1]) print(l1) output = ' '.join(l1) p...
09bafb7c5bdf34cdc7f1a16d91be11445a14ebd6
mukesh25/python-mukesh-codes
/pattern/pattern3.py
99
3.796875
4
# 3 3 3 # 3 3 3 # 3 3 3 n= int(input('Enter n value: ')) for i in range(n): print((str(n)+' ')*n)
90ee5d614355f201a11e5a5f8d64dd2632427dac
urskaburgar/python-dn
/naloga-8/calculator/calculator.py
417
4.21875
4
first_number = int(input("Enter the first number: ")) second_number = int(input("Enter the second number: ")) operation = input("Choose operation (+, -, *, /): ") if operation == "+": print(first_number + second_number) elif operation == "-": print(first_number - second_number) elif operation == "*": prin...
47dd2fc0e8d7c899202fb443b08d8c8c733f1525
rbrowngt/Practice
/src/practice.py
1,790
3.8125
4
""" Find the longest positive subsequence i.e. [-1,4,3,1,2,3,4,5,-9,2,7] Longest: 7, index:1 """ def longest_subsequence(a): """ Return: (length, index) """ # Sanity checks if a is None or len(a) == 0: return 0 index = -1 currentLength = 0 maxLength = 0 flag = False...
28e29acdcf38cec8c1ec5aae0331c415af645144
DatHydroGuy/PythonSecurity
/0402_Timing_Attacks.py
1,921
3.828125
4
import time from random import randint def check_password(guess_password): """ Here, we emulate what happens 'under the hood' during a string comparison (or a comparison of any two iterables of data). The basic premise is that a comparison is made between the first element of each iterable, and if they ...
249e09b23d489e212a4e9c1ca11e3e60df29e2ca
OmarAbdAlFattah/Calculator.
/Calc.py
232
4.09375
4
d = input("Enter the degree of your equation : ") x = input("Enter the value of x : ") function_value = int(0) while d>= 0 : processing = x**d function_value = function_value + processing d = d-1 print (function_value)
93a9d54017262e64b6a0216982f66ef0aa5b3cfc
hoddere/LEAPCodemakers2018
/Student Files/Session 2 Files/calculator.py
3,157
3.84375
4
from tkinter import * cal = Tk() cal.title("Calculator") operator = "" text_Input = StringVar() def btnClick(numbers): global operator operator = operator + str(numbers) text_Input.set(operator) def btnClear(): global operator operator = "" text_Input.set("") def btnEquals(): global oper...