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
b389c04b0c384240d7008ce9b68f2c81cb4f869d
marioamz/Migration_Visualizations
/LAPOP/read.py
4,827
3.5625
4
# LAPOP Migration Project # 11-24-2019 import pandas as pd def go(fname, countries, year, col, dvar): ''' Go function for the program, spits out cleaned df ''' dept_dict = read_dta(fname, col) findf = read(fname, countries, year, dept_dict, dvar) #Change the names of the countries findf[...
a7745492208033ac49f8d0285ff7c141eed19a70
gatherworkshops/programming
/_courses/tkinter2/assets/zip/pythonchallenges-solutions/eventsdemo.py
2,908
4.21875
4
import tkinter import random FRUIT_OPTIONS = ["Orange", "Apple", "Banana", "Pear", "Jalapeno"] window = tkinter.Tk() # prints "hello" in the developer console def say_hello(event): name = name_entry.get() if len(name) > 0: print("Hello, " + name + "!") else: print("Hello random stranger...
22e98ce21d57df972450811fdb6f667bfc96a173
drawwon/show-me-the-code
/04/4.py
312
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/5/11 22:21 import re from string import punctuation with open(raw_input('filename:')) as f: text = f.read() punctuation = punctuation+' ' pat = '[%s]+' % punctuation word = re.split(pat,text) print word print len(set(word))
47dfb4df983755d2861df91fc599add35a4a59c2
drawwon/show-me-the-code
/22/22.py
545
3.703125
4
#!/usr/bin/env python # -*- coding: gbk -*- # @Time : 2017/6/28 13:53 import os from PIL import Image def resize(filename,new_name): pic = Image.open(filename) out = pic.resize((1000,800),Image.ANTIALIAS) out.save(new_name,quality=100) list_dir = os.walk(r'C:\Users\jeffrey\Desktop\python exercise\pytho...
dac0e28ffe4a510960a7f5e5997ccc937946c430
Godul/advent-of-code-2020
/day16/solution.py
2,747
3.65625
4
from collections import defaultdict from functools import reduce def load_data(): with open('input.txt') as file: rules = {} line = next(file).split() while line: name = ' '.join(line[:-3])[:-1] min_1, max_1 = map(int, line[-3].split('-')) min_2, max_2 =...
ce91d5c1b80ab1001d251ce4c46801a4fe04d161
Godul/advent-of-code-2020
/day10/solution.py
1,337
3.703125
4
from collections import defaultdict def get_sorted_jolts(): with open('input.txt') as file: return list(sorted(map(int, file))) def count_diffs(jolts: list): count_dict = defaultdict(int) for i in range(1, len(jolts)): count_dict[jolts[i] - jolts[i - 1]] += 1 return count_dict def ...
8ab8f7fe82c9e7f7f4e3aaf24bbadef6c9fdf604
Godul/advent-of-code-2020
/day02/solution.py
874
3.6875
4
def load_input(): input_list = [] with open('input.txt') as file: for line in file: line = line.split() r = map(int, line[0].split('-')) letter = line[1][0] password = line[2] input_list.append((r, letter, password)) return input_list def...
0a8a034e95d884e38454f630038d504071c7104f
moranneil/pands-final-project-2019
/analyse-iris-generate-pairplot.py
1,044
3.859375
4
# Neil Moran 25/04/2019 # Python script imports Iris Dataset from csv file # Generates Pairplot once the data is imported from the csv file #Python librarys Numpy, Pandas, MatplotLib and Seaborn are imported import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #Pandas command...
3dab7b70d98cce6503ac44d66619164b0cb2e3df
BigFedor/Tasks
/Contest_October/Task_H.py
523
3.765625
4
def merge_lists(arr1, arr2): i = 0 j = 0 k = 0 arr = [0] * (len(arr1) + len(arr2)) while (i < len(arr1)) and (j < len(arr2)): if arr1[i] <= arr2[j]: arr[k] = arr1[i] i += 1 k += 1 elif: arr[k] = arr2[j] j += 1 ...
b0722e98bf4fb590be94321a148a74a39ad650b1
jeanbapt-sanchez/jeu-du-morpion
/src/MorpionEducatif.py
5,369
3.953125
4
#python 3.7.1 #Auteur : Jean-Baptiste Sanchez # Définition d'une constante représentant la taille de la grille de jeu TAILLE_GRILLE = 3 # Définition de la liste des joueurs (classe joueur ?) joueur = [" ", "x", "o"] # Définition de la grille 2D de jeu pour sauvegarder les infos de jeu grille = [[0] * TAILLE_GRILLE f...
d6eb76e86a7c77ce7f875289e87562990ed2bd58
karramsos/CipherPython
/caesarCipher.py
1,799
4.46875
4
#!/usr/bin/env python3 # The Caesar Cipher # Note that first you will need to download the pyperclip.py module and # place this file in the same directory (that is, folder) as the caesarCipher.py file. # http://inventwithpython.com/hacking (BSD Licensed) # Sukhvinder Singh | karramsos@gmail.com | @karramsos import py...
712f9f9a8fe4d7bd7936b10defcae8faaae94903
iamebube-ekpe/Python-DSA
/insert_sort.py
468
3.84375
4
def insertSort(uList): # sortedResult = [] for index in range(1, len(uList)): keyElement = uList[index] element = index - 1 while element >= 0 and keyElement < uList[element]: uList[element+1] = uList[element] element -= 1 uList[element+1] = keyElement ...
8764850aa58199ba36f2439373b9b64e8725bbf2
buttegab/SoftDesSp15
/gene_finder/get_complimenttest.py
271
3.640625
4
def get_complement(nucleotide): if nucleotide == "T": return "A" if nucleotide == "A": return 'T' print 'T' elif nucleotide == "G": return "C" elif nucleotide == "C": return "G" print get_complement("G")
2ea42b749ee8320df5a7eda34a07e3bc683101b3
40168316/PythonTicketApplication
/TicketApplication.py
2,257
4.375
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 # Create a function that calculates the cost of tickets def calculate_cost_of_tickets(num_tickets): # Add the service charge return (num_tickets * TICKET_PRICE) + SERVICE_CHARGE # Run this code continuously until we run out of tickets wh...
ef86c4bfd8bb3d196ff0c90f3194ea4b7607fe23
Holmsoe/PandasHints
/plot eksempler.py
4,757
3.625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.style as mplstyle #Brug denne og ikke pylab def ex1(): x=np.linspace(0,1,10) plt.plot(x,x*x,label="x i anden") def ex2(): fig = plt.figure() # an empty figure with no axes fig, ax_lst = plt.subplots(2, 2) # a fi...
9c704098d61f7d88c98df0eeba2d0c6f0ed72fc0
nesl/TransientSensorRobustInference
/Evaluation/generateUserData.py
6,644
3.609375
4
from random import random import os sit_count = 0 walk_count = 0 run_count = 0 bike_count = 0 def getLabel(subListOfLabels): return_val = -1 return_str = "" global sit_count, walk_count, run_count, bike_count for i in range(0, len(subListOfLabels)): if subListOfLabels[i] == "1": return_val = i if ret...
1327c1c7146f479450e0513533175b6a1c7c0286
mblanco71/KeepCoding-Boot0-Homework
/MBP-MYFIRSTGUI-0001.py
5,529
3.703125
4
#Here I have my turtle code def prueba (): def house(): tu.penup() tu.goto(0, -100) tu.pendown() # Parte cuadrada de la casa for i in range(4): # Cambio velocidad tu.speed(20) # Pongo la tortuga tu.shape("turtle") ...
ab8bde95d77d47931e3bc837a59c247884386039
alisa1810/advent-of-code-2020
/Day6/day6.py
961
3.703125
4
def get_groups(lines_list): group_list = [] one_group = [] for line in lines_list: if line == "\n": group_list.append(one_group) one_group = [] else: line = line.strip("\n") one_group.append(line) group_list.append(one_group) return ...
4f659f6843bcd5a9691308437213cdf9bcb37bc4
zvut/Data-Structure-and-Algorithm-COURSERA-
/Algorithm Toolbox/WEEK 1/max_pairwise_product.py
404
4.0625
4
# python3 def max_pairwise_product(numbers): n = len(numbers) max_product = 0 for first in range(n): for second in range(first + 1, n): max_product = max(max_product, numbers[first] * numbers[second]) return max_product input_n = int(input("Enter the len")) input_num...
b49ea3e976180eecf26802fe0a6a198ce6e914fb
aabidshaikh86/Python
/Day3 B32.py
1,119
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: fullname = 'abid sheikh' print(fullname ) # In[ ]: # Req: correct the name format above by using the string method. # In[3]: print(fullname.title()) # Titlecase ---> first Letter of the word will be capital # In[ ]: # In[ ]: # Req: I want all the name ...
626aea1dbd007cc33e1c79e6fa7a35848f313cc5
aabidshaikh86/Python
/Day7 B32.py
1,888
4.375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: list Continuation : # In[ ]: # In[1]: cars = ['benz','toyota','maruti','audi','bnw'] # In[ ]: ## Organising the list datatype # In[ ]: req : i want to organise the data in the alphabetical order !!! A to Z # In[ ]: Two different approcahes : 1...
94368dae9daa5bc95af4272b270b57751a710aa4
jlaufmann/python_apis_databases
/databases/Exercise_02.py
6,146
3.703125
4
''' Consider each of the tasks below as a separate database query. Using SQLAlchemy, which is the necessary code to: - Select all the actors with the first name of your choice - Select all the actors and the films they have been in - Select all the actors that have appeared in a category of a comedy of your choice ...
d6edefcc801c6b88b73c153c07e8450eaf79f259
emrearik/currency_project
/Currency Project.py
7,636
3.828125
4
# Libraries were added to get exchange rate from xml.etree.ElementTree import parse from urllib.request import urlopen # Currency rate is taken from TCMB website and parsed XML. def fetchXMLData(index): url = "https://www.tcmb.gov.tr/kurlar/today.xml" response = urlopen(url) xmldoc = parse(response) ro...
f39d08f509be804ff2c72a55eaa5302b84f949df
sachinshikhare/coding-challanges
/python/PythonTester.py
1,202
3.515625
4
string = "123456789" if len(string) % 3 == 1: arr = [string[0]] arr.extend([string[i:i+3] for i in range(1, len(string), 3)]) elif len(string) % 3 == 2: arr = [string[0:2]] arr.extend([string[i:i+3] for i in range(2, len(string), 3)]) else: arr = [string[i:i+3] for i in range(0, len(string), 3)] p...
3d2ef28de62694c343895c67bf474e80885e8c8e
sachinshikhare/coding-challanges
/python/SerializeAndDeserializeBinaryTree.py
2,211
3.953125
4
import math # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str ...
2f996652da6acc26f2119fc73b9b36f9b373fde9
lawga/Algos-Bender
/Pascal Triangle/Python/Pascal - Basic.py
408
3.75
4
def pascal(x, y): if (x<=0 or y<=0) : return 1 if (x==1 and y==1) : return 1 if (y>x) : return 0 return pascal(x-1, y) + pascal(x-1, y-1) import time start = time.time() #start timer x = 15 y = 0 for i in range(0, x): for j in range(0, i+1): print(pascal(i,j), end=" ") ...
cba0e3df6ccef062a345234650ddb61b3e54a96a
ShahzaibSE/Python-Babysteps
/marksheet_maker.py
1,136
4.25
4
marks = [] eng_marks = int(input("Enter marks for English:")) marks.append(eng_marks) # chemistry_marks = int(input("Enter marks for Chemistry:")) marks.append(chemistry_marks) # computer_marks = int(input("Enter marks for Computer:")) marks.append(computer_marks) # physics_marks = int(input("Enter marks for Physics:")...
e6af2b34c1c7229a5d9dfc7d38f45165fbfa259d
violivei/call-center
/app/call_handler.py
1,988
3.53125
4
class CallHandler: """ The main class. Handles the associating respondents with calls, redirecting calls to a queue if respondent is unavailable """ def __init__(self): self.respondent_types = ["respondent", "manager", "director"] self.call_queue = [] self.respondents = [] ...
068da642e9e3c2e1a9544b5bca3d0128ee3f02df
yiVodka/python
/1.tutorial.py
1,157
3.96875
4
if True: print('True') else: print('False') word = '字符串' sentence = "这是一个句子。" paragraph = """这是一个段落, 可以由多行组成""" print(word) print(sentence) print(paragraph) total = word + sentence + \ paragraph print(total) str = 'Python' print(str) # 输出字符串 print(str[0:-1]) # 输出第一个到倒数第二个的所有字符 print(...
ea086ee67f1da0738a2d7f65a097292510decc55
Nageshpermand/batch49
/project/eyesdetect.py
2,928
3.625
4
# open cv2 is computer vision open sourse library files are available # this is for face and eyes detection import cv2 # Method to generate dataset to recognize a human face def generate_dataset(img, id, img_id): # write image in data direction cv2.imwrite("data/user.%s"%(id)+"."%(img_id)+".jpg", img) # this...
28c4909472672e7dcfc5bd8ced18421c954bdb1e
liangcyn/crazyeights
/card_actions.py
824
3.859375
4
import draw import random from card import Card values = ['ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king'] suits = ['clubs', 'diamonds', 'hearts', 'spades'] NUM_INITIAL_CARDS_IN_HAND = 5 CRAZY_EIGHT = '8' def create_deck(): deck = [] for value in values: for suit in suits: new_c...
897e84d7e0085200eb7ffda7895553602fe57f7f
ArielGobbato/Curso_Python
/3- Condicionales y Listas/3-9- Ejercicio de CLAVE.py
526
4.03125
4
# LISTAS INSERTAR ELEMENTOS colores = ["rojo" , "amarillo" , "verde" , "fuxia"] colores.append("naranja") # con .append puedo añadir al "final de la lista solamente" print (colores) colores = [] #lista vacia colores.append("naranja") colores.append("celeste") # con .append puedo añadir al "final de la lista solamen...
505176900ca60ffc5a484bf900ffb00429c90025
ArielGobbato/Curso_Python
/3- Condicionales y Listas/3-3- Ciclo WHILE.py
523
4.03125
4
# BUCLES, LOOP O CICLO WHILE WHILE (mientras) # número indeterminado de ciclos mientras se cumpla una condición import math numero = int(input("ingrese su numero")) while numero<0: print("ERROR -> el numero debera ser positivo") numero = int(input("ingrese su numero")) print (f"la raiz cuadrada es:{math.sqr...
a6c2b8857c7cc050d3118182bbae23ffc1ed7b66
Gijsbertk/afvinkblok2
/afvink5g/5.1.py
732
3.75
4
class pet: def __init__(self, __name, __age, __type): self.__name = __name self.__age = __age self.__type = __type def SetName(self): self.__name = input('Geef de naam van je huisdier: ') def SetAge(self): self.__age = input('Geef de leeftijd van je huis...
8d778b4cf8872d0c928d6a55933fcdfa86d0847d
Jasmine582/guess_number
/main.py
468
4.125
4
import random random_number = random.randrange(100) correct_guess = False while not correct_guess: user_input = input("Guess a number between 0 and 100:") try: number = int(user_input) if number == random_number: correct_guess = True elif number > random_number: print("You guessed too hig...
91f938f9f01ebba7f706521237e7d09a14f9e822
Rnevr/flask-dev3
/tweet.py
665
3.84375
4
import datetime def createTweet(): author = input("Nom de l'auteur du tweet : ") text = input("Contenu du tweet : ") return Tweet(author, text) class Tweet: numberOfTweets=0 def __init__(self, authorName, content, image=None): Tweet.numberOfTweets += 1 self.id = Tweet.numberOfTweet...
e79dd5b2ad6de7391f8b3eebd8bb97d50b32622f
Bobur-oiligarh/CabinetBook
/models.py
5,398
3.859375
4
import sqlite3 class Database: """ Создадим класс для связи с БД, записи, чтения данных из базы данных """ def __init__(self, path_to_db='cabinet_book_db.db'): # Передадим классу параметром путь к БД. self.path_to_db = path_to_db @property def connection(self): """Фу...
df37409d7d638ffaac6ad488b147cd983949a4c7
nair12parvathi/Computational-Problem-Solving
/Encryption/transformer.py
9,969
4.53125
5
""" file: transformer.py language:python 3 author: pan7447@cs,rit,edu Parvathi Nair author: dck1135@cs.rit.edu Darshan Kavathe description: To generate fractals in 3 different ways precondition: messages and operations as strings postcondition: messages encrypted or decrypted as per user input """ def encrypt_Sik(messa...
114e7bf705ca72a61e2a4b4e62ec228fc4aea6a6
nair12parvathi/Computational-Problem-Solving
/Cut-Down-Trees/lumber.py
8,452
3.5625
4
""" file: lumber.py language:python 3 author: pan7447@cs,rit,edu Parvathi Nair author: dck1135@cs.rit.edu Darshan Kavathe description: To generate trees on click on the window and then harvest the same and draw logs precondition: Turtle is at coordinates(0,0),facing east, pendown postcondition: Turtle is at coordinates...
66a3d3673a445c97ed3eafee8220c318ee7470c2
marcin-jamroz/python4beginners
/w5/praca_domowa/zadanie_1.py
3,655
3.84375
4
# Iterator Collatza # # Zadanie rozwiąż BEZ UŻYCIA GENERATORÓW. # Napisz klasę CollatzSeq(start_value) wyliczającą kolejne liczby według wzoru: # https://pl.wikipedia.org/wiki/Problem_Collatza#Sformu.C5.82owanie_problemu_Collatza # Powinno być możliwe iterowanie po CollatzSeq (po kolejnych liczbach z sekwencji). # W...
db16b17821471718433952a012bbe92117f09695
marcin-jamroz/python4beginners
/w2/pd2/zadanie3.py
291
3.625
4
def add_one(list_tmp = None): if list_tmp is None: list_tmp = [] list_tmp.append(1) return list_tmp test_list = [5, 6, 7] result1 = add_one(test_list) assert result1 == [5, 6, 7, 1] result2 = add_one() assert result2 == [1] result3 = add_one() assert result3 == [1]
13f8fe6cfbfb110bae6457600b109f2197e7d812
marcin-jamroz/python4beginners
/w5/praca_domowa/zadanie_2.py
3,476
3.609375
4
# Napisz funkcję longest_collatz(start, stop) # Funkcja ma zwracać długość najdłuższej sekwencji Collatza i wartość startową dla wartości od ‘start’ włącznie, do ‘stop’ wyłącznie. # W tym zadaniu można (lecz nie ma przymusu) użyć generatorów. # Proszę o wykorzystanie kodu z zadania 1 (przeklejcie kod do tego zadania, ż...
686d03d60a541f88178f065fb15790c836507c19
ringotian/LP14_homework
/additional_homework/string_challenges.py
951
4.1875
4
# Вывести последнюю букву в слове word = 'Архангельск' print(word[-1]) # Вывести количество букв "а" в слове word = 'Архангельск' print(word.lower().count('а')) # Вывести количество гласных букв в слове word = 'Архангельск' print(len([x for x in word.lower() if x in 'ауоыэяюёе'])) # Вывести количество слов в предл...
0a1b4944b8c3d2b92ccc648094998c24f57b3bff
Goku-kun/1000-ways-to-print-hello-world-in-python
/using-asyncio.py
498
3.9375
4
# print Hello, World! using asyncio library import asyncio async def hello(): await asyncio.sleep(3) print('Hello,', end=' ') async def world(): await asyncio.sleep(3) print('World!') a = [hello(), world()] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather(*a)) ...
e00da369443f92f2e42d580635302cdf96ffa59b
Goku-kun/1000-ways-to-print-hello-world-in-python
/using-user-input.py
272
4.4375
4
# A program to print 'Hello, World!' by force typing it by the user himself def hello_world(): str = input("Enter 'Hello, World!' exactly: ") if str == 'Hello, World!': print(str) else: print('Try Again!') hello_world() hello_world()
632b20638a2e3922140a4cc4e9aeff6a9309a049
Goku-kun/1000-ways-to-print-hello-world-in-python
/using-random.py
358
3.5
4
# this is probably one of the worst ways possible # this script might actually be interesting for statistical purposes on the random() function. who knows. import random target = "Hello world!" strlen = len(target) i = 0 while i != strlen: cascii = random.randint(0,127) if chr(cascii) == target[i]: print(chr(...
0dee6bf093be84a5ef0a18c1777f39c4b64a580a
Goku-kun/1000-ways-to-print-hello-world-in-python
/using-join.py
124
3.640625
4
#Printing Hello World using join hello_world = ["H","e","l","l","o"," ","W","o","r","l","d","!"] print("".join(hello_world))
cee2655d77fa9de36f433247b5713a2648fdfbf0
otolaa/Tkinter
/calculator.py
2,216
3.734375
4
# Calculator form tkinter from tkinter import * from tkinter import messagebox from tkinter import ttk root = Tk() root.title("Калькулятор") root.geometry("500x310") def calc(key): # логика калькулятора global memory if key == "=": # исключение написание букв strl = "-+0123456789....
836b40f3445ebe8bfa2ed03a1dd4a21d7236f265
ben-norton4/module-one
/test.py
1,643
4
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def calculate (operator, parameterA, parameterB): result = 0 if((operator == '*') or (operator == 'x')): result = multiply(parameterA, parameterB) elif(ope...
6a3a1e8a064d37122bbdadfaa9c8d050928ac372
hyorangnavi/deep-learning
/Gradient_Decent.py
1,144
3.5
4
#%% Import TF and Set 2-axis Data import tensorflow as tf #[공부시간, 과외수업횟수, 성적] data = [[2,0,81], [4,4,93],[6,2,91],[8,3,97]] x1_data =[x[0] for x in data] x2_data = [x[1] for x in data] y_data =[y[2] for y in data] print(x1_data) print(x2_data) print(y_data) #%% Set Running Rate learning_rate = 0.1 #%% Set variable a1, ...
ad4020c60e7f46eae3306807291bd7f8486a2273
bcsf16a540/Python
/SJF.py
872
3.6875
4
ProcessList=[] print("Enter the Number of Process: ") n=int(input()) for i in range(0,n): procInfo={} procInfo["Number"]=i+1 procInfo["BT"]=int(input("Brust Time for process "+str(i+1)+" :")) ProcessList.append(procInfo) ProcessList=sorted(ProcessList,key=lambda x: x["BT"]) Total_BT=0 for pr...
f8390e1a672802dd30b581fb71a50b1a2d3fbcd5
kristopher-merolla/Dojo-Week-3
/python_stack/python_fundamentals/type_list.py
1,418
4.46875
4
# Write a program that takes a list and prints a message for each element in the list, based on that element's data type. # Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At ...
0c6cecbb159ee1a89414c2957ca1308b548a3274
kristopher-merolla/Dojo-Week-3
/python_stack/python_fundamentals/strings_and_lists.py
447
3.875
4
str = "It's thanksgiving day. It's my birthday,too!" new_str = str.replace("day","month") # print new_str x = [2,54,-2,7,12,98] # print x # print "The max value in array x is:", max(x) # print "The min value in array x is:", min(x) y = ["hello",2,54,-2,7,12,98,"world"] # print y # print y[0],y[len(y)-1] z = [19,2,54,-2...
efaea1b35e99e69cb01dcb6ba14ebce6bae5b5e5
kristopher-merolla/Dojo-Week-3
/python_stack/python_fundamentals/names.py
2,882
3.8125
4
# Assignment: Names students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] users = { 'Students': [ {'first_name': 'Michael', 'last_nam...
bf19a67d1b7f176b17492fea6da77a40a1ce4c8e
v-apor/algorithms
/DS and Algo Made Easy/2 Recursion/4Fibonacci.py
146
3.890625
4
def getFibo(num): if num in [1,2]: return num-1 else: return getFibo(num-1) + getFibo(num-2) print(getFibo(int(input())))
c6cf062a9abbe57540bc0b758c6fb06cab8fc634
lekhabajpai/ga-learner-dsmp-repo
/First-Predict-algo/code.py
1,699
3.546875
4
# -------------- import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split # code starts here df = pd.read_csv(path) print(df.head(5)) #Store features in X y = df.iloc[:,1] X = df.iloc[:,:9] #X = X.drop('list_price', axis=1) #print(X.head()) #Split dataframe X_train, X_test, y_train, ...
87beb7914cf0e755cccc871344c8ff0ae3bbc909
whime/dataStructure-algorithm
/剑指offer/数组中只出现一次的数字.py
1,272
3.71875
4
""" 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 """ # 多使用一个列表辅助 # -*- coding:utf-8 -*- class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here array.sort() arr = [] for i in range(0, len(array)): if array[i] not in arr: ...
9b0b0c6fe1d1c6644f40deee39631d2f5256527e
whime/dataStructure-algorithm
/剑指offer/构建乘积数组.py
631
3.734375
4
""" 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1], 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。 """ # -*- coding:utf-8 -*- class Solution: def multiply(self, A): # 时间复杂度O(n),来自讨论区 B=[] B.append(1) for i in range(1,len(A)): B.append(B[i-1]*A[i-1]) ...
1a77eabd88998a0e81812fc6d1f5bba27302a53e
whime/dataStructure-algorithm
/剑指offer/表示数值的字符串.py
707
3.703125
4
""" 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。 """ # -*- coding:utf-8 -*- class Solution: # s字符串 def isNumeric(self, s): # write code here import re # 牛客的python2不支持 re.fullmatch,会有局部匹配,需要在最后加上$ 限制结尾 ...
2c2ed468feaddb370a724e3f50744e52353d449c
whime/dataStructure-algorithm
/剑指offer/数组中的逆序对.py
3,134
3.578125
4
""" 题目描述 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 题目保证输入的数组中没有的相同的数字 数据范围: 对于%50的数据,size<=10^4 对于%75的数据,size<=10^5 对于%100的数据,size<=2*10^5 """ """ 使用插入排序,边找插入的地方边计算左边大于插入值的数的个数。 下面两个方法估计是没问题的,第二种方法使用折半查找找插入位置还超时。 只能说python不适合做这道题目 """ ...
5e7300a9b9d43d241b5111a7518084ad87e317b7
whime/dataStructure-algorithm
/Leetcode/medium/1583. 统计不开心的朋友.py
2,028
3.671875
4
""" 给你一份 n 位朋友的亲近程度列表,其中 n 总是 偶数 。 对每位朋友 i,preferences[i] 包含一份 按亲近程度从高到低排列 的朋友列表。换句话说,排在列表前面的朋友与 i 的亲近程度比排在列表后面的朋友更高。每个列表中的朋友均以 0 到 n-1 之间的整数表示。 所有的朋友被分成几对,配对情况以列表 pairs 给出,其中 pairs[i] = [xi, yi] 表示 xi 与 yi 配对,且 yi 与 xi 配对。 但是,这样的配对情况可能会是其中部分朋友感到不开心。在 x 与 y 配对且 u 与 v 配对的情况下,如果同时满足下述两个条件,x 就会不开心: x 与 u 的亲近程度胜过 x 与 y...
1c00d5c708f37cdbc51b4f94b8f1c2442479b459
whime/dataStructure-algorithm
/剑指offer/数组中重复的数字.py
811
3.796875
4
""" 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的, 但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 """ # -*- coding:utf-8 -*- class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # write code here...
984d12b4981d16df2368b3c9b8321787b52b01e6
tdb219/python-challenge
/PyPoll/main.py
3,296
3.859375
4
#open and read csv file import os import csv csvpath = os.path.join('Resources', 'election_data.csv') # with open("Resources/Homework_03-Python_Instructions_PyPoll_Resources_election_data.csv", 'r') as pypoll_file: with open(csvpath) as pypoll_file: csvreader = csv.reader(pypoll_file, delimiter = ",") # identi...
cd6be1d0df371e2e7f5dd4fe2afc9c2abe1eb89f
caleanunoah/async_web_scraper
/pages/books_page.py
1,367
3.515625
4
from bs4 import BeautifulSoup from parsers.books import BooksParser from locators.books_page_locators import BooksPageLocators import re import logging logger = logging.getLogger("scraping.books_page") class BooksPage: """ Takes in front page and extracts information """ def __init__(sel...
88f372702cbdf0cf4a9147f3aa3f26aedb8f7af5
ByakuyaSnow/Tello_Project
/Task1/2_Moving_around.py
734
3.5
4
""" todo write a short code to command the drone into moving following a 2*2m square (approximately based on flight time at constant speed). """ from djitellopy import Tello # create drone instance and connect tello = Tello() tello.connect() print("BATTERY:", tello.get_battery()) # drone speed set to 20cm/s tello...
351628338e20f8bdda013753c1ac808372aa5de8
botked/DigitRecognition
/Keras+Tensorflow/mnist_keras_DNN.py
1,780
3.609375
4
# import classes and functions from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.utils import np_utils import matplotlib.pyplot as plot # Load / Download images if needed (X_train, Y_train), (X_test, Y_test) = mnist.load_data() # Plo...
989bbc444f1b63372616540f036075f8fda4312f
marotpam/algorithms
/quicksort/pq2.py
643
3.53125
4
def quick_sort(A): n = len(A) if n <= 1: return 0, A left = 0 right = n comparisons += right -left p, A = partition(A,left, right) nL, L = quick_sort(A[left:p]) nR, R = quick_sort(A[p:right]) return n-1 + nL + nR, L+R def partition(A, l, r): p = A[l] i = l+1 for...
3caf05cc3eb9cee2e9e0d7ad2ef9882a32a8668d
niteeshmittal/Training
/python/basic/Directory.py
1,490
4.125
4
#Directory try: fo = open("phonenum.txt") #print("phonenum.txt exists. We are good to go.") except IOError as e: if (e.args[1] == "No such file or directory"): #print("File doesn't exists. Creating a phonenum.txt.") fo = open("phonenum.txt", "w") finally: fo.close() opt = input("1 for store and 2 for read: ")...
217242a65b390294f9660aff4ca5ec8c06d5a046
niteeshmittal/Training
/python/basic/Lists.py
3,198
4.40625
4
print("This program is to practice Lists Sequence."); num_list=[1,2,3,4,5,6,7]; str_list=['Music','Books','Travel','Games','Cook','Movies']; alpha_list=[31,'Bday',12,'Month',1989,'Year']; print();print('This is the number only list: ',num_list); print();print('This is the string only list: ',str_list); print();print(...
3dde22d71aab3f343ef9f0aa6707e7b6a9220a61
rjcmarkelz/python_the_hard_way
/functional_python/chp1_1.py
1,619
4.15625
4
# chapter 1 of functional python book def sum(seq): if len(seq) == 0: return 0 return seq[0] + sum(seq[1:]) sum([1, 2, 3, 4, 1]) sum([1]) # recursive def until(n, filter_func, v): if v == n: return [] if filter_func(v): return [v] + until(n, filter_func, v+1) else: ...
fb8f886ada9f7acece214f922d3f6ebcad79799c
rjcmarkelz/python_the_hard_way
/functional_python/chp2_1.py
724
3.84375
4
def example(a, b, **kw): return a*b type(example) # although NOT recommended, can use lambdas mersenne = lambda x: 2**x-1 # combine functions with higher order functions # immutable data ## a common design pattern that works well with immutable objects: the wrapper() ## snd = lambda x: x[1] snd(max(map(lambda y...
f3603fcc0d52c2bd9add77331a257fef459b0495
sunjingwei1991/shiyanlou-code
/jump7.py
113
3.734375
4
a = 0 while a <100: a +=1 if a%10 ==7 or a%7 ==0 or 69<a<80: continue else: print(a)
4ec7d99d42c219ce7a129ed4af7e42bc34a8a762
matthewpaulin/Tetris
/tetris/tetris_classes.py
13,812
3.859375
4
######################################### # Programmer: Mrs.G # Date: 04/12/2016 # File Name: tetris_classes3.py # Description: These classes form the third and final class template for our Tetris game. ######################################### import pygame #colors BLACK = ( 0, 0, 0) RED ...
89dc223f20d1d5c93873cdc4152399121dacd9e9
jeffreybyrne/0326-reinforcement
/exercise.py
800
3.953125
4
class Location: def __init__(self, name): self.name = name def __str__(self): return f"{self.name}" class Trip: def __init__(self): self.stops = [] def addStop(self, location): self.stops.append(location) def listRoute(self): print("Began trip.") ...
25436cbd4e320f23f9c9d275b14af0456c482429
resudirga/coursera-python
/tic_tac_toe.py
4,946
4.15625
4
""" Mini-project for Principles of Computing Part 1. A machine Tic-Tac-Toe player by Monte Carlo simulation. Written on: 18/09/2015 """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not ch...
32efa3cf77238d5194e3111b0c78d35c08cab312
HuiningBinla/LearnPython
/FUNC/PrintImport_00.py
462
3.578125
4
def print_line(char, times): """打印分隔线 :param char:分隔线使用的分隔符 :param times: 分隔符重读的次数 """ print(char * times) def print_lines(char, times): """打印多行分隔线 :param char:分隔线使用的分隔符 :param times:分隔线重复的次数 """ row = 0 while row < 5: print_line(char, times) row += 1 n...
8efbabbcd50642123c38bc469fccb74198e512f1
HuiningBinla/LearnPython
/FUNC/Multipl_00.py
251
3.671875
4
def multiple_table(): # 1.打印9 行小星星 row = 1 while row <= 9: col = 1 while col <= row: # print("%d" %col,end="") #print("*",end=" ") print("%d * %d = %d" %(col,row,col * row),end="\t") col += 1 print("") row += 1
87e1d23d7248a1f6cd6676d30b2b7a47ba07a4be
AbbyLiumm/learn_python
/dict.py
529
3.515625
4
text = "ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort." # text = text.lower() dict1 = {} dict1['a'] = [0, 0] dict1['e'] = [0, 0] dict1['i'] = [0, 0...
d9206512fccbda1a5acce4ee3198c7e0b8868709
Scopula/algo_ds
/combinatorics/num_permutations.py
298
3.875
4
from collections import Counter from math import factorial """ Numbers of permutations of a sequence. """ def num_perms(sequence): counts = Counter(sequence) res = factorial(len(sequence)) for key, count in counts.items(): res /= factorial(count) return int(res)
1ddbb899e10246172dab80b9ba2ca63f5a49fe9f
k3ymkr/blackjack_cli
/PlayBlackJack.py
3,378
3.5
4
#!/usr/bin/env python import sys,os,CardDeck money=100 stdbet=5 deck=CardDeck.Deck(1) def mainmenu(m): #clear() return "1" def clear(): pass # os.system("/usr/bin/clear") class Hand: def __init__(self,player): self.cards=[] self.value=0 self.label=player def getvalue(self): return self.value de...
c59562788b4f0876bfa61bf52572f1551e289431
roshk99/pipebot
/archive/alg_stage1.py
2,121
3.796875
4
#!/usr/bin/env python # This is a Python script that implements the first stage of classification: junction detection. # Input: # data: list of tuples with the first element in each tuple as an angle and the second a distance # radians: boolean that indicates whether the input data is in radians import math import ra...
40f54f4122729cba200e3ede71fcbab9ad4481f3
alexspring123/machine-leaning-study
/scikit-lean/linear-models/Ordinary-Least-Squares/OrdinaryLeastSquares.py
1,076
4.1875
4
''' 普通最小二乘法 根据商品历史销量预测未来销量 ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model def get_data(file_name): "获取训练数据" # https://chrisalbon.com/python/pandas_dataframe_importing_csv.html data = pd.read_csv(file_name) x = np.array(data[['week']]...
134b005094c65107925439248899b1ae07aea946
EduZarate/My-first-one
/Números pares de 0 a 100.py
236
3.875
4
### Realizar un programa que determine y muestre por pantalla los ### números pares entre 2 y 100 (inclusives). contador = 0 for contador in range (0,100): if contador % 2 == 0: print (contador) contador +=1
2b74b77dd51cd14d8a32f95141f8c2d66dba5f46
daevheed13/firstcode
/Assignment.py
7,499
4.09375
4
# Assignment 1 # filename = 'twist.txt' # mode = 'r' #read only mode # data = open(filename, mode) # import random # random_word = random.choice(data.read().split()).strip() #split the words and strip the spaces # length = len(random_word) # first_letter, second_letter, last_letter = random_word[0], random_word[1], r...
ec14a6ee189c3042bbd53277b8ab51dc5581a50d
brunocamps/pandas-study
/series-basics.py
650
3.828125
4
import pandas as pd import numpy as np obj = pd.Series([4, 7, -5, 3]) print(obj) # prints the object print(obj.values) # prints the values as arrays print(obj.index) # prints the indexes interval # Create a series which indexes match labels obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c']) print(obj2) p...
41649d7c0931ddcd8f8460a50c1561720ecade1b
mauryakash/snake-and-ladder
/PlayerDetails.py
206
3.8125
4
#This is a class for Player #This will return the name of player given class PlayerDetails: def getDetails(self): playerName = input("Please Enter your Name : ") return playerName
6d49fa13a423cfa06816c7d05c7d1b879bd5ab4a
arsh-khokhar/Bayesian-Nets-Fraud-Detection
/main.py
1,401
3.65625
4
""" File name: main.py Author: Arsh Khokhar, Kiernan Wiese Date last modified: 21 March, 2021 Python Version: 3.8 This script contains the main function that calls Inference.py to solve and show solutions a specific inference query. It parses command line arguments that specify which query ...
b36cd987bd7a8e866dc761758ed8e6e1f3d25920
sheldonbazzell/py-algos
/Tries/trie.py
918
4.03125
4
class TrieNode(object): def __init__(self, data): self.data = data self.next = {} self.end = False def __repr__(self): return "data: {}, end: {}, next: {}\n".format(self.data, self.end, self.next) class Trie(object): def __init__(self): self.root = {} def __repr__(self): return "root: {}".forma...
b9b22be77a2ec061bba9dea6a8967e6f18e1da3c
cumtqiangqiang/leetcode
/top100LinkedQuestions/5_longest_palindromic_sub.py
783
4.125
4
''' Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" ''' def longestPalindrome(s: str) -> str: start = 0 end = 0 for i in range(len(s...
560f616083f33b95ba075a311d5c0a799f7c466b
Afraysse/practice_problems_II
/HB_warm_ups.py
1,889
4.28125
4
""" REVERSE A STRING RECURSIVELY """ def reverse_string(string): output = "" if len(string) == 0: return output output += string[-1] return output + reverse_string(string[:-1]) """ REVERSE STRING WITH INDEXES """ def reverse_string_indexes(string): return string[::-1] """ SUM ITEMS IN...
366c2e4b0c4bb9d5cfbfb212ef347f6e6491ed2b
Afraysse/practice_problems_II
/list_algorithms.py
7,229
3.890625
4
import time """ LINEAR SEARCH ALGORITHM """ # Tests friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] test(search_linear(friends, "Zoe") == 1) test(search_linear(friends, "Joe") == 0) test(search_linear(friends, "Paris") == 6) test(search_linear(friends, "Bill") == -1) def search_linear(xs, ta...
3db5f4095940fc4f2a55b435eed3a4e822cda494
nkeroy/CodeInTheCommunity
/Shiritori(First letter, last letter game).py
1,874
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[5]: # FUNCTIONS def buildGlobalDict(): # open file # if you are using https://repl.it/languages/python3, replace below file name with "word_list.txt", after uploading the file on repl # else if using command line or ipython, can replace filename with absolute fi...
28a876c43b0a36f4d56f0961d994aa86087bca9e
ArjunSahlot/GUIs
/snowflake.py
1,198
3.671875
4
# # Guis # Some GUIs to learn from # Copyright Arjun Sahlot 2021 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version...
6b5fad2eff089aa64a579ecb2252a16826be8980
diceitoga/regularW3PythonExercise
/Excercise11.py
175
3.703125
4
#Exercise 11: Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). #Example: abs() value_example = 10.56 print(abs(10.56))
f1386a1b5ff8705938dbdd96f11c954fdf1dfd3c
diceitoga/regularW3PythonExercise
/Exercise8.py
339
4.125
4
#Exerciese 8: 8. Write a Python program to display the first and last colors from the following list. Go to the editor #color_list = ["Red","Green","White" ,"Black"] color_list = ["Red","Green","White" ,"Black"] lengthof=len(color_list) print("First Item: {}".format(color_list[0])) print("Last Item: {}".format(color_...
cf2a4e7217f251ae3b854f5c5c44eaa3ea3f140b
diceitoga/regularW3PythonExercise
/Ex19_is.py
413
4.21875
4
#Ex 19: Write a Python program to get a new string from a given string where "Is" has been added to the front. #If the given string already begins with "Is" then return the string unchanged print("test") sentence_string = input("Please enter a short sentence and I will add something: ") first_l = sentence_string.spli...
84fee185f3fbf9a59cf1efe89ca7ff5472e97691
diceitoga/regularW3PythonExercise
/Ex21even_odd.py
388
4.46875
4
#Ex21. Write a Python program to find whether a given number (accept from the user) is even or odd, #print out an appropriate message to the user. def even_odd(num): even_odd = '' if num%2==0: even_odd = 'even' else: even_odd = 'odd' return even_odd what_isit =even_odd(int(input("Please enter an integer betw...
34529f46ec96d96d86e210b570b7094b2da58bfa
joqhuang/si
/lecture_exercises/animals.py
1,263
3.78125
4
class Animal: legs = 4 def __init__(self, nm): self.name = nm def get_num_legs(self): return self.legs def greeting(self): return "cowers" def speak(self): print('grrrrrr') class Dog(Animal): def __init__(self, nm, br): super().__init__(nm) s...
d83882634e4db5e59edfbb1c760ef0483010fd3b
joqhuang/si
/lecture_exercises/gradepredict.py
2,003
4.40625
4
# discussion sections: 13, drop 2 # homeworks: 14, drop 2 # lecture exercise: 26, drop 4 # midterms: 2 # projects: 3 # final project: 1 # get the data into program # extract information from a CSV file with all the assignment types and scores # return a data dictionary, where the keys are assignment groups and values ...
6a28361d7a6ba9e2b19236130c37e1f5cbb4cb58
madeleinema-cee/interview_coding_challenges
/data_visualization_with_plotly/company_headcount/helpers/generate_db.py
4,017
3.796875
4
import argparse import csv from db import Db class GenerateDatabase: """Contains all queries to create headcount database and insert data Arguments: db.path (str): database path db (Db): Db instance input_file (str):csv path """ def __init__(self, input_fil...