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
a0a25e83e84fb72de47b4d091202b4499673cb98
LizaViitanen/DZ8
/venv/1.py
1,003
3.53125
4
class Data: def __init__(self, user_data): self.user_data = user_data user_data = str(user_data) @classmethod def extr(cls,user_data): user_data = list(user_data.split('-')) date = int(user_data[0]) month = int(user_data[1]) year = int(user_data[2]) u...
a9772fb5964a06dc1bcf4c26e18b6d25c2532487
sauravprakashgupta/ticTacToe
/ticTacToe.py
3,466
3.6875
4
from tkinter import * import tkinter.messagebox mainWin = Tk() mainWin.title("Tic Tac Toe") click = True def checker(buttons): global click if buttons["text"] == " " and click == True: buttons["text"] = 'X' click = False elif buttons["text"] == " " and click == False: buttons["tex...
eb1a2a2405dc1e52ea31395552c5bc140ba43fd0
sl-as-kj/tbl
/tbl/commands.py
3,321
3.578125
4
""" Command interface Commands are named, user-accessible operations. To create a command, decorate a function with the `@command()` decorator. The name of the command is constructed from the function name. The function may take any of these arguments: - `mdl` -- the model - `ctl` -- the controller - `vw` -...
145c271256c0b6299aed90cef66d14ea09ea8ba6
thomas-rohde/Classes-Python
/classes/a.10/aula18.py
418
3.53125
4
#test = [] #test.append('Gustavo') #test.append(40) #guys = [] #guys.append(test[:]) #test[0] = 'Maria' #test[1] = 22 #print(test, guys[0][1]) galera = list() dado = [] for c in range(0, 5): dado.append(str(input('Qual é o seu nome? '))) dado. append(int(input('Qual é a sua idade?'))) galera.append(dado[:])...
a04423b24c66f1ad94c3a2562be69fb874f7081e
thomas-rohde/Classes-Python
/exercises/exe11 - 20/exe012.py
173
3.671875
4
tc = float(input('A temperatura atual em ºC é ')) tk = tc + 273 tf = 9 * tc / 5 + 32 print('Convertendo {:.2f}ºC, resultamos em {:.2f}ºF e {:.2f}K'.format(tc, tf, tk))
57ebe82b5f60e68b215e805ac6a44a38ba9675b8
thomas-rohde/Classes-Python
/exercises/exe71 - 80/exe078.py
1,145
3.625
4
#nu = [] #i = n0 = n1 = n2 = n3 = n4 = 0 #for c in range(0, 5): # n = int(input('Digite um valor: ')) # if c == 0: # n0 = n1 = n2 = n3 = n4 = n # i = 0 # elif n < n0: # i = 0 # n0 = n # elif n < n1: # i = 1 # n1 = n # elif n < n2: # i = 2 # n2 = n # ...
6a272d9887c28f3171ca4807de08427e26c795d7
thomas-rohde/Classes-Python
/exercises/exe21 - 30/exe028.py
136
3.90625
4
n = int(input('Insira um nº: ')) if n % 2 == 1: print('O nº {} é ímpar'.format(n)) else: print('O nº {} é par'.format(n))
7eb3155133f8c2ea0432b3d9cd3e88ede45f7638
thomas-rohde/Classes-Python
/exercises/exe41 - 50/exe049.py
337
3.84375
4
#x = int(input('Digite o primeiro termo da progressão: ')) #r = int(input('Digite a razão: ')) #for s in range(0, 10): # print(x + r*s, ' ', end='-> ') #print('Acabou!') x = int(input('Primeiro termo: ')) r = int(input('Razão: ')) d = x + (10 - 1) * r for c in range(x, d, r): print('{} '.format(c), end='-> ') pr...
2253a2dd423feb793c431f56abc887fcb8fdb7df
thomas-rohde/Classes-Python
/exercises/exe21 - 30/exe026.py
325
3.59375
4
from random import randint from time import sleep print('-'*30) d = int(input('Eu escolho um número entre 0 e 5, tente adivinhar qual: ')) print('-'*30) f = int(randint(0, 5)) print('PROCESSANDO...') sleep(2) if f == d: print('Parabéns, você vençeu') else: print('Que pena, você perdeu, eu escolhi {}'.format(f))
ab831612bbff1a31713d19078790c27824580f48
thomas-rohde/Classes-Python
/exercises/exe31 - 40/exe039.py
381
3.859375
4
from datetime import date a = date.today().year i = int(input('Ano de Nascimento: ')) e = a - i if e > 25: print('Você é da categoria MASTER') elif 19 <= e < 26: print('Você é da categoria SÊNIOR') elif 15 < e <= 18: print('Você é da categoria JÚNIOR') elif 9 < e <= 14: print('Você é da categoria INFANT...
d6510372b7e607fd7c9d772a25e24ff70ce73971
thomas-rohde/Classes-Python
/exercises/exe31 - 40/exe037.py
424
3.75
4
from datetime import date a = int(input('Qual o seu ano de nascimento? ')) a0 = date.today().year i = a0 - a print('Quem nasceu em {} tem / vai fazer {} em {}'.format(a, i, a0)) if i == 18: print('Você deve se alistar \033[4:31mIMEDIATAMENTE\033[m') elif i > 18: print('Você deveria ter se alistado faz {} ano(s)...
bc36e88075c3b49eee07443062ec0e8d5890d014
thomas-rohde/Classes-Python
/exercises/exe11 - 20/exe015.py
530
3.875
4
'''Calcula a hip com base em pit''' '''from math import sqrt, pow print('Digite os lados do triângulo retangulo:') print('-' * 39) l0 = float(input('Digite o 1º lado(co): ')) l1 = float(input('Digite o 2º lado(ca): ')) print('-' * 39) print('O traiângulo formado tem como hipotenusa:\n{:.2f}'.format(sqrt(pow(l0, 2) + ...
a8649c47745c91efc9595c1599ad0e3a8a6c8874
thomas-rohde/Classes-Python
/exercises/exe21 - 30/exe027.py
207
3.796875
4
v = float(input('Insira a velocidade do carro, em Km/h: ')) a = ((v - 80)*7) if v <= 80: print('Tudo nos conformes') else: print('Deverá pagar uma multa por andar a {}Km/h de R${:.2f}'.format(v, a))
ca401cde5571a528f22946fccffd874d7ab257cc
thomas-rohde/Classes-Python
/exercises/exe01 - 10/exe002.py
114
3.765625
4
a = input('Digite algo: ') print ('O tipo primitivo de ', a, 'é', type(a)) print('Algo é maiusculo', a.isupper)
cad2da5749dbf125dbb2e043414ea068335a858c
thomas-rohde/Classes-Python
/classes/a.00/aula07.py
369
4.0625
4
n1 = int(input('Digite um nº:')) n2 = int(input('Digite outro nº:')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 dr = n1 % n2 p = n1 ** n2 r = n1 ** (1/n2) print(f'A soma é {s:~<5}. A multiplicação é {m:=>5}. A divisão é {d:°^5}, enquanto a divisão inteira é {di}, com resto {dr}.') print ('A elevação é {}, enquan...
2fb556cae35579049a155f491f27aceb614476c3
thomas-rohde/Classes-Python
/exercises/exe11 - 20/exe020.py
371
3.890625
4
nome = str(input('Qual é o seu nome? ')).strip() print('''O seu nome apenas em letras garrafais (porém amigáveis) é {} Já em letras minusculas {}. Seu nome possuí {} letras. Seu primeiro nome tem {} '''.format(nome.upper(), nome.lower(), len(nome) - nome.count(' '), nome.find(' '))) #separa = nome.split() #print('Seu ...
5d0655b2379cdf0af26511a248c090505ca6717f
thomas-rohde/Classes-Python
/exercises/exe61 - 70/exe067.py
541
3.578125
4
c = '' m = s0 = f20 = 0 print('=' * 22) print('Cadastrador de Pessoas') print('=' * 22) while c == 'N': i = int(input('Idade: ')) s = str(input('Sexo [ M / F ]: ')).strip().upper()[0] print('-' * 22) if i >= 18: m += 1 if s == 'M': s0 += 1 elif i < 20 and s == 'F': f20 +=...
5b375097d5639da61e0542b472ad2433f463a946
thomas-rohde/Classes-Python
/exercises/exe31 - 40/exe038.py
301
3.8125
4
n0 = float(input('Primeira nota: ')) n1 = float(input('Segunda nota: ')) m = (n0 + n1) / 2 print('A média das notas {} e {} dá {}'.format(n0, n1, m)) if m >= 7: print('Parábens, você foi APROVADO!') elif m <= 4: print('Você foi REPROVADO') else: print('Você está de RECUPERAÇÃO!')
7d026dde4c9f42156aad5c54c6b091bbd7b56c5f
yohei-freelance/atcoder
/abc/164/d.py
294
3.53125
4
s = str(input()) numbers = [] current_num = 2019 while current_num < 200000: numbers.append(str(current_num)) current_num += 2019 ans = 0 for i in range(len(s)+1): for j in range(i+3, len(s)+1): focus = s[i:j] if focus in numbers: ans += 1 print(ans)
146463ed98354255c2560b7462d268ae2e6b0c9b
Dusernajder/Tic_tac_toe_teamproject
/tic-tac-toe.py
8,698
3.75
4
import re import math import os import time import random from Image import image from Color import Color def init_board(): # Misi """Returns an empty 3-by-3 board (with zeros).""" return [[0, 0, 0] for i in range(3)] """ ###### Additional Methods ###### """ def clear(): """Clears the screen.""" ...
f7add68103512616914d9765652650a2082a0b3e
zlohner/DatalogInterpreterPy
/Scanner.py
4,020
3.53125
4
#!/usr/bin/env python import os from Token import Token keywords = { 'Schemes' : 'SCHEMES', 'Facts' : 'FACTS', 'Rules' : 'RULES', 'Queries' : 'QUERIES' } class Scanner(object): def __init__(self): self.file = None self.c = None self.tokens = [] self.lineNum = 1 def __str__(self): sb = [] for token in...
3400ffad90230452301d74dd26d8c1524188ec76
RodColson/Python-Projects
/Sandbox/dict.py
1,286
4.0625
4
# Creating an empty dictionary data = {} # OR data = dict() # Creating a dictionary with initial values data = {'a':1,'b':2,'c':3} # OR data = dict(a=1, b=2, c=3) # OR data = {k: v for k, v in (('a', 1),('b',2),('c',3))} # Inserting/Updating a single value data['a']=1 # Updates if 'a' exists, else adds 'a' # OR data...
8a8bada033325eafc36b3269ae1d48e2ddfc7d43
pan060757/mif_2019
/timeseries/data_of_month.py
1,116
3.5625
4
#-*-coding:utf-8-*- ''' 构造月份数据集 ''' # load dataset # 加载数据 from pandas import read_csv data_input= read_csv('dataset/workerCostByMonth.csv', header=None) ##### data_input.columns=['date','total_fees','group_fees','hospital_fees','h_groupfees','menzhen_fees','m_groupfees','hospital_count','menzhen_count','avg_hgroupfee...
22e0ac81a45590e2b4f562a042b2c0290705e7e5
ShraiLakshmanR/Python-Project
/Student_Managment_System/student_mentordb.py
761
3.8125
4
import sqlite3 def connectData(): con=sqlite3.connect("student_mentordb.db") cur=con.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS mentorlogin(student id TEXT NOT NULL PRIMARY KEY,fname TEXT NOT NULL,surname TEXT NOT NULL,dob TEXT NOT NULL,age NOT NULL,gender TEXT NOT NULL,address TEXT NOT NULL,mobil...
81998e32f82b3b0ae45faec3a8d5ffe6fc6d2b97
LargeLlama/softdev
/16_csv2db/db_builder.py
2,311
4.09375
4
#Team Old Money - Rubin P, Imad B. #SoftDev1 pd7 #SQLITE3 BASICS #2018-10-04 import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O DB_FILE="discobandit.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #facilitate db ops #==...
931943432e78a070699585b5ca933f3fd049ac6e
Serban1995/Proiect.Final
/quizapp.py
3,537
3.5
4
from tkinter import * from tkinter import messagebox as mb import json root = Tk() root.geometry("800x500") root.title("Quiz") with open('quiz.json') as f: #deschidem fisierul jason dupa care transformam obiectele din el in fisiere la noi in program obj = json.load(f) q = (obj['ques']) options = (obj['options'])...
866a0dfca82922a91cedc09695d7b035100bb808
HarshitVerma1/All_Courses
/Rice-Python-Data-Analysis/week2/tabular_data_matrix.py
414
4.09375
4
# -*- coding: utf-8 -*- """ @author: salimt """ NUM_ROWS = 3 NUM_COLS = 5 # construct a matrix my_matrix = {} for row in range(NUM_ROWS): row_dict = {} for col in range(NUM_COLS): row_dict[col] = row * col my_matrix[row] = row_dict print(my_matrix) # print the matrix for row in range(NUM_RO...
9d6bd773a3402250cd88be44ed1388540f146b0f
ImdadMiran17/AI-Exercises
/chatbotJordan.py
1,447
3.59375
4
from functions import * # create chatbot home_bot = create_bot('Jordan') # train all data train_all_data(home_bot) # check identity identity = input("State your identity please: ") # rules for responding to different identities if identity == "Mark": print("Welcome, Mark. Happy to have you at home.") elif ide...
e3c0d00e09c4d22d56215e836bc4c7738d5a8c36
mazza72/PacMan
/PacManPlayer.py
4,505
3.65625
4
#Locations of Pac-Man movement sprites in the spritesheet. START = (489,1,14,14) RIGHT1 = (457,1,14,14) RIGHT2 = (473,1,14,14) LEFT1 = (457,17,14,14) LEFT2 = (473,17,14,14) UP1 = (457,33,14,14) UP2 = (473,33,14,14) DOWN1 = (457,49,14,14) DOWN2 = (473,49,14,14) #Locations of Pac-Man death sprites. DEATHSPRITES = [(505...
c29dad78f223a38fb7504bac3c992816335c9072
Nithin-gitweb/Data-science-and-analytics-using-python
/17. Seaborn_exercises.py
1,005
3.53125
4
import matplotlib.pyplot as plt import seaborn as sb import numpy as np var = sb.load_dataset('titanic') print(var.head(2)) sb.set_style(style='whitegrid') sb.jointplot(x='fare',y='age',data=var) plt.show() #Replicates the titanic data as a scatter plot graph sb.distplot(var['fare']) plt.show() #Replicates t...
c634ed9bbea10cc35abea403cd66cca87242c032
Kmedrano101/PlanificacionRutas
/Codigo B (Python)/Algoritmo_B.py
3,330
3.59375
4
""" Algoritmo de busqueda de ruta corta tipo Greedy basado en A* By Kevin Medrano Ayala Date: 24/10/2020 1: Obstacle 2: Start 3: End 8: Visited """ import csv print("Start!") # Clase Nodo class Nodo: def __init__(self, x, y, distancia,myId,parentId): self.x = x self.y = y self.distancia...
ae9df6d6ac28fad9c47e66675de51be85f39502a
Revold1/PJC-CS
/data-structures/queue/queue.py
1,011
4.03125
4
from node import Node class Queue: def __init__(self): self.front = None def enqueue(self, new_data): """Add a new node to the rear of the queue.""" new_node = Node(new_data) current = self.front if current is None: self.front = new_node else: ...
5767e3a4613cda94c090a4ddf65e1b58f9ccdc8d
Revold1/PJC-CS
/exercises/2015-prelim/task-2/task_2_3.py
1,023
3.828125
4
test_array = [435, 646, 344, 54, 23, 98, 789, 212, 847, 201, 733] test_array2 = [999, 854, 643, 321, 289, 111, 95, 47, 12, 0] def Quicksort(ThisArray, First, Last): ThisArray[-1] = ThisArray[-1] + 1 # increment function call count Low = First High = Last Pivot = ThisArray[Low] while Low <= High...
5c1c18ade1953ee419cdb050b71b7565f7dd2379
Revold1/PJC-CS
/exercises/pc13-linear-equation/linear.py
1,786
3.90625
4
# NOTE: this code can also handle variables with no explicit coefficients # e.g. 'x', '-x', '+x' def get_terms(string): """Return a list of terms found in a string. e.g. "-3x+7+x" => ['-3x', '+7', '+x'] """ terms = [] term = string[0] for c in string[1:]: if c in ('+', '-'): ...
0c184109da884694f779ced6a1e1284a1d3a4d11
Revold1/PJC-CS
/exercises/2015-j2-elearning/decoder.py
1,021
3.734375
4
def decoder(): with open("textstream.txt", 'r') as infile: textstream = infile.read() integers = [int(i) for i in textstream.split(',')] # make a list containing each integer from the text stream punctuations = ['', '!', '?', ',', '.', ' ', ';', '"', "'"] decoded = "" # final ou...
0caf51f5f67177067d1b0a31fc2582f27f078475
Revold1/PJC-CS
/exercises/2015-dunman-prelim/task-3/task_3_5.py
505
3.90625
4
def Hash_Key(isbn): isbn = ''.join(isbn.split('-')) # Parse ISBN into string of numbers only. ascii_sum = 0 for c in isbn: ascii_sum += ord(c) # Obtain a value likely unique to each ISBN. address = ascii_sum % 251 # Generate an address to insert each ISBN into. bucket = 7 - as...
cbbcbb53dde869544981a36bb276e23a631504d1
Revold1/PJC-CS
/exercises/2015-j2-common-test/task-2/task_2_1.py
892
3.953125
4
def get_cc_num(): while True: cc_num = input("Enter credit card number: ") if cc_num.isdigit(): if len(cc_num) == 16: if (cc_num[0] == '4' or 51 <= int(cc_num[:2]) <= 55): return cc_num elif len(cc_num) == 13: ...
89a78125885f791c6a3a069cfe3c07da780022ad
Revold1/PJC-CS
/data-structures/stack/stack.py
930
3.890625
4
from node import Node class Stack: def __init__(self): self.top = None def push(self, new_data): """Add a new node to the top of the stack.""" temp = self.top self.top = Node(new_data) self.top.setPtr(temp) def pop(self): """Remove the node at the top of ...
3898123f67a821273687180030ed885c5bf6a267
Revold1/PJC-CS
/exercises/2015-dunman-prelim/task-3/task_3_4.py
330
3.8125
4
from task_3_1 import ISBN_Check_Digit def ISBN13_To_ISBN10(isbn): isbn = isbn[3:] check_digit = ISBN_Check_Digit(isbn) isbn10 = isbn + "-" + check_digit if isbn10[0] == '-': # return isbn without leading '-' return isbn10[1:] else: return isbn10 print(ISBN13_To_ISBN10("978-0-07-...
612b31ba576a4bee474b525f577e1b84f7cdacd8
Revold1/PJC-CS
/exercises/pc09-linked-list-fruits/task_3_7.py
340
3.59375
4
def TraversalInReverseOrder(self, Index, stack=[]): if Index != 0: stack.append(self.Node[Index].get_data()) self.TraversalInReverseOrder(self.Node[Index].get_ptr(), stack) else: while len(stack) != 0: print(stack.pop()) def ReverseTraversal(self): self.TraversalInRever...
2b11fd0bb761e059ebe198df7d2d60dd90f32388
Revold1/PJC-CS
/exercises/pc09-linked-list-fruits/task_3_2.py
3,751
3.84375
4
class ListNode: def __init__(self, data="empty string", ptr=0): self.DataValue = data # string self.PointerValue = ptr # integer def get_data(self): return self.DataValue def set_data(self, new_data): self.DataValue = new_data def get_ptr(self): return self....
f1ade52e52c65e353e9d40147cdbd1450e1e00f9
Revold1/PJC-CS
/exercises/2014-dunman-prelim/task-3/everything.py
2,404
3.578125
4
class Node: def __init__(self, Item_ID, Type, Title, Status): self.LeftP = None self.Data = [int(Item_ID), Type, Title, Status] self.RightP = None def getLeftP(self): return self.LeftP def setLeftP(self, new_ptr): self.LeftP = new_ptr def getRightP(self): ...
424de3a791f5bed0206fd7c705b5e4ce994cbac5
Revold1/PJC-CS
/exercises/oop-tutorial/03_bank_class.py
4,022
3.90625
4
class BankTransaction(): ''' Class representing tha main bank account for a user, which itself can contain multiple sub-accounts ''' def __init__(self): '''Parameters: None''' self.account = [] self.count = 0 def openAcc(self): ''' Opens an account for...
ead66c48d9ec689ed0fa5f7d72be2a69e2842019
Sarthaks21/Naive-Bayes-from-Scratch
/naiBayes.py
2,945
3.65625
4
import pandas as pd '''This dataset has various features that decide whether a person will play golf or not''' data = pd.read_csv('golf2.csv') print(data.shape) data.head() #Encoding the labels to 0(No) and 1(Yes) for i in range(14): if data['label'][i] == 'No': data['label'][i] = 0 elif da...
b3ceb97e8e03769ea3f62caf7a85e3a2a14eff03
oli360/SQL_Assignment
/Most_Surface_Area.py
7,507
3.765625
4
# python used to answer Question 3: (SQL) Which artist is created the most artwork by total surface area? from SQL_Helper import * conn = get_connection() # retrieve connection to database c = conn.cursor() # get the cursor to execute SQL queries # relatively simple SQL select statement to retrieve the surface are ...
18f97a596ccdcdd8af666263e585e9a8b69f6d61
oli360/SQL_Assignment
/Who_Lived_The_Longest.py
1,113
4.03125
4
# python file used to answer question 1: (SQL) Which artist in this data set lived the longest? from SQL_Helper import * conn = get_connection() # get connection c = conn.cursor() # get cursor # SQL query to retrieve the oldest artist sql_query=('SELECT ' 'Name, Nationality, MAX(\"Death Year\"-\"Bir...
42ef03068009940196467561e874c2885c3b7ef7
RagingLeviathan/useful_python
/check_uniqueness.py
226
3.84375
4
def unique(l): if len(l) == len(set(l)): print("All elements are unique") else: print("List has duplicates") unique([1, 2, 3, 4]) # All elements are unique unique([1, 1, 2, 3]) # List has duplicates
5d751e977f9c9fe0d93c39364f4349e56d38826a
RagingLeviathan/useful_python
/use_list_comprehensions.py
92
3.53125
4
numbers = [1, 2, 3] squares = [number**2 for number in numbers] print(squares) # [1, 4, 9]
e959d78b6ed5b1c8557fd530e5a6e7f93ae0cd33
ksh5324/python_pra
/repeat.py
121
3.78125
4
fruits=['apple', 'banana', 'cherry'] print(fruits) for i in 'banana': if i=='n': break print(i, end=' ')
ff68d2cda8c138ebdd8b3fccbb94f9bd5e1be108
pablobezard/pythonaprendiendo
/set.py
221
3.59375
4
colors = {'red' , 'green' , 'blue'} print(colors) print('red' in colors) #pregunta boolean print(colors.add('violet')) #añadir elemento colors.remove('red') #remueve elemento print(colors) colors.clear() print(colors)
ac5913fbbeeb992387f27189989d121639b7dc99
ckabuloglu/interview_prep
/lineSegmentIntersection.py
1,598
3.640625
4
''' Given two line segments (xStart, yStart, xEnd, yEnd), find and return the intersection point if it exists If it doesn't exists, or if they're parallel, return nil. It's guaranteed that x values are increasing ''' import numpy as np # Define the function def findIntersect(point1, point2): # Check if the points...
ce4f1a0dfc6a33f53622ede4aceacd70b3831df6
ckabuloglu/interview_prep
/isConnected.py
804
3.796875
4
''' Cracking the Coding Interview 4.1 Route Between Two Node: Given a graph, find if there's route between two given nodes ''' def isConnected(graph, n1, n2): visitList = list(graph[n1]) visited = set() visited.add(n1) while visitList: currentNode = visitList.pop(0) if currentNode == n...
0eab1ed437e774dfec150f02150884343d041d54
ckabuloglu/interview_prep
/maximumSubarray.py
564
3.703125
4
''' Maximum sub-array Leetcode Given an array with at least 1 element, return the sum of a sub-array with the maximum sum ''' def maxSum(nums): mx = nums[0] until = nums[0] for i in range(1,len(nums)): until = max(until + nums[i] , nums[i]) mx = max(mx, until) return mx a ...
49df02fa0471bc2df5c283df9cb6208d789c3810
ckabuloglu/interview_prep
/magicIndex.py
776
4.0625
4
''' Cracking the coding interview 8.3 p. 135 Magic Index: A magic index in an array A[1. .. n-1] is defined to be an index such that A[i] i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. ''' # Wrapper function def magic(arr): return findMagic(arr, 0, l...
dd936881514bcd8bf7c628183ecbc376b0c2758a
ckabuloglu/interview_prep
/getFactors.py
489
3.734375
4
''' Get Factors of a given number https://leetcode.com/problems/factor-combinations/?tab=Description ''' def getFactors(n): results = [] helper(results, [], n, 2) results.pop() return results def helper(results, current, n, start): if n == 1: results.append(list(current)) for i in ran...
8da21b78fd90a65b70bb461f0370564724ab1dc8
ckabuloglu/interview_prep
/levelOrder.py
939
4.15625
4
''' Level Order Traversal Given a binary tree, print the nodes in order of levels (left to right for same level) ''' # Define the Tree structure class BSTNode: def __init__(self, val): self.val = val self.left = None self.right = None # Define the add method to add nodes to the tree def ad...
d4d4b264108424df39b1b3801269430ad2727379
qmulosoft/nimbus-store
/src/nimbus_store/models/model.py
5,084
3.875
4
from abc import ABC, ABCMeta, abstractmethod import typing class Field: """ Represents a single field on a data model class """ def __init__(self, description: str, _type, writable=True, name=None): self._name = name self._desc = description self._type = _type self._writable = ...
1f437cd94401af97ae898767a64bf24e36c674e1
Garrison50/unit-2-brid
/1.3.1 temp conv.py
195
4.0625
4
def main (): farenheit = int(input("What is the Farenheit temperature?")) celcius = (farenheit - 32) * 5/9 print ("The temperature is", round(celcius, 1), "degrees Celcius!") main()
2c50bed4074123edcc2f4feab539c300a65071be
Garrison50/unit-2-brid
/2.3 Vol/SA.py
279
4.15625
4
def main(): import math radius = float(input("Enter the radius of the sphere")) volume = ((4/3) * math.pi * (pow(radius,3))) sa = (4 * math.pi * (pow(radius,2))) print ("The volume is:", round(volume,2)) print ("The surface area is:", round(sa,2)) main()
ab64fec4326517b59ff574b0d4a9e8ad7200d92f
shakyaruchina/100DaysOfCode
/dayTwo/lifespan.py
375
3.921875
4
# Life in weeks # Number of days/months/weeks left to turn 90years old from the current age. #user input age age = input("What is your current age? ") #90-current age life_span = int(90-int(age)) days = life_span *365 weeks = life_span *52 months = life_span *12 #printing the result inside f-strings print(f"You have...
643730d15360ecc6c8e59db671e489a17932fe08
shakyaruchina/100DaysOfCode
/dayTen/calculator.py
1,182
4.25
4
#Calculator from art import logo #add function def add(n1,n2): return n1+n2 #subtract functuon def subtract(n1,n2): return n1-n2 #divide function def divide(n1,n2): return n1/n2 #multiply function def multiply(n1,n2): return n1*n2 #operation dictionary{key:value} operations = { "+":add, "-":s...
2b9f93427a8c0a60d9696f81d845ba945a1a4047
shakyaruchina/100DaysOfCode
/dayNine/blind_auction.py
876
4.0625
4
bids={} bidding_finished = False #bidding record = dictionary: records all the inputs def highest_bidder(bidding_record): #{Name: Value, Name:Value} highest_bid = 0 winner= "" for bidder in bidding_record: #Dictionary to get value biddingrecord[bidder] bid_amount = bidding_record[bidde...
c9fd197ab1a1073d7fdf168e8be9cd6438b0ba1f
shakyaruchina/100DaysOfCode
/dayFive/loops.py
276
4
4
#Loops #for loops #for item in list_of_items: fruits = ["Apple", "Peach", "Pear"] for fruit in fruits: print(fruit) print(fruit + "Pie") #range function #for number in range(a,b): (1-9) total = 0 for number in range(1,101): total += number print(number)
a58ba97557f749e5c7a7e0db04224662f7918ba4
rubenbuelvas/IFT3335-TP1
/sudoku_norvig.py
22,359
3.859375
4
## Solve Every Sudoku Puzzle ## See http://norvig.com/sudoku.html ## Throughout this program we have: ## r is a row, e.g. 'A' ## c is a column, e.g. '3' ## s is a square, e.g. 'A3' ## d is a digit, e.g. '9' ## u is a unit, e.g. ['A1','B1','C1','D1','E1','F1','G1','H1','I1'] ## grid is a grid,e.g. 81...
ace0bd1709f3fa950ce81c470bfc3251cfa924ae
Dimitreus/PE
/PE_10.py
454
3.8125
4
import math import time def is_prime(number): if number < 2: return False elif number == 2: return True for check in range(2, int(math.sqrt(number)+1)): if number % check == 0: return False return True ctime = time.time() i = 1 result = 0 primes = [2] while i < 2000000: if is_prime(i): result += i ...
331be087e096aa00f393babc02da88034d383c14
rafaelzottesso/2019-ES-Algoritmos
/aula25_selecao.py
1,163
3.953125
4
vetor = [30, 10, 40, 50, 20, 8] print("Vetor original:", vetor) print("Tamanho do vetor:", len(vetor)) print(" ") # Ocupar a posição do vetor que procura-se o menor para ele for x in range(0, len(vetor)-1): menor = x # Fazer as verificações no vetor do x em diante for y in range(x+1, len(vetor))...
0b2177fde6932b3582c9b3552507c587a3b2398e
rafaelzottesso/2019-ES-Algoritmos
/aula18_vetor_e_while.py
595
3.9375
4
x = int(input("Tamanho: ")) vetor = [0] * x # Exemplo com valores do próprio programa pos = 0 while( pos < len(vetor) ): vetor[pos] = pos + 1 pos = pos + 1 print(vetor) # Exemplo com usuário Preenchendo os valores do vetor # pos = 0 # while( pos < len(vetor) ): # vetor[pos] = int(input("Número: ")) # # ...
827904d6c3c5dd080ce6b3b353967d2f1cc52131
rafaelzottesso/2019-ES-Algoritmos
/aula11-while.py
1,168
4.21875
4
""" -- Estrutura básica do laço de repetição while -- variável de controle iniciada while(condição): . . . incremento da variável de controle """ # # Variável de controle iniciada # cont = 1 # # Condição do while montada de acordo com a variável de controle # while( cont <= 1000 ): # # Código a s...
7915f253573e2652d0a02218b6c0bdaac57aed48
leticiafs2020/Exercicio_Problema_Design_de_Software
/Jogo_Craps_com_uma_opcao_de_aposta.py
7,478
4.25
4
#Design de Software - Exercíçio Problema 1 #Jogo Craps Insper #Criadora: Letícia Sanchez #Esse programa permite realizar apenas uma aposta por vez import random print("Olá") nome = input("Qual o seu nome?") print("Bem-vindo(a) ao Craps, {0}!".format(nome)) # Cada jogador começa cada um com 1000 fichas - Declaração...
256152df2f536fd43ac28fa163616f6030ecda2c
AjinkyaPawale/Artificial-Intelligence
/Games and Bayes/part2/SebastianAutoPlayer.py
17,726
3.828125
4
# Automatic Sebastian game player # B551 Spring 2021 # PUT YOUR NAME AND USER ID HERE!: cdeshpa-ajpawale-svogiral-a2 # # Based on skeleton code by D. Crandall # # # This is the file you should modify to create your new smart player. # The main program calls this program three times for each turn. # 1. First it calls...
37edcb18d99535368bed81e37733a64e655a0e4f
Ezan/Missionaries-and-Cannibals
/boat.py
776
3.59375
4
class boat: width = 70 height = 80 def __init__(self, x, y, pos,image1,image2, win): self.x = x self.y = y self.pos = pos #position of boat i.e. 2,3,4,5 self.image1 = image1 self.image2 = image2 self.win = win def highlight...
f5f7981d6de2145addb0f3eb3ef2963be160ee42
Ayaanfaraz/CricAnalysis
/extractTest.py
690
3.59375
4
testString = 'jxfbanana1jxfbanana2jxfbanana3jxf' # while True: # firstPos = testString.find('ban') # secondPos = testString.find('jxf',firstPos) # fruit = testString[firstPos:secondPos] # print(fruit) # previousFruit = fruit # if count >1 and fruit == previousFruit: # break # could make a function and rec...
f1824d01ca004c3c289408d84fc6c1b552b451c2
j6k4m8/headline-parser
/NewsSource.py
811
3.6875
4
class NewsSource(object): """ A class to hold a single news source, such as an RSS feed or simply a manually entered list of article texts. """ def __init__(self, name): """ Constructs a parent class for a generic NewsSource. """ self.articles = [] self.name ...
14f102a80b773471dfdc6597c32f8edbb0d784b1
Fictions1337/directory-sorting-tool
/main.py
1,187
3.9375
4
import os import shutil user_input = input("Enter full path to directory that will be sorted: ").replace("\\", '/') if user_input.endswith('/'): PATH = user_input else: PATH = user_input + '/' # <----------------------- Funcions -----------------------> def files(path): for file in os.listdir(pa...
245f5b433f1b6f9297e5161161d6081a4c1bc7b0
jeremykardash/databootcamp-homework
/Unit 3 - Python Challenge/PyBank/main.py
1,954
3.671875
4
import os import csv month = [] revenue = [] revenue_ch = [] monthly_ch = [] #import budget data filepath = os.path.join("PyBank", "Resources", "budget_data.csv") with open(filepath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csvheader = next(csvreader) #months for row in csvr...
4f6d15c068cce2a7b00df861c2feea7d41a326cb
SamanehGhafouri/DataStructuresInPython
/doubly_linked_list.py
2,468
4.125
4
# Doubly Linked List # Advantages: over regular (singly) linked list # - Can iterate the list in either direction # - Can delete a node without iterating through the list (if given a pointer to the node) class Node: def __init__(self, d, n=None, p=None): self.data = d self.next_node = n ...
b9f3804dd5b9d082d41cfb38a3f542c3b058ddcd
eoja82/cs50
/Into_To_Computer_Science/Week6Python/readability/readability.py
1,242
3.9375
4
from cs50 import get_string import math """ use Coleman-Liau formula to test grade level of input text """ def main(): text = get_string("Text: ") letters = countLetters(text) words = countWords(text) sentences = countSentences(text) l = (letters / words) * 100 s = (sentences / words) * 100 ...
76af9c5bcb70a6e44f3b2e931c3d7981392c7abe
eoja82/cs50
/Into_To_Computer_Science/Week6Python/cash/cash.py
876
3.71875
4
from cs50 import get_float import math def main(): changeOwed = -1 coinCount = 0 while changeOwed <= 0: change = get_float("Change owed: ") changeOwed = round(change, 2) * 100 if changeOwed >= 25: coins = getCoins(changeOwed, 25) coinCount += coins changeOwed ...
1c8bed250e8ff0cc4c5b04f2ca3d37508025f693
EG-easy/exponentialcalculator
/test1.py
162
3.546875
4
def pow0(x, n): value = 1 for i in range(n): value *= x return value x = 4989 n = 1000000 mod = 123456789 answer = pow0(x, n) % mod print(answer)
27eb61e6178807230557be14222b31abc79b27d7
dheerajj007/india-state-guessing-game
/main.py
1,156
3.71875
4
import turtle import pandas as pd from state import State screen = turtle.Screen() screen.title("India State Guessing Game") image = "india.gif" screen.addshape(image) turtle.shape(image) state_answer = screen.textinput(title="Guess the State", prompt="What's another state's name?").title() data = pd.read_csv("28_st...
ab213af605211e8b766ca76a48441e2e5d3595c6
sdshah5796/Data-Structures
/PycharmProjects/Data-Structures/Trees/level_order_traversal.py
1,240
4.09375
4
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def height(root): if not root: return 0 lheight = height(root.left) rheight = height(root.right) if lheight > rheight: return lheight + 1 else: return rheig...
28526854b1941d63b8a1e2ffb47928265fb9331e
sdshah5796/Data-Structures
/PycharmProjects/Data-Structures/Trees/inorder_traversal.py
955
4.0625
4
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def inorder_traversal_recurrsion(root): if root: inorder_traversal_recurrsion(root.left) print(root.data, end = " ") inorder_traversal_recurrsion(root.right) def inorder_tr...
08420184e30cf36b59b1cf4839740e39b3d94cca
sdshah5796/Data-Structures
/PycharmProjects/Data-Structures/Strings/pallindrome_permutation.py
286
3.765625
4
# Cracking the coding interview: 1.4 def pallindrome_permutation(str): letter_count = [0] * 128 for i in str: letter_count[ord(i)] +=1 count = 0 for i in letter_count: count += i%2 return count <=1 str ="abbc" print(pallindrome_permutation(str))
b76b31f313d6e6de3cb2a32529ded80c0ecca5ae
jdabel123/UdacityProject2-DisasterResponsePipeline
/data/process_data.py
3,085
3.625
4
import sys import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): ''' Function to load two CSV files and return a merged dataframe on Id. INPUT - messages_filepath, categories_file expected strings OUTPUT - merged single dataframe ...
85259ff277b4276883648568c88127f2edffd82a
tedda42/PaperScissorsRock-Other
/PaperScissorsRock.py
1,028
3.984375
4
from sys import stdin from random import random print "Do you choose rock, paper or scissors?" userChoice = stdin.readline().rstrip() computerChoice = random() if computerChoice < 0.34: computerChoice = "rock"; elif computerChoice <= 0.67: computerChoice = "paper"; else: computerChoice = "scissors"; print ...
1eba475a2ad3f55f1a590a40f9b29af754a8f1fa
Darkeran/Python3
/Exercicios/LoopW_Popul_2.0.py
711
3.90625
4
# Altere o programa anterior permitindo ao usuário informar as populações e as taxas de crescimento iniciais. # Valide a entrada e permita repetir a operação. População_A = int(input("População A: ",)) Taxa_Cres_A = float(input("Taxa de Crescimento da população A: ",)) População_B = int(input("População B: ",)) T...
75ddb9f91a898d005c0cf8f52a51da372966cf48
Darkeran/Python3
/Exercicios/Intervalo.py
981
4.09375
4
# Faça um programa que leia uma quantidade indeterminada de números positivos e conte quantos deles estão nos # seguintes intervalos: [0-25], [26-50], [51-75] e [76-100]. A entrada de dados deverá terminar quando for # lido um número negativo. X = True Contador_0_25 = 0 Contador_26_50 = 0 Contador_51_75 = 0 Contado...
32743d6ea7dd7050e96fc9c4f7c33988411e442e
Darkeran/Python3
/Exercicios/Bissexto.py
297
3.953125
4
# Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se este ano é ou não bissexto. ano = int(input("Insira o ano:", )) if (ano % 4 == 0 and ano % 100 != 0) or ano % 400 == 0: print("O ano é bissexto") else: print("O ano não é bissexto")
de3737142b286b86ef9f2104b24ac79de64c5a0d
Darkeran/Python3
/Exercicios/LoopW_Par_Impar.py
451
4
4
# Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a quantidade de números impares. Lista_Impar = [] Lista_Par = [] loop = 0 while loop < 10: Numero = int(input("Digite um número inteiro: ",)) loop = loop + 1 if Numero % 2 == 0: Lista_Par.append(Numero...
d16a5a86ee12545676d76241cf3a10d74e709455
Darkeran/Python3
/Exercicios/LoopW_Validação.py
1,289
4.28125
4
# Faça um programa que leia e valide as seguintes informações: # # Nome: maior que 3 caracteres; # Idade: entre 0 e 150; # Salário: maior que zero; # Sexo: 'f' ou 'm'; # Estado Civil: 's', 'c', 'v', 'd'; Nome = input("Digite seu nome: ") while len(Nome) < 3: Nome = input("Digite seu nome: ") Idade = int(...
761a8fdd5decb1490992489a7a216cc628740804
Darkeran/Python3
/Exercicios/LoopW_Num5.py
255
4.09375
4
# Faça um programa que leia 5 números e informe o maior número lista = [] Numero = 0 while Numero < 6: Maior_Num = int(input("Digite um número: ",)) lista.append(Maior_Num) lista.sort(reverse=True) Numero = Numero + 1 print(lista[0])
71be0802f2cff8cee6ceef5b0389af937d6ebd70
KorrMelen/Min-Makespan
/Min_Makespan.py
3,365
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from statistics import mean from math import ceil from sys import exit from time import time import Min_Makespan_Instance import Min_Makespan_Algos def input_choice(): c = input("""Choix du mode de saisie des instances d'entrée: 1 : Depuis un fichier 2 : Au clavier 3 ...
c6d21ece56ab80dccdf11ddc86b08790d35ab314
augustonz/Color-Theories
/src/ColorTheories/classes/Color.py
4,135
3.90625
4
import copy import math import operator # Implementação de Color: # - exemplo para criar uma cor independentemente de outra: # Color("nome", red=213, green="123", blue="0", alpha="50") # - exemplo para criar uma cor como resultado de um processo aditivo entre duas cores: # red = Color("red", 255, 0, 0, 255) # gre...
66352731d8b952a633dea499c56cc58903051b4d
nikitakumar2017/Assignment-4
/assignment-4.py
1,450
4.3125
4
#Q.1- Reverse the whole list using list methods. list1=[] n=int(input("Enter number of elements you want to enter in the list ")) for i in range(n): n=int(input("Enter element ")) list1.append(n) print(list(reversed(list1))) #Q.2- Print all the uppercase letters from a string. str1=input("Enter string ") for...
034091d4f57849e8ef82f5534f7665e15188ac68
victorknust/experimentosPython
/Livro-Usa-a-cabeca-Python/Desvio-Condicional/Desvio-Condicional.py
455
3.875
4
valor = 0 if valor < 0: print('Valor negativo') elif valor > 0 and valor < 100: print('Valor positivo menor que 100') elif valor > 0: print('Valor positivo') else: print('Valor zero') valor_string = 'string abc' the_list = [1, 2, 3, 4, 5] if isinstance(valor, int): print('valor é um int') if isi...
413958b6351cf01a519968f52f16d73dffab40b8
fansOnly/Python-test
/learning/常用内建模块/itertools_.py
2,859
4.25
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # itertools # itertools提供了非常有用的用于操作迭代对象的函数。 import itertools ######################################################################################### # count()会创建一个无限的迭代器 # natuals = itertools.count(1) # for n in natuals: # if n < 5: # print(n) # print('*'*...
71fe63cc6198bda93990140f347bd02f23cd4d97
fansOnly/Python-test
/learning/函数式编程/高阶函数/filter.py
1,572
4.09375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # ################################################################################### # filter # Python内建的filter()函数用于过滤序列。 # 和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 # example 1 # def is_odd(x): # return x % 2...
f35c63fe177902e0f75173ca0a7b7491447c0b15
fansOnly/Python-test
/learning/函数式编程/高阶函数/mapreduce.py
1,866
3.9375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################################ # map/reduce # def f(x): # return x*x # r = map(f, [1,2,3,4]) # print(list(r)) # from functools import reduce # def add(x, y): # return x + y # s = reduce(add,[1,2,3,...
cdfd0ea603a9a2cacb6ad606f5a78ce152b4bc73
fansOnly/Python-test
/learning/网络编程/UDP编程/server_.py
689
3.53125
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定端口 s.bind(('127.0.0.1', 9999)) # 创建Socket时,SOCK_DGRAM指定了这个Socket的类型是UDP。绑定端口和TCP一样,但是不需要调用listen()方法,而是直接接收来自任何客户端的数据: # recvfrom()方法返回数据和客户端的地址与端口,这样,服务器收到数据后,直接调用sendto()就可以把数据用UDP发给客户端。 print('bin...
708ce9f9b84ecd483e151e0d01f46dfba054472f
poettler-ric/infobw
/content/ws1617/_index.files/calc_solution.py
1,060
3.828125
4
from sys import argv def is_int(a): return a - int(a) == 0 def subtract(a, b): return a - b def handle_args(args): if len(args) == 2: n0 = float(args[0]) op = args[1] if op not in operations: print("not implemented") else: print(operations[op]...