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 |
|---|---|---|---|---|---|---|
dc262f3b25c6762ed2be19fa67a7cf54d82cce9e | GNLRaviTeja/Python | /11_bisectionCube.py | 875 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Studying approximate solutions using bisection search
Program to find cube root
Author: Kriyative Edge
"""
cube = int(input("Enter the integer to find cube root: "))
epsilon = 0.01
num_guesses = 0
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 - cube) >= epsi... |
7ef7fc04c0262670bb6e79ee1567612859f42b6d | GNLRaviTeja/Python | /arithmeticOperators.py | 166 | 3.5 | 4 | x = 'String'
y = 10
z = 5.0
print(x + x) # print command 1
print(y + y) # print command 2
print(y + x) # print command 3
print(y + z) # print command 4
|
0ad9fc82e0efdeae378a90156c15554b58140570 | GNLRaviTeja/Python | /Prog_2_csvProg.py | 2,138 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Generating a identifying missing parameters in the csv file
Author: Kriyative Edge
"""
#NOTE: Refer the below website for any type of real time datasets for understanding data, parsing data and understand real-time standards of
# analytics and machine learning
"""
https://archive.ics.uci.... |
474d703a55570439f8439e519ca69ee82cdd967b | mrlia/Strokes | /Stroke.py | 715 | 3.703125 | 4 | import pygame, math
class Stroke:
"""This class represents a player stroke."""
positions = []
def __init__(self,pos):
self.positions = []
if pos != None :
self.positions.append(pos)
def addPos(self, pos):
self.positions.append(pos)
def draw(self,surface):
prevPos = self.positions[0]
for pos in self... |
e6b67b88febcfec2ca03ebd7e93f39e36d793826 | Sawera-Ansari/Draughts | /board.py | 7,220 | 3.5 | 4 |
from piece import Piece
from variables import *
class Board:
def __init__(self):
self.board = []
self.white_pieces = self.black_pieces = 12
self.white_kings = self.black_kings = 0
self.set_board()
def draw_board(self, window):
window.fill(BLACK)
for row in r... |
1e02a62459ead67b4eac0975cba7063b7ca0a194 | jbrueno/nqueens_csp | /nqueens.py | 4,863 | 3.53125 | 4 | from copy import copy, deepcopy
class CSP: # full csp with variabless, domain, and constraints
def __init__(self, queens, doms, cons, rows):
self.queens = queens # list of all queens, the number of the queen is the column it will be placed in
self.doms = doms # dict mapping queen to its domain, the domain... |
51313b0157806b5d1fdbadb91602b7402971af68 | Kavya-K2001/Guess-game | /game in file.py | 1,787 | 3.578125 | 4 | import random
import os
import sys
stage = 1
getname = str(input("Enter the UserName : "))
FilePath = str(os.getcwd())
from pathlib import Path
file1 = Path(FilePath + "\\" + getname + ".txt")
if (file1.exists() == False):
f1 = open(getname + ".txt", "w")
f1.write(str(stage - 1))
f1... |
c1d18a1835f98f1206e334ef5157940d567be036 | palohotox/PythonChallenge | /WorkingwithArray.py | 952 | 4 | 4 |
from array import *
myarr = array('i',[1,2,3,5,6,7,2]) #array
myarr2 = array('i',[7,4,5,7,8,9,6]) #array
numlist = [5,5,5,5,5,1,1,2,2] # List
#print("Original: " , myarr)
#myarr.append(1000) # Will append new element on the last loction
#myarr.pop(0) # Will remove third element
#myarr.remove(2) # Wil... |
63c3e84b6677ca2ed1433eaba998dbbfeceb8a4e | ViniciusArdonyx/Coloracao_de_grafo | /Codigo/Graph.py | 3,817 | 3.625 | 4 | # -- coding: utf-8 --
# Importacao de bibliotecas
import sys
class Graph:
# Construtor da classe
def __init__(self):
self.vertices = []
self.edges = []
self.amountV = 0
self.amountE = 0
# Seta o vertice na lista de vertices do grafo
def setVertices(self, vertex):
... |
12decd877e605eb5d1ae23afdcefb6fdb99d9d1b | AnshumaanBajpai/Project-Euler | /Problem_10.py | 373 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 05 15:03:18 2014
@author: Anshumaan
"""
## This script is a solution to Problem 10 in project_euler. The aim is to add
## the prime numbers upto 2 million
import is_prime_small as ips
sum_p = 2 # The sum of the prime numbers
p = 3
while p < 2000000:
if ips.isp... |
4730dc71638058cee705b0c23871cea1309943aa | AnshumaanBajpai/Project-Euler | /Problem_5.py | 1,412 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 20 19:28:49 2014
@author: Anshumaan
"""
## This script is for problem 5 in project Euler. The aim is to find out the
## least common multiple of natural number till 20. The way I am approaching
## this problem is by observing that the LCM from 11 to 20 will be a multiple... |
2be00d9d99d1feb4780d2ccdbc857f5efbd26748 | vitorkaio/Servidor-nomes-python | /Servidor de Nomes/Cliente/classe_number.py | 705 | 3.53125 | 4 | # coding: utf-8
class Number(object):
'''
Classe que abstrai operações com dois número e seu resultado.
'''
def __init__(self, numeroAA, numeroBB, res):
self.__numeroA = numeroAA
self.__numeroB = numeroBB
self.__resultado = res
def getNumeroA(se... |
561d1fb7fe43b112fc01635b105cf3b12b87f2d1 | jepify/SudokoSolver | /src/solver_internet.py | 1,645 | 3.796875 | 4 | solvedTable = []
initialTable = []
try:
lines = open('sudokus/Sudoko1.txt').read().splitlines()
except:
print("File does not exist")
exit()
index = 0
for line in lines:
initialTable.append([])
solvedTable.append([])
for number in line:
initialTable[index].append(int(number))
sol... |
6600d0d74d0e7c61008ebd7c7942341a4f38192f | kkhaw1/practice_problems | /binary_search.py | 2,736 | 3.8125 | 4 | # -*- coding: utf-8; -*-
class Solution(object):
def search(self, haystack, needle):
found = False
left, right = 0, len(haystack) - 1
while not found and left <= right:
mid = (left + right) / 2
if haystack[mid] == needle:
found = True
el... |
e8d27c11a5868d7efef32ada05880af963a173eb | eaindra-wp/Algorithms-and-Data-Structure | /Assignment 8/rbt.py | 11,044 | 4.03125 | 4 | import sys
class Color:
RED = 0
BLACK = 1
class Node:
def __init__(self):
#initialize pointers for nodes and elements with none
self.data = None
self.color = Color.RED
#color as red
self.left = None
self.right = None
self.parent = None
... |
4f41b7a627f234aaf5fe998c6e7e9741daad1787 | Afeezmahmud1/my_pyneng | /my_decorator/decor_wt_arg.py | 605 | 3.640625 | 4 | from functools import wraps
def restrict_args_type (required_type):
def decorator (func):
@wraps (func)
def wrapper ( * args):
if not all ( isinstance (arg, required_type) for arg in args):
raise ValueError ( f'All arguments must be { required_type . __name__ } ' )
... |
084571ea82833e15a9c65c78d98c61d1f01650c7 | JosephAdolf/AP-II | /EX 11 EXTRA AULA 2.py | 493 | 3.96875 | 4 | def mmc (x1,x2):
if x1 < x2:
menor = x1
else:
menor = x2
if x1%x2 == 0 or x2%x1 == 0:
print("MMC = ",menor)
return
else:
while True:
if menor%x1 == 0 and menor%x2 == 0:
print("MMC = ",menor)
break
... |
b224a74f8fd83baa78b3c2b9b7b6cab109f59fda | JosephAdolf/AP-II | /EX 9 AULA 2.py | 351 | 3.890625 | 4 | def somaDigitos (n):
y = len(n)
z = 0
for i in range (0,y,1):
z += int(n[i])
return z
def numero():
n = input("Digite o número positivo:")
a = int(n)
while a < 0:
n = input("Número negativo !! Digite o número positivo:")
a = int(n)
return somaDig... |
365349f1afdda44d8e400f798120ef09861bdc14 | JosephAdolf/AP-II | /EX 3 LAB 6 REVISAO.py | 297 | 3.796875 | 4 | cont = 0
letra = input("Digite a letra que você quer comparar:")
palavra = input("Digite a palavra que você quer comparar:")
for i in range (0,len(palavra)):
if palavra[i].upper() == letra.upper():
cont += 1
print("A letra",letra,"aparece",cont,"vezes!!")
|
af23b3e2be6ffb185b0cff29df5680c544937bcd | CaduBonon/formula1_track_analysis | /scrapers/DataScrapper.py | 3,709 | 3.53125 | 4 | from time import sleep
from selenium import webdriver
from datetime import datetime
import pandas as pd
class DataScrapper:
def __init__(self, browser):
"""When we instantiate this Class, we need to set:
- date & time: so that we are able to traceback changes
in our data over tim... |
58ddf4cb641466f464a157fe13acef29b892bf2c | HeiderJeffer/PythonForBeginners | /app.py | 305 | 4 | 4 | # print("Hello World my name is Heider")
# print('O-----o')
# print(' --___----')
# name
# price = 10
# price = 20.9
# is_publish = True
# print(price)
#
name = input('What is your name? ')
color = input('What is your favorite color? ')
print('My name is ' + name + ',and my favorite color is ' + color) |
96a45d8871139de80ad2269648602c64209c04a3 | HelinaBerhane/Budget | /budget.py | 6,100 | 4.15625 | 4 | # This Python file uses the following encoding: utf-8
### Import Modules ###
import sqlite3 # databases
#--------------------#
#-- Initialisation --#
#--------------------#
# create the connection object that represents the database
connection = sqlite3.connect('budget.db')
# create a Cursor object and call its exec... |
78d06b6a9fb261085da55a1bdfbdc68443e61ecf | codegauravg/Python-Practice | /Hackerrank Problems/Prog2-If-Else.py | 595 | 4.34375 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python
"""
Task
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20... |
50b20584d6755b14e67ada659e7ba666e8d63369 | realsystem/stud_python | /emails/gen_emails.py | 1,355 | 3.578125 | 4 | import sys
import random
def rand_char():
random.seed()
return unichr(random.randrange(97, 122))
def rand_str(str_len):
res_str = ''
for n in range(0, str_len):
res_str = res_str + rand_char()
return res_str
def gen_email(email_len):
return rand_str(random.randrange(1, email_len - ... |
8765e57bf5820ea6421882cdbfebe29a51f38395 | realsystem/stud_python | /15-reverse.py | 193 | 4.34375 | 4 |
def reverse(string):
string_list = string.split()
string_list.reverse()
return string_list
user_string = raw_input('enter the string line: ')
print ' '.join(reverse(user_string)) |
4458440962c7ae69be90f07fcf49c67db714521e | mybatete/Python | /Power W:O recursion/power_nonrecursive.py | 304 | 4.0625 | 4 | def main():
x=input("Base: ")
y=input("Power: ")
z = power(x,y)
print "Result: ", z
def power(x,y):
result = 1
count = 0
while count < y:
result *= x
count += 1
return result
"""
def power(x,y):
result = 1
for count in range(y):
result *= x
return result
"""
main()
|
fa662cc5dba9a47d637ca61a31ec780812f3876c | mybatete/Python | /Orderded List/orderedList (1).py | 2,937 | 3.96875 | 4 | from ListNode import Node
class orderedList:
def __init__(self):
self.head = None
def getHead(self):
return self.head
def isEmpty(self):
return self.head == None
def add(self, item):
print "Adding ..."
# Case 1: List is Empty:
if self.head == None:
temp = Node(item)
temp.setNext(self.hea... |
6886fb7cda4200f52e9021cba4b2989aa73d3b62 | mybatete/Python | /Prime Number/prime.py | 264 | 4.125 | 4 | prime=True
num = input("Enter a Number: ")
if num <1:
print "Enter a Number Greater Than 1!!!"
exit()
for k in xrange(2,num):
if num % k == 0:
prime = False
break
if prime == True:
print num,"is a Prime Number"
else:
print num,"is NOT a Prime Number"
|
d27234036f158cfe74dd50e65b2222467e8c39ec | mybatete/Python | /Quick Sort/quick_sort.py | 2,132 | 3.640625 | 4 | MINSIZE=4
def main():
myList=[11,5,78,3,14,67,22,37,19,25,99]
#myList=[15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
print "Before Sort: ",myList
left = 0
right = len(myList)-1
myList = quickSort(myList,left,right)
print "\n\nAfter Sort: ",myList
print "\n\n"
def quickInsertion(myList,first,last):
#print "\n... |
82a6ce44ab41b791f413519b7076145f574bb91f | mybatete/Python | /Student/lab7.py | 1,686 | 3.59375 | 4 | from StudentsClass import Students
def main():
sl=[]
match=[]
fp= open ("LCSC-Student_Records.dat","r")
fp.readline()
while True:
line = fp.readline()
if line == "":
break
line= line.strip()
word = line.split()... |
8cd722978b4902fd1f5e803d37358ac481741a54 | mybatete/Python | /seqBinSearch.py | 1,873 | 4.25 | 4 | """
Program: seqBinSearch.py
Author : Charles Addo-Quaye
E-mail : caaddoquaye@lcsc.edu
Date : 01/31/2018
Description:
This program implements demo for both
sequential and binary search algorithms.
The program generates a random list of integers
and provides a menu for searching for numbers
in the list.
Input v... |
98779b523fe47886dfa7999416d96a021e524ee6 | wsysissi/NanYang-program-interview | /question_1/code_question_1_1.py | 7,102 | 4.28125 | 4 | #Since the value of each member in a row of the matrix given in the example is
#equal to the number of that row, the matrix generated in this code is also of this form,
#but can be replaced with other matrices in other cases.
'''
README
input of the code is like the example below:
e.g.we want to find the oper... |
1cd80b62d2de20078e169af9ec3332b9862e2bb5 | WilliamHerrgott/artificial-intelligence-ruc | /MyDataManager.py | 2,051 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from cryptory import Cryptory
from sklearn.preprocessing import MinMaxScaler
class MyDataManager():
def __init__(self, date):
self.crypto_data = Cryptory(from_date = date)
self.bitcoin_data = self.crypto_data.extract_coinmark... |
97cbad6efeed92d06082f371966262e15d6cdfe5 | krissmile31/documents | /Term 1/SE/PycharmProjects/pythonProject/venv/TemperatureConverter.py | 233 | 4.40625 | 4 |
print("Celsius to Fahrenheit temperature Converter!\n")
Celsius = float(input("Enter the temperature in Celsius: " ))
convert = (9/5) * Celsius + 32
print("\nCelsius: ", Celsius, "℃")
print(" Fahrenheit: " , convert, "℃")
|
4a8c5e4e892824fc19fa7b723371cac5ee6ca380 | krissmile31/documents | /Term 1/SE/PycharmProjects/pythonProject/Tut2/phoneNumber Transalator.py | 870 | 4.03125 | 4 | #declare Dictionary
alphaDict = {"ABC": '2', "DEF": '3', "GHI": '4', "JKL": '5', "MNO": '6', "PQR": '7', "STUV": '8', "WXYZ": '9'}
#method for translating
def Trans(phoneNum):
# initialize result
num = ""
#loop over the input
for i in phoneNum:
#input = number || = "-" --> append it to result
... |
9ac61ebd2d240dc19e235c45347956cd4b96534a | krissmile31/documents | /Term 1/SE/PycharmProjects/pythonProject/practise/number2text.py | 4,070 | 3.609375 | 4 | # Program: Read Vietnamese Money
# Course: HANU-FIT-SS1: Python programming
# Author: Hung Ta
#============================================================================
def ret_0word(order):
return {0: "", 1: "", 2: "Không"}[order]
def ret_1word(order):
return {0: "Một", 1: "", 2: "Một"}[order]
def ret_word(... |
dff114f7caa3b803d85a634807ae4e38aa70a4e0 | krissmile31/documents | /Term 1/SE/PycharmProjects/pythonProject/Tut2/Most Frequent Character.py | 263 | 4.28125 | 4 | from collections import Counter
#ask user input a string
stringCount = input("Enter a string: ")
#count char appearing most in that string
count = Counter(stringCount).most_common(1)
print("Character that appears most frequently in the string: " )
print(count) |
123d4e749e86036c0e3331b9f2a45d6895261876 | Kenneth-Sweet/Algorithm-Challenges | /Python/FactorsGenerator.py | 547 | 3.5625 | 4 | def factors(n):
for k in range(1,n+1): ##set range to plus 1 as range takes in final parameter minus 1
if n % k == 0: ##if a factor of n
yield k
fc = factors(12)
counter = 0
ten_factors = [] ##store factors in a list
while counter < 10: ##count only 10 variables
... |
ac979d2a0c0d4f6852d5059dd74ec8f350a9f39a | Itumeleng091slk/animal-part-two | /dog.py | 361 | 3.71875 | 4 | from animal import Animal
class Dog(Animal):
def __init__(self, eats, sounds):
super().__init__(eats,sounds)
#def food(self):
#print(self.name + " eats")
def sound(self):
return self.sounds
def eat(self):
return self.eats
dog_1 = Dog("Food ","Bark ")
#dog_1.food()... |
8dbd259f104b60d3f9ea46faea3c273059276951 | Jiale-Fan/Rugged_Car | /code/early_test/Python_PWM_generation/pwm_motor.py | 511 | 3.5 | 4 |
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 1000) # 通道\频率
dc = 50
p.ChangeDutyCycle(dc)
p.start(0)
try:
while 1:
t = input()
# print('got')
if t == 'w':
if dc + 10<=60:
dc += 10
elif t == 's':
... |
a19360ad61d5e93e4347128cf6e59b28b497559e | Lachlan00/ocean-classifier | /prototypes/ocean_class.py | 2,278 | 3.53125 | 4 | """
Ocean classification algorithm
------------------------------
Experimental program to classify two different water masses
based on temperature and salinity profiles.
"""
# import modules
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
import math
import matplotlib.pyplot... |
479ead5dea0def1058526202505f7df93aadaf7c | Polcsi/Person-Generator-App | /Address.py | 617 | 3.640625 | 4 | class Address:
Street: str
City: str
State: str
Zip: int
@property
def Street(self):
return self._Street
@Street.setter
def Street(self, street):
self._Street = str(street)
@property
def City(self):
return self._City
@City.setter
def City(self... |
438f4ff5cfe336821fc56f3ec9785dd5c38b8848 | caseynv/GuessingGame | /GuessNumber.py | 3,142 | 4.03125 | 4 | import random
print("Please select your level of difficulty." "1 - Easy, 2 - Medium, 3 - Hard")
x = int(input("Enter your level of difficulty: "))
if (x == 1):
n = int(input("You have 6 guesses. Enter a number between 1 - 10: "))
count = 1
guess = random.randint(1, 11)
if n != guess:
... |
61458c669094702d08f3c877c9ea13f8aa557bb5 | AEFitzGerald/user | /user.py | 1,850 | 4.09375 | 4 | class User:
def __init__(self):
self.name = "Anna"
self.email = "annaefitzgerald@gmail.com"
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
#issues with initialization
return self
def make_withdrawal(self, amou... |
7d12015381d1a24658f9fcd196eb30236927c1e5 | lokeshnk09/Aaron_Maxwell | /guessing_num.py | 757 | 3.984375 | 4 | from random import randint
def guess_num():
print("I'm thinking of a number b/w 1 and 20.\nGuess the number!")
secret_num = randint(1, 20)
count = 0
while True:
guess = int(input())
while guess != secret_num:
if guess < secret_num:
print('Your guess is too l... |
02df23eede4cae9e27fcb53c3ea54ae5747e2f26 | hassan-jamous/python-test-examples | /test_mocks/test_mock_abstract.py | 576 | 3.75 | 4 | from abc import ABC, abstractmethod
from unittest.mock import MagicMock
class AbstractAdd(ABC):
@abstractmethod
def add(self, value1, value2):
pass
class AddImplementation(AbstractAdd):
def add(self, value1, value2):
return value1 + value2
def mainFunction(AbstractAdd):
return Abstra... |
688d0471616443e2b07c3f281f90de7af43ee63a | alohith/UCSC-BME205-F16 | /assignment7-Rosalind-DAG/Rosalind-LongestPathinDAG.py | 9,191 | 3.96875 | 4 | #!/usr/bin/env python3
########################################################################
# File:treeBuilder.py
# executable: treeBuilder.py <input >output
# Purpose: Build the Newick tree from tab delineated distance matrix.
# stdout: Species tree in Newick format
#
# Author: Akshar Lohith
# Group(sound... |
58226b3152c83301f15eb4c0a9d6afa6532a550d | Matanhalfon/intro-doctor | /ex_10_tests.py | 6,380 | 3.515625 | 4 | # FILE: ex7.py
# Exercise: Intro_2_cs ext10 2017-2018
import ex10
def test_1(diagnoser):
diagnosis = diagnoser.diagnose(["cough"])
if diagnosis == "cold":
print("Test passed")
else:
print("Test failed. Should have printed cold, printed: ", diagnosis)
tiny_data = r'Data\tiny_data.txt'... |
a29770c8f3947e7d01e46aa87d83a7f24411dd90 | danielzarateos/Algoritmos | /TodoMenosElUltimoTaller/PerdonProfeEsQueTeniaMuchaCosa/TallerOptimizacion/conteo.py | 1,248 | 3.90625 | 4 | #Caso1
print("Hola mundo")
nombre = input(str("Ingrese su nombre : "))
print(nombre)
# PASOS = 3
#Caso2
print("Hola mundo")
nombre = input(str("Ingrese su nombre : "))
print(nombre)
x = int(input("Ingrese hasta cuanto voy a contar : "))
for i in range (x):
print(f"He contado {i+1} pasos")
# PASOS = 4 (hasta x) +... |
a5509b044ac351004b6ca4a952f56a722842fb5c | JonathanAlderson/3DRenderer | /code0.5 faceShading.py | 11,471 | 3.90625 | 4 | import tkinter,math,time,random
def matMul(a,b):
"""Will multiply two matricies together that are 3x3 and return the sum"""
c = []
# All these calculcations return the product of any two matricies A * B
#print("Mat mul called")
#print("A = ",a)
#print("B = ",b)
c.append(a[0] ... |
62126ad16bff03b6a8affb8588f2ed3aa4cb12f0 | seanecho/Python | /interaction.py | 341 | 3.734375 | 4 | #Author: Sean Gao
'''username = input("username")
password = input("password")
print(username, password)'''
name = input("name:")
age = input("age:")
job = input("job:")
salary = input("salary:")
info = '''
---------info of''' + name + '''------
Name:'''+ name +'''
Age:''' + age +'''
Job:''' + job +'''
Salary:''' +... |
172bc9f514f994609ffa60bc387af532793d06c9 | Mosesvalei/Password-Locker | /credential.py | 1,104 | 3.6875 | 4 | class Credential:
credential_list=[]
'''
class that generates new instances of credentials
'''
def __init__(self, identity, user_name, password):
'''
Initializing the variables for the list of credentials
'''
self.identity=identity
self.user_name=user_name
... |
801beeb56fd5b8fd9021998c0e7830e3dfba1575 | SoniaZhu/Lintcode | /linkedin/30. Insert Interval [M].py | 1,386 | 3.921875 | 4 | """
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param intervals: Sorted interval list.
@param newInterval: new interval.
@return: A new interval list.
"""
def insert(self, interval... |
6934f8172f808abc0585ebe3e4383a7f947b078d | SoniaZhu/Lintcode | /linkedin/905. Nested List Weight Sum II [M].py | 605 | 3.78125 | 4 | from collections import deque
class Solution:
"""
@param nestedList: a list of NestedInteger
@return: the sum
"""
def depthSumInverse(self, nestedList):
# Write your code here.
queue = deque(nestedList)
presum = 0
result = 0
while queue:
for _ in r... |
64316f61761abe0d4d518dddf4d97d71efbf5087 | SoniaZhu/Lintcode | /High Frequent/661. Convert BST to Greater Tree [E].py | 1,416 | 3.5625 | 4 | class Solution:
"""
@param root: the root of binary tree
@return: the new root
"""
def convertBST(self, root):
# write your code here
self.sum = 0
self.dfs(root)
return root
def dfs(self, root):
if not root:
return
self.dfs(root.right)... |
44013da3c13840c210fbf99f257bd38d3f2490e0 | SoniaZhu/Lintcode | /fb/51. Previous Permutation [M].py | 693 | 3.546875 | 4 | class Solution:
"""
@param: nums: A list of integers
@return: A list of integers that's previous permuation
"""
def previousPermuation(self, nums):
# write your code here
for i in range(len(nums) - 2, -1, -1):
if nums[i] > nums[i + 1]:
break
else:
... |
1e354d342d5da60de65f8b4d44c2f666be2fed57 | SoniaZhu/Lintcode | /linkedin/69. Binary Tree Level Order Traversal[E].py | 737 | 3.734375 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Level order a list of lists of integer
"""
def levelOrder(self, root):
# write your code here
... |
82a7e4785af35c42e07ba36456fdcf371cd5c1e5 | SoniaZhu/Lintcode | /Amazon OA/1165. Subtree of Another Tree [E].py | 788 | 3.9375 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param s: the s' root
@param t: the t' root
@return: whether tree t has exactly the same structure and node values with a subtree of s
"... |
5042b55644aeecdd843e37b1b5f9356ecb0ff924 | SoniaZhu/Lintcode | /linkedin/1105. Print Binary Tree [M].py | 1,199 | 3.9375 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the given tree
@return: the binary tree in an m*n 2D string array
"""
def printTree(self, root):
# Write your code ... |
99534512eeb963a692e2bcd7afcc7a9f9ab81519 | SoniaZhu/Lintcode | /linkedin/650. Find Leaves of Binary Tree [M].py | 1,556 | 3.96875 | 4 |
## mine. second time. feel bad.
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: the root of binary tree
@return: collect and remove all leaves
"""
def findLeaves(self, r... |
2a2b022e13a00560a9e883dad35df7fe0d2a344a | SoniaZhu/Lintcode | /linkedin/1056. Find Smallest Letter Greater Than Target [E].py | 1,023 | 3.84375 | 4 | class Solution:
"""
@param letters: a list of sorted characters
@param target: a target letter
@return: the smallest element in the list that is larger than the given target
"""
def nextGreatestLetter(self, letters, target):
# Write your code here
left = 0
right = len(let... |
f7bc11a93d1f3cf13f3e4ec9e2e8a0099c2883e5 | SoniaZhu/Lintcode | /linkedin/528. Flatten Nested List Iterator [M].py | 2,842 | 3.9375 | 4 | ## The best.
## My sol below. BAD: 1, not lazy (oop). 2, next should call has next.
class NestedIterator(object):
def __init__(self, nestedList):
# Initialize your data structure here.
self.stack = nestedList[::-1]
self.nextElement = None
# @return {int} the next element in the iterati... |
a1a913f40fc78e389c3d07fe03f48be66ed8929c | aaguasvivas/CodeBreakersCode | /1.Fundamentals/stacks_queues/stack.py | 1,272 | 3.78125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class Stack:
def __init__(self):
self.first_item = None
self._size = 0
# prints out stack in order
def __str__(self):
# O(n) time
# O(n) space
cur = self.first_item
out... |
85ac10705731a90306129a83eda92bd7e4b3b5e0 | aaguasvivas/CodeBreakersCode | /Educative_DS_for_interviews/lists/list_products_of_elements.py | 286 | 3.640625 | 4 | def findProduct(lst):
left = 1
product = []
for ele in lst:
product.append(left)
left *= ele
right = 1
for i in range(len(lst) - 1, -1, -1):
product[i] = product[i] * right
right *= lst[i]
return product
# Time Complexity: O(n)
|
c43af2acc58e816264a77dfe760afd13da19dba7 | aaguasvivas/CodeBreakersCode | /1.Fundamentals/linked_lists/LinkedList.py | 1,990 | 4.03125 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = Node("dummy")
self._size = 0
def __str__(self):
# O(n) runtime
# O(n) space
out = ""
cur = self.head.next
... |
eb3c3133cc2f4a08864e6ce45c1a15b5746540e6 | aaguasvivas/CodeBreakersCode | /Educative_DS_for_interviews/tries/tries_implementation.py | 7,511 | 4.3125 | 4 | class TrieNode:
def __init__(self, char=''):
self.children = [None] * 26 # Total size of the English alphabet
self.is_end_word = False # true if node represents the end of the word
self.char = char
# Function to mark the currentNode as Lead
def mark_as_leaf(self):
self.is_... |
0fc206977242e324ff45cc9bb5a64a8efbe8d097 | aaguasvivas/CodeBreakersCode | /5.Recursion/introduction/fibonacci.py | 710 | 3.890625 | 4 | # O(2^n) time
def fibonacci(n):
if n == 0 or n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
# O(n) time and space
def fibonacciMemo(n, d, memo):
if n in memo:
return memo[n]
if n in d:
d[n] += 1
else:
d[n] = 1
if n == 0 or n == 1:
return 1... |
1359a7f162a0baa3f0fee3fccbf501f6c5eba06a | aaguasvivas/CodeBreakersCode | /Educative_DS_for_interviews/lists/remove_even_from_list.py | 155 | 3.640625 | 4 | def removeEven(num_list):
return [item for item in num_list if item % 2 != 0]
ten_list = list(range(10))
print(ten_list)
print(removeEven(ten_list))
|
b352521cd19a2cd19e8af34f6b4f2966efcd4c5f | aaguasvivas/CodeBreakersCode | /Educative_DS_for_interviews/stacks_queues/queue_implementation.py | 2,051 | 3.84375 | 4 | from stack_implementation import myStack
class myQueue:
def __init__(self):
self.queueList = []
def isEmpty(self):
return len(self.queueList) == 0
def front(self):
if self.isEmpty():
return None
return self.queueList[0]
def back(self):
if self.isE... |
f391bc44d5bd7902d83c1b5df44e71d68b79a84d | tranquilshore/CodeforcesProblems | /21A_jabberID.py | 1,536 | 3.71875 | 4 | mail = raw_input().split("@")
at_rate_flag = True
if len(mail) > 2:
at_rate_flag = False
if at_rate_flag == True:
username = mail[0]
onlyusername = False
if len(mail) == 1:
onlyusername = True
else:
rest = mail[1].split("/")
hostname = rest[0]
resource_flag = False
... |
742618da85230d71be8bc75cdcac1fd6e179b663 | tranquilshore/CodeforcesProblems | /12A_superAgent.py | 724 | 3.625 | 4 | lcd = []
try:
while True:
r = raw_input()
if r != "":
lcd.append(r)
else:
break
except EOFError:
pass
lcd = [list(x) for x in lcd]
noflag = False
right_diagonal_flag = False
left_diagonal_flag = False
middle_horizontal_flag = False
middle_vertical_flag = False
... |
caef9b6831d2507b2149fc33305c191062b2396a | jocaro97/AA | /P2/bonus.py | 5,835 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
TRABAJO 2
Nombre Estudiante: Johanna Capote Robayna
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# Fijamos la semilla
np.random.seed(1)
def simula_unif(N, dim, rango):
return np.random.uniform(rango[0],rango[1],(N,dim))
def simula_gaus(N, dim, sigma):
med... |
2ac298765900d155eab1e26560908a7efa884d45 | IceMortyGod/icemortoos | /IceMorty Pro Calculator.py | 1,167 | 4.1875 | 4 | print("Welcome To Sub To Icemorty Facking Calculator:)")
x = int(input('Enter the first number pls: '))
y = int(input('Enter the second number: '))
yes = ("Good Job Facker :)")
no = ("fuck of facker 👿")
def add(x, y):
print(x + y)
def subtract(x, y):
print(x - y)
def multiply(x, y):
print(x * y)
d... |
c67d1c5ec86e3a893113ff70a8a3b53d2c2f87b8 | av4l4nc14/solutions_to_erdos | /equation.py | 582 | 3.609375 | 4 | def is_perfect_cube(x):
return int(round(x**(1./3))) ** 3 ==x
def calc():
for i in range(100):
y= (i**6) + 8*(i**4) -6*(i**2) +8
... |
dd5eedacf78010c1a4a7ad3ac76675cc7e6a76a6 | njoubert/UndergraduateProjects | /CS188_p1/trunk/src/searchAgents.py | 27,330 | 3.734375 | 4 | """
This file contains all of the agents that can be selected to
control Pacman. To select an agent, simple use the '-p' option
when running pacman.py. That is, to load your DepthFirstSearchAgent,
just run the following command from the command line:
> python pacman.py -p DepthFirstSearchAgent
Please only change th... |
5b40c7b3b073b57b29bf85f9ae28862b455f68b1 | Cfhansen/stephenson-pywb52 | /main.py | 819 | 3.703125 | 4 | ###Solution to problem 52 from ben stephenson's "the python workbook".
print("Enter a numerical grade:")
grade = float(input())
if grade < 0:
grade = 0
grades = { 0: 'F',
1: 'D',
1.3: 'D+',
1.7: 'C-',
2.0: 'C',
2.3: 'C+',
2.7: 'B-'... |
7a735d3795e3cacfff458828a950f7034df34601 | hannawallach/misc | /text_plot.py | 1,772 | 3.703125 | 4 | import csv
from urllib2 import urlopen
from itertools import islice
from pylab import axis, infty, show, subplot, text
import pandas
def plot_without_pandas():
min_population = infty
max_population = 0
data = []
for row in islice(csv.reader(urlopen('http://datasets.flowingdata.com/crimeRatesByState... |
017cfb7bfcd64286064f1295d2ae907629827535 | Agevork2020/python-project-lvl1 | /brain_games/games/gcd.py | 671 | 3.84375 | 4 | """A gcd module."""
import math
import random
RULE = 'Find the greatest common divisor of given numbers..'
SPAN_START = 0
SPAN_END = 50
def gcd(variable1, variable2):
"""
Run a code.
Args:
variable1: x
variable2: y
Returns:
gcd
"""
return math.gcd(variable1, variabl... |
25ff57faf81c6c7d740e618fdcde86213a2eb39f | adinimbarte/codewayy_python_series | /Python_Task6/Q.6/Q.6.py | 565 | 3.984375 | 4 | # function is declared
def findType(n):
sum=0
# addition of all divisors
for i in range (1,n):
if (n % i)==0 :
sum=sum+i
print("the sum of divisors is:", sum)
# checking the condition
if sum<n:
z=1
elif sum>n:
z=-1
else:
z=0
re... |
783e2a359919dbc8c45916ccac462ca588d31715 | adinimbarte/codewayy_python_series | /Python_Task4/Q2.WorkingWithModules/functionsOfLogicalOperators.py | 524 | 3.96875 | 4 | #function for and operator
def andOperator(x,y):
print(" %d and %d are greater than 100? Ans="%(x,y),end=" ")
if ( x > 100 and y > 100 ):
print("True")
else:
print("False")
#function for or operator
def orOperator(u,v):
print("%d or %d are greater than 100? Ans="%(u,v),end=" ")
... |
8dfcd3b7339f271409fa64ae63b4357c8692e990 | adinimbarte/codewayy_python_series | /Python_Task6/Q.4/Q.4.py | 283 | 4.15625 | 4 | # taking string input
string = input("Enter the string from which you want to count number of 'at': ")
# counting occurence of "at" and printing
count=string.count("at")+ string.count("At")+ string.count("At") + string.count("AT")
print("'at'occured %d times in string." % count )
|
a5092e1195218e3bccc9092f8b8253108806264c | JiratNakarit/eleven_code | /eleven_vision/playground_jirat/same_triangle.py | 281 | 3.5 | 4 | import math
def find_c(a, b):
a = math.pow(a, 2)
b = math.pow(b, 2)
c = math.sqrt(a+b)
return c
if __name__ == "__main__":
# a = (0.972e-3)/2
# b = 1.93e-3
# c = find_c(a, b)
a = (160e-3)/2
b = 327.572e-3
c = find_c(a, b)
print(c)
|
082f9ee81cf938bd2548b2b35b3bd44215c4e8cb | Yixin-Zhang95/leetcode_challenge | /FizzBuzz.py | 467 | 3.65625 | 4 | def fizzBuzz(n: int):
answer = []
fizz_buzz_dic = {3: 'Fizz', 5: 'Buzz', 7: 'Jazz'}
for num in range(1, n + 1):
current_answer = ''
for key in fizz_buzz_dic.keys():
if num % key == 0:
current_answer += fizz_buzz_dic[key]
if not current_answer:
... |
324e49310e45a2dc9ad1bf53b79336f70e6a5c6e | Yixin-Zhang95/leetcode_challenge | /flood_fill.py | 640 | 3.609375 | 4 | def floodFill(image, sr, sc, newColor):
if image[sr][sc] == newColor:
return image
stack = [(sr, sc)]
start = image[sr][sc]
while stack:
i, j = stack.pop()
if image[i][j] == start:
image[i][j] = newColor
if i + 1 < len(image):
sta... |
d40136ff4b8ffe975161d037831e6362f526bc64 | pklauke/chatbot | /src/data/filter.py | 2,274 | 3.546875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
import numpy as np
import config
class DataFilter(ABC):
"""Abstract class for filtering data."""
@abstractmethod
def filter_data(self, data):
pass
class CharacterLevelFilter(DataFilter):
"""Class to filter ... |
1b55c12459db1d08eb8f885129d2ba27d2284598 | Harshala-Gaikwad/TOC | /string_having_equal_no_1_and_0.py | 215 | 3.75 | 4 | #Design a program for creating a machine which accepts string having equal no. of 1's and 0's
s = input("Enter the String: ")
if s.count('1')==s.count('0'):
print("Accepted")
else:
print("Rejected")
|
da9547820eac09d4d8f8442fff7812dff8efb9d6 | ethanglaser/foobar | /foobar4.2.py | 1,718 | 3.5625 | 4 | '''
Find the most possible bunnies to save in the time limit given the traversal time matrix
'''
def solution(times, times_limit):
# Your code here
minDist = minDists(times)
for index, val in enumerate(minDist):
if val[index] < 0:
return [val for val in range(len(times) - 2)]
possib... |
feaef2bdb3ae12a2986b2d6a4f42b3ce662cc72e | hdcsantos/exercicios-python-secao05-41e-v2 | /11.py | 554 | 4.03125 | 4 | print("Soma de todos os algarismos")
numero = int(input('Informe um número: '))
if numero > 0:
numero_lista = list(range(3))
numero_lista[0] = numero // 100
numero_lista[1] = numero // 10 - 10 * (numero//100)
numero_lista[2] = numero - 10 * (numero // 10 - 10 * (numero // 100)) - 100 * (numero // 100)... |
bb92a9a54d61fbe877532487373e3a91eda7adea | hdcsantos/exercicios-python-secao05-41e-v2 | /20.py | 775 | 4.09375 | 4 | print('Lado dos triangulos')
a = int(input('Infome o valor do lado a: '))
b = int(input('Infome o valor do lado b: '))
c = int(input('Infome o valor do lado c: '))
if a < (b + c) and b < (c + a) and c < (a + b):
print('De acordo com os valores, vc criou um triângulo! Agora vamos saber qual é o seu tipo.')
if a... |
500694e3b81a13b68097ca655bbee49f8ea54582 | ShanzayA/CSI4106 | /Assignments/csi4106_a1/searchdir/util.py | 4,520 | 4.125 | 4 | ## Author: Amal Zouaq
### azouaq@uottawa.ca
### Author: Hadi Abdi Ghavidel
###habdi.cnlp@gmail.com
from operator import attrgetter
from collections import deque
import heapq
#Queue - Implementation of the data structure Queue
class Queue:
# initializes the current data structure
def __init__(self):
se... |
2ab3ed3bfa54be61a0e083c62c46002cae1c1ee3 | Graziela-Silva/Jogos-Games | /Cara ou Coroa em Python.py | 658 | 3.890625 | 4 | import random
print('-='*15)
print('Vamos jogar cara ou coroa!')
opcoes = ['Cara','Coroa']
print('\nJogando a moeda...')
computador = random.choice(opcoes)
usuario = str(input('\nO que você acha que deu? ')).strip().capitalize()
while usuario != 'Cara' and usuario != 'Coroa':
print('\nA resposta deve ser cara ou co... |
a13744a12453b393a527a7115e8cadda9e863e6e | SG-325/Homework_Course_Python_2 | /class_1/class_5.py | 946 | 3.890625 | 4 | #1
# text = input("Enter a word: ")
# if text[-3:] == "ing":
# t = text[:len(text)-3] + "ly"
# print(t)
#2
# word = "playing"
# c = input("leter: ")
# a = word.find(c)
# if c in word:
# word = word[:a] + "0" + word[a+1:]
# print("The word has changed ", word)
# else:
# print("The word hasn't changed ", word)
#3
... |
cc9ad51a0c3664dfd9190164fa646571ecd44e43 | SG-325/Homework_Course_Python_2 | /h_1/f_1.py | 446 | 4 | 4 | def func(dic:dict)->list:
'''
Description:
The function returns a list of all letter combinations.
Parameters:
dic (dict):The given dictionary.
Returns:
l (list):List of all combinations.
'''
l = []
for k_1 in dic.values():
for k_2 in dic.values():
if k_1 != k_2:
... |
79fde07eef93e53b4be07492f0535b8f919fb153 | dreedgibson/Projects | /MIT Python/final.py | 5,525 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 7 20:30:06 2016
@author: Dennis
"""
def convert_to_mandarin(us_num):
'''
us_num, a string representing a US number 0 to 99
returns the string mandarin representation of us_num
'''
# FILL IN YOUR CODE HERE
trans = {'0':'ling', '1':'yi', '2':'er', ... |
74f45d51151e6a1731ff4b68cc12a6cf901805d4 | DhananjayPorwal/Grey-Test | /Python/006 Input from user.py | 362 | 4.03125 | 4 | print("Enter your lucky number")
inputFromUser1 = input()
print("Great, Your lucky number is", inputFromUser1)
# input() , default data type is string
print(type(inputFromUser1))
# To change th datatype of input we hava to use typecasting
print("Enter your lucky number")
inputFromUser2 = input()
print("Great, Your lu... |
463afeabdd37b1063f6f22de487719dbb268eb48 | Padhky/BCI | /database.py | 7,513 | 3.9375 | 4 | import mysql.connector as sql_con
import pandas as pd
from tabulate import tabulate
# Without doing the work multiple times, please look at:
# https://www.w3schools.com/python/python_mysql_getstarted.asp
# This gives a good overview of how we access MySQL functionality from Python
database = sql_con.connect(
# si... |
e72f37dbaed95696aec657b4af071994362515a1 | Padhky/BCI | /get_trial_data.py | 865 | 3.5625 | 4 | import pandas as pd
'''
These functions help store the features in the joblib file
You do not have to calculate all the features again
'''
def make_feature_vec(data, label):
'''
concatenate features and label in one data frame
df = [features[N columns], label]
'''
df = pd.DataFrame(data)
df['l... |
b1610deddee7d89a24c98ba417cdcdfcb8b14844 | gzsalam7/python-practice | /salamTest6.py | 3,055 | 4.09375 | 4 | game = [["-", "-", "-"],["-", "-", "-"],["-", "-", "-"]]
def main():
print("This is the TicTacToe app.")
print("This is a tictactoe game. First player is cross and second is circle. \n You enter first the row and then the column of where you want to place your symbol. \n Continue and one players does... |
c8b0b7ef83a2dc315ee66b635e978f2acac7351a | gzsalam7/python-practice | /Calculator.py | 8,576 | 3.671875 | 4 | from tkinter import *
from tkinter import ttk
#The calculator works by itself, I managed to get it running by itself but it crashes now if a second operation is attempter
#I was not able to connect the number system, radiobuttons and the Assign function together
#I was able to get the conversion functions for the n... |
af75d7b813b3b9ecc613c7cba7acc29effb9dd42 | gzsalam7/python-practice | /salamTest5.py | 901 | 3.71875 | 4 | #Wasnt able top finish
def main():
sumList(toNumbers(list(salamTest5())))
def salamTest5():
x = (input("Please enter a list of integers: "))
return (x)
def squareEach(nums):
counter = 0
for i in nums:
nums[counter] = i**2
counter+= 1
print(nums)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.