blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
92e0aa3c1962fdb1ae4eed83d9544230abab919f | ryanSoftwareEngineer/algorithms | /graphs and trees/230_kth_smallest_element_in_a_bst.py | 1,205 | 3.671875 | 4 | '''
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
'''
# do an in order traversal
# when you reach a node that is none..
# you flag k to start counting down
# when k is 0 you set the answer to th... |
30e81797e4d0067d6be86efa63b5d4a595e34459 | ryanSoftwareEngineer/algorithms | /arrays and matrices/121_best_time_to_buy_and_sell_stock.py | 912 | 3.96875 | 4 | '''
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve... |
09c6d467d2570b88286da1373664cf74c8f41b53 | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/substrings_of_size_k.py | 1,305 | 3.859375 | 4 | '''Find all unique substrings containing distinct characters of length k given a string s containing
only lowercase alphabet characters.
Input: s = xabxcd, k = 4
Output: ["abxc", "bxcd"]
Explanation:
The substrings are xabx, abxc, and bxcd. However x repeats in the xabx, so it is not a valid substring of a distinct cha... |
1baa47ebd1d4d7c129f20ffab0f3965ef2ef1296 | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/1335_min_difficulty_of_schedule.py | 2,096 | 4.0625 | 4 | '''
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 <= j < i).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days.
The difficulty of a day is the... |
d4091ef007d1c4c4790b0706e7778c0b0ff62dc3 | ryanSoftwareEngineer/algorithms | /graphs and trees/shopping_patterns.py | 3,359 | 3.875 | 4 | '''
Your team is trying to understand customer shopping patterns and offer items that are regularly bought together to new customers. Each item that has been bought together can be represented as an undirected graph where edges join often bundled products. A group of n products is uniquely numbered from 1 of product_no... |
57cd15146c5a663a0ccaa74d2187dce5c5dc6962 | PabloLSalatic/Python-100-Days | /Days/Day 2/Q6.py | 498 | 4.1875 | 4 | print('------ Q 6 ------')
# ?Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
# ?Suppose the following input is supplied to the program:
# ?Hello world
# ?Practice makes perfect
# *Then, the output should be:
# *HELLO WORLD
# *PRACT... |
95747debbbceafd283d76860e01fca9bcc416be5 | jaalorsa517/gestion_mensajeria_API | /app/models/delivery.py | 1,038 | 3.5 | 4 | """Módulo que se encarga de gestionar los mensajeros"""
from csv import DictReader, DictWriter
from os import write
from os.path import join
from app import app
def get_deliveries():
with open(
join(app.root_path, "data", "delivery.csv"), newline=""
) as csv_file:
reader = DictReader(csv_file... |
c6a3d1beb068a85da6f35c73d2e5f61539d252c2 | javierfrjunior2/Python | /numero_de_pares.py | 246 | 3.796875 | 4 | def numero_de_pares():
pares=0
numero=input("Dime cualquier numero")
while numero>0:
if (numero%10)%2==0:
pares=pares+1
numero=numero/10
print "El numero tiene",pares,"pares"
numero_de_pares()
|
7902ec6be552b5e44af3e0c73335acd52c7cb3e7 | 44858/lists | /Bubble Sort.py | 609 | 4.28125 | 4 | #Lewis Travers
#09/01/2015
#Bubble Sort
unsorted_list = ["a", "d", "c", "e", "b", "f", "h", "g"]
def bubble_sort(unsorted_list):
list_sorted = False
length = len(unsorted_list) - 1
while not list_sorted:
list_sorted = True
for num in range(length):
if unsorted_l... |
10b8fb226ad47e75500e17eaff0197ed2d6eb447 | lbingle/Think-Python | /hexagon_pie.py | 185 | 3.5 | 4 | import turtle
import math
bob = turtle.Turtle()
print(bob)
l = 100
a = 120
b = 60
for i in range (6):
for i in range(3):
bob.fd(l)
bob.rt(a)
bob.rt(b)
|
7e317b88cd28f4c8c5f9a449564826a30cf138bc | lbingle/Think-Python | /Rose2.py | 549 | 4 | 4 | import turtle
import math
bob = turtle.Turtle()
print(bob)
def polyline(t, n, length, angle):
for i in range(n):
t.fd(length)
t.lt(angle)
def arc(t, angle, pedal):
radius = 200
arc_length = 2*math.pi*radius*angle/360
n = 50
step_length = arc_length/n
step_angle = angle/n
outer_angle = 180-angle
for i in r... |
e01e7aed7bdc3f3969c2d9ad640cdc5ffec72bb9 | anandnevase/bday-app | /bday-app/app.py | 4,957 | 3.5625 | 4 | from flask import Flask
from flask import request
from flask import jsonify
from flask import json
import datetime
import sqlite3
from flask import g
app = Flask(__name__)
#userlist={"userlist":[]}
@app.route('/hello', methods=['GET'])
def get_userlist():
if request.method == 'GET':
myuserlist = query_db... |
3ec3a1ef9d822dad32d77313b8026164841e743f | dlievre/python | /d01/all_in.py | 1,567 | 3.515625 | 4 |
def isState(param, states, capital_cities):
if param in states:
return getCapitalOfState(param, states, capital_cities)
def isCapital(param, states, capital_cities):
if param in capital_cities.values():
return getStateOfCapital(param, states, capital_cities)
def getStateOfCapital(param, states, capital_cities)... |
cc65ccc6d616b280f9fbff06272db4a2359a57ac | milktea8285/Interview | /Trend-1.py | 984 | 4 | 4 | # 1. clock 15:10:10 - 15:15:15 find time with at most two integer
from datetime import datetime, timedelta
import time
# Determine if it has more than two numbers
def isTwoNum(S):
dic = {}
count = 0
if len(S) < 6:
dic[0] = 1
count += 1
for s in S:
if s not in dic.k... |
a0d8aa7501b9bd7ae8375f3841c03457ad8a481e | Aynazik/2021_starchenko_infa | /lab2/exs13.py | 674 | 3.796875 | 4 | import turtle as t
t.hideturtle()
def circle(k):
for _ in range(50):
t.forward(k)
t.left(36 / 5)
def halfcircle(k):
for _ in range(25):
t.forward(k)
t.right(36 / 5)
t.shape('turtle')
t.begin_fill()
circle(7)
t.color('yellow')
t.end_fill()
t.color('black')
t.penup()
t.goto(-... |
6920bedb8cafbca14d58b7923f024394cb41bb07 | Aynazik/2021_starchenko_infa | /lab3/exs1.py | 147 | 3.59375 | 4 | import turtle as t
import random
t.speed(0)
t.shape('circle')
while True:
t.forward(25 * random.random())
t.right(360 * random.random())
|
fee4831ef102d440d800c1142a2420e843aa8808 | SebastiGarmen/checkout | /productosEmpleados.py | 971 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Persona:
nombre = ""
apellido = ""
edad = 0
nacionalidad = ""
sexo = ""
def __init__(self, nombre="NA", apellido="NA", edad="NA", nacionalidad="mexicano", sexo=""):
self.nombre = nombre
self.apellido = apellido
self.edad = edad
sel... |
44c1cd0140dab1a369406292c8c7865f96e69e1c | HarryIsSecured/chattybot-python-hyperskill | /Problems/Healthy sleep/task.py | 196 | 3.53125 | 4 | a = int(input()) # Recommended
b = int(input()) # Over
h = int(input()) # Input
if h < a:
print('Deficiency')
else:
if h > b:
print('Excess')
else:
print('Normal')
|
3bb3f7cf5db3a34c6181fe369eddf4727579d2c9 | ivanjureta/new-concept-networks | /archive/v0/analysis/ilang_f_output_text.py | 615 | 3.96875 | 4 | # Functions to print to text files
# Print text to text file.
def print_to_txt(file_content, project_name, content_description, save_to_project_dir = False):
import os
from tabulate import tabulate
output_file_name = project_name + '_' + content_description + '.txt'
if save_to_project_dir == False:
... |
b0de2b2dcdf3e54d03182cfc106d976b90f0095c | danieljohnson107/EmpDat-Payroll | /payroll.py | 4,879 | 3.5 | 4 | from abc import ABC, abstractmethod
import os, os.path
PAY_LOGFILE = "paylog.txt"
employees = []
def load_employees():
"""Loads employee data into memory and creates an instance of the employee object for each entry"""
with open("employees.csv", "r") as emp_file:
first_line = True
for line in ... |
04f3fbda2d7553f9450a90d7b8d64b604e29fef2 | danieljohnson107/EmpDat-Payroll | /Checkpoints/Sprint Something/EnterNewEmployee.py | 10,012 | 3.875 | 4 | from tkinter import *
# from PIL import imageTk, Image
from UserData import *
from GuiValues import *
ud = UserData()
gv = GuiValues()
''' to use images yoy need to install pillow
install with "pip install pillow" on your python to use
ImageTk.PhotoImage(Image.open("imagename.png"))
put image in widget
then put on pa... |
77ef65d344b1306138c43cfd77ee29774126d632 | THEIOTIDIOT/data_structures_and_algorithms | /P1/huffman_coding_task_3.py | 2,855 | 3.5 | 4 | import sys
class Node:
def __init__(self, value):
self.value = value
self.char = None
self.left_child = None
self.right_child = None
self.left_code = None
self.right_code = None
def set_value(self, value):
self.value = value
def get_value(self):
... |
5e0280d79cfd8be76595523a7c329bd0c6735ad3 | THEIOTIDIOT/data_structures_and_algorithms | /P1/recursion_indexed_linear_time.py | 2,284 | 4.03125 | 4 | """
def sum_array_index(array, index):
# Base Cases
if len(array) - 1 == index:
return array[index]
return array[index] + sum_array_index(array, index + 1)
arr = [1, 2, 3, 4]
print(sum_array_index(arr, 0))
"""
"""
def recursion(listy, num):
if len(listy) == 0:
print('False')
r... |
1e40b7e83b0f6b42321108d478be47b6610fabe8 | terrywang15/optim_assignment | /knapsack/stupid_tree_search.py | 7,161 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
def parse_input(file_location):
with open(file_location, 'r') as input_data_file:
input_data = input_data_file.read()
Item = namedtuple("Item", ['index', 'value', 'weight'])
# parse the input
lines = input_data.spli... |
8bdad239bf2f477aa074cc51f058db1d5f4c66ff | MikeMull10/spanishproject | /Post.py | 1,490 | 3.671875 | 4 | import pygame
from math import *
class Post:
def __init__(self, screen, x, y):
self.win = screen
self.x = x
self.y = y
self.dx = 0
self.dy = 0
self.radius = 16
self.gravity = .8
def tick(self):
self.x += self.dx
self.y += self.dy
... |
90b59d5607388d4f18382624219a9fcfd7c9cf17 | LorenzoY2J/py111 | /Tasks/d0_stairway.py | 675 | 4.3125 | 4 | from typing import Union, Sequence
from itertools import islice
def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]:
"""
Calculate min cost of getting to the top of stairway if agent can go on next or through one step.
:param stairway: list of ints, where each int is a cost of ap... |
15242cc4f007545a85c3d7f65039678617051231 | LorenzoY2J/py111 | /Tasks/b1_binary_search.py | 841 | 4.1875 | 4 | from typing import Sequence, Optional
def binary_search(elem: int, arr: Sequence) -> Optional[int]:
"""
Performs binary search of given element inside of array
:param elem: element to be found
:param arr: array where element is to be found
:return: Index of element if it's presented in the arr, N... |
7941328e4cb2d286fefd935541e2dab8afde61c0 | SACHSTech/ics2o1-livehack---2-Maximilian-Schwarzenberg | /problem2.py | 771 | 4.59375 | 5 | """
-------------------------------------------------------------------------------
Name: problem2.py
Purpose: To check if the inputted sides form a triangle.
Author: Schwarenberg.M
Created: 23/02/2021
------------------------------------------------------------------------------
"""
# Welcome message
print("Welcome ... |
88ad6f097eae9f8f1944d6d7ed0de2e8432bf5b7 | vandat0599/DecisionTree | /ID3_AI.py | 5,461 | 3.625 | 4 | import matplotlib.pyplot as plt
from sklearn import datasets
import pandas as pd
import numpy as np
import math
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
iris=datasets.load_iris()
X=iris.data
y=iris.target
#split dataset into training data and testing data
X_train,... |
098005bffaac2433081c9fde0decda640f2a5809 | lyfxgd/Test | /ground.py | 5,576 | 3.53125 | 4 | # # 斐波那契
# a = 0
# b = 1
# fbLength = 10
# for i in range(fbLength):
# print(a,end=' ')
# a, b = b , a + b
# ---------------------------
# # for loop
# aaa = [1,2,3,4,5,6,7,8,9,0]
# for i in range(len(aaa)):
# print(aaa[i],end=' ')
# print() #换个行
# for i in aaa:
# print(i,end=' ')
# -----... |
66b8b7e645ccd548eddf896153738f8e3d3974f5 | tgquintela/pySpatialTools | /pySpatialTools/utils/util_classes/Membership.py | 17,497 | 3.71875 | 4 |
"""
Membership
----------
Module which contains the classes and functions needed to define membership
object.
Membership object is a map between elements and collections to which they
belong. It is done to unify and simplify tasks.
"""
import numpy as np
import networkx as nx
from scipy.sparse import coo_matrix, is... |
89a48a124f396752291d053063f6126c8bbac45c | nigelaukland/project-euler | /euler_005.py | 835 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 22:55:22 2020
https://projecteuler.net/problem=5
@author: nigel
"""
# What is the smallest positive number that is evenly divisible by all of the
# numbers from 1 to 20?
# All integers less than or equal to ten can be ignored
# check each integer greater than 20
# lo... |
7feee7c365f92d707d7967c2b8ccb99323957a11 | nigelaukland/project-euler | /euler_002.py | 324 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 6 21:46:26 2020
https://projecteuler.net/problem=2
@author: nigel
"""
# create fibonnaci sequence
# sum all even elements
a, b = 0, 1
total = 0
while a < 4000000:
a, b = b, a + b
print("b = ", b)
if b % 2 == 0:
total += b
print("total = ", to... |
0679779b2fdd92c7f8d85170088ac46ebe1fe985 | astat17/PythonCourse | /hw_B3.py | 193 | 3.625 | 4 | first_dna, second_dna, mutation = input(''), input(''), 0
for i in range ( len (first_dna) ):
if first_dna[i] != second_dna[i]:
mutation += 1
print(mutation)
|
05dcc638c74e67fbc1248394e9f775cec5118c1e | pulakdas1999/DecisionTree | /Machine_learning_5_Decision_Tree.py | 4,746 | 3.765625 | 4 | training_data = [
['Green',3,'Mango'],
['Yellow',3,'Mango'],
['Red',1,'Grape'],
['Red',1,'Grape'],
['Yellow',3,'Lemon']
]
header = ['Color','Diameter','Label']
# Find the unique values for a column in dataset.
def unique_vals(rows,columns):
return set([rows[columns] for row in rows])
... |
12bc8c474358876720c5c6f6cb2adaedaebb9bac | adkulas/Project-Euler | /006_problem.py | 803 | 4.0625 | 4 | '''
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Fi... |
c4bdec7d10a125cbbb4da1edfc4aca7004064d2e | sriniverve/Python_Learning | /venv/tests/decorators.py | 633 | 3.875 | 4 | '''
This is to demonstrate the usage of decorators
'''
import time
import math
#function decorators
def decorator_timer(func):
#print('came in to the decorator')
def timer_function(*args, **kwargs):
print('Inner function started')
begin_time = time.time()
print(begin_time)
fun... |
9b3495345e4f4ad9648dcca17a8288e62db1220e | sriniverve/Python_Learning | /venv/tests/conditions.py | 271 | 4.21875 | 4 | '''
This is to demonstrate the usage of conditional operators
'''
temperature = input('Enter the temperature:')
if int(temperature) > 30:
print('This is a hot day')
elif int(temperature) < 5:
print('This is a cold day')
else:
print('This is a pleasant day') |
1140a8dd58988892ecca96673ffe3d2c1bf44564 | sriniverve/Python_Learning | /venv/tests/guessing_number.py | 395 | 4.21875 | 4 | '''
This is an example program for gussing a number using while loop
'''
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess_number = int(input('Guess a number: '))
guess_count += 1
if guess_number == secret_number:
print('You guessed it right. You Win!!!')
... |
a5c94db302c2c2fc7e394569f90372b9df42ecd9 | sriniverve/Python_Learning | /venv/tests/modules.py | 151 | 3.5 | 4 | from libs.utils import utils
list = [1, 5, 9, 3, 2, 8]
largest = utils()
largest_num_in_list = largest.find_max(list)
print(largest_num_in_list)
|
01b3319010f240b6ddfdd0b5ae3e07f201a9a046 | sriniverve/Python_Learning | /venv/tests/kg2lb_converter.py | 285 | 4.21875 | 4 | '''
This program is to take input in KGs & display the weight in pounds
'''
weight_kg = input('Enter your weight in Kilograms:') #prompt user input
weight_lb = 2.2 * float(weight_kg) #1 kg is 2.2 pounds
print('You weight is '+str(weight_lb)+' pounds')
|
2d7f003b6d1f2d148586e8ca3ac26a55a6869bc9 | vmmc2/Competitive-Programming | /Cracking The Code/Chapter 1 (Arrays and Strings)/1_6(string compression).py | 863 | 3.5 | 4 | def compress(s1: str) -> str:
s2 = ""
index = 0
tam = len(s1)
counter = 1
while index <= tam - 1:
if index > 0:
if index == tam - 1:
if s1[index] == s1[index - 1]:
counter += 1
s2 = s2 + s1[index] + str(counter)
... |
23d110cff79eb57616586da7f78c7ac6d4e7a957 | vmmc2/Competitive-Programming | /Sets.py | 1,369 | 4.4375 | 4 | #set is like a list but it removes repeated values
#1) Initializing: To create a set, we use the set function: set()
x = set([1,2,3,4,5])
z = {1,2,3}
#To create an empty set we use the following:
y = set()
#2) Adding a value to a set
x.add(3)
#The add function just works when we are inserting just 1 element into our ... |
720af938c7a753de2be6a73a89711de860527d92 | vmmc2/Competitive-Programming | /LeetCode/Top Interview Questions/Hard Collection/Array and Strings/Game of Life (Space - O(1)).py | 1,710 | 3.53125 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# This version will have a space-complexity of O(1) instead of O(m*n)
# Se uma celula que era viva (1) morrer, eu transformo ela em -1.
... |
0594a4160131b1fb61465082360eef71b1e9704a | vmmc2/Competitive-Programming | /LeetCode/Top Interview Questions/Medium Collection/Arrays and Strings/Group Anagrams(MUCH BETTER).py | 621 | 3.734375 | 4 | from collections import defaultdict
# A funcao ord() de python3 retorna o codigo da tabela ASCII de um char.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = defaultdict(list) # dicionario que mapeia para listas..
for string in strs: # iterando sobre cada string
... |
52377e7a4daa4d849a168c07dcef1c0eae862ead | vmmc2/Competitive-Programming | /Codeforces/50A - Domino Piling.py | 228 | 3.671875 | 4 | dominoarea = 2
linha, coluna = input().split()
#convertendo de string para inteiro
linha = int(linha)
coluna = int(coluna)
#calculando a area do tabuleiro
area = linha*coluna
#resposta
dominos = area//dominoarea
print(dominos)
|
768ce4a45879ad23c94de8d37f33f7c8c50dca24 | AmangeldiK/lesson3 | /kall.py | 795 | 4.1875 | 4 | active = True
while active:
num1 = int(input('Enter first number: '))
oper = input('Enter operations: ')
num2 = int(input('Enter second number: '))
#dict_ = {'+': 'num1 + num2', '-': 'num1 - num2', '*': 'num1 * num2', '/': 'num1 / num2'}
if oper == '+':
print(num1+num2)
elif oper == '-... |
ed0fe74197a845a6cf4c59c9c106050bbe0bdd91 | erickfmm/ANMetaL | /src/anmetal/iterative_methods.py | 441 | 3.625 | 4 |
def euler_method(dy_times_dx_func, x_start, x_end, y0, n_steps):
h = float(x_end - x_start) / float(n_steps)
x = x_start
y = y0
for _ in range(n_steps):
y = y + h * dy_times_dx_func(x, y)
x = x + h
return y
def newton_method(func, derivative_func, x_start, n_iterations, m=1):
... |
69795887c2cd00981551931827615e124d6fd14e | mharmanani/hangman-cli | /hangman.py | 3,731 | 4.1875 | 4 | """
hangman.py
Mohamed Harmanani, 2017
"""
import random
from HangmanWord import *
from HangingMan import *
import getpass
ROOT = '.lang/'
#modules for pick_language
LANGUAGES = { 0: 'english',
1: 'french',
2: 'spanish' }
MAX_LANG_INDEX = max(list(LANGUAGES.keys()))
MIN_LANG_INDEX = min(list(LANGUAGES.keys... |
b42889f94a49b620300eec99b9f9ff9b793c0867 | macgors/Prog-Class-tasks | /list1/3.py | 149 | 3.671875 | 4 | from numpy import dot
from math import sqrt
def cosine(a,b):
return dot(a,b) / (sqrt(dot(a,a))*sqrt(dot(b,b)))
print(cosine((1,1,1), (-1,1,1))) |
bbd1f925c4f75ce3df82a0c8f644c077739fb776 | macgors/Prog-Class-tasks | /list1/2.py | 160 | 3.5625 | 4 | import random
from typing import List
def mean(lst: List[int]) -> int:
return sum(lst) / len(lst)
print(mean([random.randint(10, 90) for _ in range(20)])) |
729cbbfce5e4444bb70f8a204c482a98d4207ab8 | TJBachorz/BJJ | /Data/create_work_dictionary.py | 4,306 | 3.59375 | 4 | from nltk.corpus import stopwords
sw = stopwords.words("english")
from Functions.functions import iterative_levenshtein as lev
from Functions.functions import get_key
#################### FUNCTION TO CREATE A DICTIONARY #########################
#
# I am creating a work-in-progress dictionary, where I find words si... |
356512f8a2f2e12aa231238a789ad4ff2be8401a | FaithS15-6/L1_Programmign-Assessment | /04fixing_rounds_v2.py | 3,155 | 4.09375 | 4 | import random
# Functions go here...
def intcheck(question):
while True:
response = input(question)
round_error = "Please type either <enter> or an " \
"integer that is more than 0\n"
# If infinite mode not chosen, check response
# Is an integer that is mor... |
882064b6ad10fd35ea7a9d251f067d9f7eab3656 | patricknelli/SF_DAT_17_WORK | /code/04_more_pandas_lab.py | 3,987 | 3.625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
'''
Part 1: UFO
'''
ufo = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/SF_DAT_17/master/data/ufo.csv') # can also read csvs directly from the web!
# 1. change the column names so that each name has no spaces
# and a... |
0b9ab5984a8213a6756575cf6d0fb88ca6302103 | rampac/ArtificialIntelligence | /SciKit_Learn/DecisionTree.py | 1,818 | 3.921875 | 4 | # A decision tree is one of most frequently and widely used supervised machine learning algorithms that can perform both regression and classification tasks.
#classification solution
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
dataset = pd.read_csv("D:/Datasets/bill... |
bea03d15b11574ed4b225fe22bc6e7d6ec37ed26 | brantheman60/BIPS-Robotics-Course-Labs | /lab2/lab2_student.py | 2,062 | 4.03125 | 4 | from lab2_questions import question_list
import random
round = 1 # current round number
completed = [] # list of the indices of completed questions
# TODO: Check that every question has exactly 6 elements,
# and the last element is either "A", "B", "C", or "D"
for question in question_list:
assert(???)
a... |
2d2d81bc949b136f791868c948c07fdaa4eccb45 | viclule/performance_script_machine_learning | /opmimization/particle_swarm.py | 5,978 | 3.859375 | 4 | # particle swarm optimizer
# based on the article:
# https://medium.com/analytics-vidhya/implementing-particle-swarm-optimization-pso-algorithm-in-python-9efc2eb179a6
import random
import numpy as np
class Particle():
"""
A particle of the swarm
"""
def __init__(self, dimensions):
"""
... |
11ad8bdf32ed08e847fc5a8fa68a91783b473da9 | ilookforme102/bachelor_thesis | /Sentiment_Analysis.py | 2,342 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 12:59:00 2019
@author: macbook
"""
from textblob import TextBlob
import re
import string
def clean_data(tweet):
# Remove HTML special entities (e.g. &)
tweet = re.sub(r'\&\w*;', '', tweet)
# To lowercase
tweet = tweet.lower()
... |
99a0eb3222f6d9994f0e9295c5d1f3a5a7e8e6a0 | maleeham/Leetcode | /ValidPalindrome.py | 406 | 3.90625 | 4 | /*Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.*/
class Solution:
def isPalindrome(self, s):
translator = str.maketrans('', '', string.punctuation + ' ')
s = s.translate(translator)
s = s.lower()
return s == s[::-1]
... |
0aa44823b9d602567270221004e967033998b4a9 | mcphersonmd28/Fin5350-Assignments | /Assignments/Assignment1WordProblems/Assignment 1_Word Problem_Madyson McPherson.py | 2,197 | 4.09375 | 4 | print("Word Problem 1")
print("If a group of 5 students work on a project for 70 hours and they")
print("split the work evenly, how many hours does each student work?")
input("Press enter to find out.")
print("70 / 5 =", 70 // 5)
print("")
print("Word Problem 2")
print("If George orders 6 whole pizza cut into 12 slice... |
11a14bcda4c59606d82520cd0c833e4d0e2f33c6 | alvaro3023/t10_Rojas.delacruz | /ROJAS_OLIVA/menu3.py | 430 | 3.765625 | 4 | # Menu de comandos
opc=0
max=3
while(opc!= max):
print("############### MENU ##############")
print("#1. agregar area triangulo")
print("#2. agregar area trapecio ")
print("#3. salir ")
#2. Eleccion de la opcion menu
opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3)
#3. Mapeo de las opci... |
dab9dfc7cc08cb6adc931582928adea652e5bc0e | alvaro3023/t10_Rojas.delacruz | /ROJAS_OLIVA/menu1.py | 414 | 3.84375 | 4 | import libreria
# Menu de comandos
opc=0
max=3
while(opc!= max):
print("############### MENU ##############")
print("#1. pedir RUC ")
print("#2. Mostrar monto")
print("#3. Salir")
#2. Eleccion de la opcion menu
opc=libreria.pedir_numero("Ingreso la opcion:", 1, 3)
#3. Mapeo de las opciones... |
c5d41a0ce9a8153202fd0acc7d05e9a60f1dcf37 | alvaro3023/t10_Rojas.delacruz | /DelaCruz/app4.py | 570 | 4.09375 | 4 | import libreria
opc=0
max=3
def agregar_uni():
input("Ingresar universidad: ")
def agregar_carrera():
input("Ingresar carrera profesional: ")
while (opc!=max):
print("########## MENU #############")
print("#1. Universidad #")
print("#2. Carrera profesion #")
print("#3. Salir... |
109ab8774125f4f49defeda0c726533f62aeda66 | fisadev/zombsole | /players/randoman.py | 713 | 3.609375 | 4 | # coding: utf-8
import random
from things import Player
class RandoMan(Player):
"""A player that decides what to do with a dice."""
def next_step(self, things, t):
action = random.choice(('move', 'attack', 'heal'))
if action in ('attack', 'heal'):
self.status = action + 'ing'
... |
230616616f10a6207b4a407b768afaabb846528a | SynthetiCode/EasyGames-Python | /guessGame.py | 744 | 4.125 | 4 | #This is a "Guess the number game"
import random
print('Hello. What is your nombre?')
nombre = input()
print('Well, ' + nombre + ', I am thining of a numero between Uno(1) y Veinte(20)')
secretNumber =random.randint(1,20)
#ask player 6 times
for guessesTaken in range(0, 6):
print ('Take a guess:' )
guess = int(inpu... |
e291518a1582a80bc20f25d383ad863a2d0219c1 | mdanassid2254/pythonTT | /constrector/5prog.py | 973 | 3.578125 | 4 | class Customer:
def setcustomerid(self,customerid):
self.__customerid=customerid
def getcustomerid(self):
return self.__customerid
def setcustomername(self,customername):
self.__customername=customername
def getcustomername(self):
return self.__customername
class... |
fb038cc7201cd3302a5eeedf9fd86511d6ff2cf6 | mdanassid2254/pythonTT | /constrector/hashing.py | 422 | 4.65625 | 5 | # Python 3 code to demonstrate
# working of hash()
# initializing objects
int_val = 4
str_val = 'GeeksforGeeks'
flt_val = 24.56
# Printing the hash values.
# Notice Integer value doesn't change
# You'l have answer later in article.
print("The integer hash value is : " + str(hash(int_val)))
print("The stri... |
dd80f057de9d0de521b37e1dea8fdbaf9ea5d6e6 | mdanassid2254/pythonTT | /constrector/superk_keyword.py | 425 | 3.578125 | 4 | class c1:
def __init__(self,a,b):
print(self)
self.a=a
self.b=b
def area(self):
print(self.a*self.b)
print(self)
class c2(c1):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
print(self)
def vol(self):
pr... |
140ec062dcfd212169b33720ef0395ef46e24ff7 | mzakrze/tkom-interpreter | /tokens.py | 1,667 | 3.5625 | 4 | from enum import Enum
class TokenType(Enum):
INT = "int"
double = "double"
BOOLEAN = "boolean"
STRING = "string"
POSITION = "position"
MOVEABLE = "moveable"
DEF = "def"
WHILE = "while"
IF = "if"
ELSE = "else"
RETURN = "return"
NULL = "null"
VAR = "var"
TRUE = "tr... |
4c6440cd45ecaeb0152d2c5bc017fdc56a33afc1 | AliMurtaza096/alilab2 | /ver.py | 54 | 3.5 | 4 | # Multiply
def mul(x,y):
return x*y
print(mul(5,3)) |
0e6b136b69f36b75e8088756712889eb45f1d24a | Kaden-A/GameDesign2021 | /VarAndStrings.py | 882 | 4.375 | 4 | #Kaden Alibhai 6/7/21
#We are learning how to work with strings
#While loop
#Different type of var
num1=19
num2=3.5
num3=0x2342FABCDEBDA
#How to know what type of date is a variable
print(type(num1))
print(type(num2))
print(type(num3))
phrase="Hello there!"
print(type(phrase))
#String functions
num=len(phrase)
print(p... |
7bfc308392fd4f8fd82ed0d2d5fb19ab1789bb8b | mdmss37/programmingQuiz | /mathPazzle/03_card_turn.py | 574 | 3.765625 | 4 | def create_cards_facingdown(n):
empty_dic = {}
for i in range(1,n):
empty_dic[i] = False
return empty_dic
cards_set = create_cards_facingdown(101)
def card_turn(start):
current = cards_set
while start < 101:
#print(start)
for i in range(start,101,start):
#print(current[i])
if current... |
8523346cb241006bae4a9f3e69a3b0d22ee406b5 | mdmss37/programmingQuiz | /UdacityIntroToCS/mutateList.py | 475 | 3.875 | 4 | # Mutating lists. which of the following procedures
# leves the value passed in as the input unchanged?
def proc1(p):
p[0] = p[1]
def proc2(p):
p = p + [1]
def proc3(p):
q = p
p.append(3)
q.pop()
def proc4(p):
q = []
while p:
q.append(p.pop())
while q:
p.append(q.pop(... |
449bc7be6a6278d204083ed27a63facbfe57a931 | 1049884729/projecteulerByPython | /Question12.py | 1,102 | 4.03125 | 4 | '''
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
n * (n + 1) / 2;
求第一个拥有超过500个因子的三角数?
'''
import math
print(int(math.sqrt(15)))
def divisors(integer):
'''
算法理由:如果一个数,能够整除某个数的平方根,那么肯定有一个比它大的数也能够整除;
所以只需检查interge... |
2f1f2581f1237b8adce941c4b8a48d89dc177399 | Hehwang/Leetcode-Python | /code/082 Remove Duplicates from Sorted List II.py | 956 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
retu... |
9a799e2d2ba2c8973cf5af8a7d07e251f40ad36f | Hehwang/Leetcode-Python | /code/224 Basic Calculator.py | 1,162 | 3.546875 | 4 | class Solution:
# 定义一个函数计算括号里的式子
def helper(self,s):
length=len(s)
# 检查时候含有'--','+-'
s=''.join(s)
s=s.replace('--','+')
s=s.replace('+-','-')
s=[x for x in s if x!='#']
s=['+']+s[1:-1]+['+']
tmp=0
lastsign=0
for i in range(1... |
296b5c3c6f16c368d547ad14c2f5e9b981825a3a | Hehwang/Leetcode-Python | /code/461 Hamming Distance.py | 288 | 3.59375 | 4 | class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
tmp=x^y
res=0
while tmp!=0:
if tmp%2!=0:
res+=1
tmp=tmp>>1
return res |
ea7b9f0cefeca1c88653ba86342bc82727cf8ff2 | Hehwang/Leetcode-Python | /code/504 Base 7.py | 411 | 3.5 | 4 | class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num==0:
return "0"
flag=True if num>0 else False
num=abs(num)
res=[]
while num:
res.append(str(num%7))
num=num//7
... |
f7aac03275b43a35f790d9698b94e76f93207e7d | abokareem/LuhnAlgorithm | /luhnalgo.py | 1,758 | 4.21875 | 4 | """
------------------------------------------
|Luhn Algorithm by Brian Oliver, 07/15/19 |
------------------------------------------
The Luhn Algorithm is commonly used to verify credit card numbers, IMEI numbers, etc...
Luhn makes it possible to check numbers (credit card, SIRET, etc.) via a control key (... |
f17e1ca5453a920e41097d3c045638edce0dc3fc | cramosCuc/Exercism_Python | /acronym/acronym.py | 149 | 3.953125 | 4 | import re
def abbreviate(palabras):
regex = "[A-Z]+['a-z]*|['a-z]+"
return ''.join(word[0].upper() for word in re.findall(regex, palabras))
|
1677fac97c69a1a4419e3352dab0cc1537600532 | cramosCuc/Exercism_Python | /pangram/pangram.py | 133 | 3.859375 | 4 | from string import ascii_lowercase
def is_pangram(oracion):
return all(char in oracion.lower() for char in ascii_lowercase)
|
35d1e795d933697b63f90dce0e9bd9e2074b184b | kadikraman/KadiCarAPI | /backend/database/convert_json_to_sql.py | 2,341 | 3.5 | 4 | '''
This will read in data from data.json and convert it into a dict
Then will create or rewrite populate_db.py with the insert statements
to insert all the data that was in the JSON file to the expenses table
'''
import json
import time
json_data = open('data.json')
# load the json data into a dictionary
data = jso... |
717156b49b0614af228351169b0bbc8081394293 | kaddynator/nqueens-npuzzle-localsearch | /scratch.py | 711 | 3.875 | 4 | def h_distinct_attacks(queen_state):
'''Groups attack pairs together if they share a common queen and returns the number of groups'''
def have_queen_in_common(queen_list_a, queen_list_b):
return len(set(queen_list_a + queen_list_b)) < len(queen_list_a) + len(queen_list_b)
attacking_pairs = q... |
027ab31cab21f5034a69b2002e2f67b4238033b9 | AlSavva/Python-basics-homework | /homework2-3.py | 1,138 | 3.984375 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна,
# лето, осень). Напишите решения через list и через dict.
month_list = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль",
"Август", "Сентябрь", "Октябрь", "Ноябрь", "Д... |
a0d900a3e43322ab1e994aa82f74a5d759e8260a | AlSavva/Python-basics-homework | /homework3-4.py | 2,163 | 4.21875 | 4 | # Программа принимает действительное положительное число x и целое
# отрицательное число y. Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y). При
# решении задания необходимо обойтись без встроенной функции возведения числа
# в степень.
# Подсказка:... |
1eaded5afd7676febe14409d999ba0699c2cb90a | AlSavva/Python-basics-homework | /homework4-7.py | 1,007 | 3.75 | 4 | # Реализовать генератор с помощью функции с ключевым словом yield, создающим
# очередное значение. При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n). Функция
# отвечает за получение факториала числа, а в цикле необходимо выводить только
# первые... |
fd180a26aaf3b285ae1d738511f62e86398e18ac | AlSavva/Python-basics-homework | /homework6-5.py | 1,543 | 3.9375 | 4 | # Реализовать класс Stationery (канцелярская принадлежность). Определить в нем
# атрибут title (название) и метод draw (отрисовка). Метод выводит сообщение
# “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil
# (карандаш), Handle (маркер). В каждом из классов реализовать переопределение
# метода dr... |
9d53ed431fc3adbbb34c08123750600c7fbfff08 | catdog001/leetcode_python | /Tree/上海交大数据结构树的课程/树课程的相关代码/huffmanTree.py | 3,486 | 3.515625 | 4 | """
Huffman Tree used for compression
上海交大翁老师的:
https://www.bilibili.com/video/BV18t411U7tH?from=search&seid=14727695894489847315
青岛大学王卓老师的:
https://www.bilibili.com/video/BV18t411U7tz/?spm_id_from=trigger_reload
https://www.bilibili.com/video/BV18t411U7tz/?spm_id_from=trigger_reload
"""
class TreeNode(object):
"... |
44da9a33162d262a1d588d67cd9b4d82c12b53ee | catdog001/leetcode_python | /BinarySearch/33.py | 1,100 | 3.890625 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums or len(nums) == 0:
return False
left, right = 0, len(nums) - 1
while left <= right:
mid = int(left ... |
a8051d4c26e31ecb5a315948a9e3bdad44975aec | catdog001/leetcode_python | /Tree/leetcode_tree/easy/226.py | 1,546 | 4.15625 | 4 | """
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class TreeNode(object):
def __init__(self, val):
self.val = val
... |
0961b93e1cebfd23c52773fa2ff942f42bd0ee5f | catdog001/leetcode_python | /Tree/leetcode_tree/easy/107.py | 2,900 | 3.984375 | 4 | """
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
"""
解题思路:... |
317e00bba0d45bba71e4d31b5e8fd60e41badddb | mrled/education | /cryptopals-2013/cryptopals.py | 29,126 | 3.515625 | 4 | #!/usr/bin/env python3
import argparse
import base64
import string
import sys
import math
import binascii
import itertools
# requires pycrypto
from Crypto.Cipher import AES
########################################################################
## Backend libraryish functions
def safeprint(text, unprintable=False,... |
8812d73519fb3656dc2252f57a96fae758d2c174 | qwert100good/Python004 | /Week03/homework01/homework_v1.py | 3,247 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
@author : Yx
"""
# # 示例代码
# import threading
# class DiningPhilosophers:
# def __init__(self):
# pass
# # philosopher 哲学家的编号。
# # pickLeftFork 和 pickRightFork 表示拿起左边或右边的叉子。
# # eat 表示吃面。
# # putLeftFork 和 putRightFork 表示放下左边或右边的叉子。
# def wantsToEat(self,
# philosopher,
# ... |
f1d8fd7ceeeef8fc1982dfee3213ef436334775c | NaruBeast/Basic-Python-Programs | /swap.py | 219 | 3.90625 | 4 | num1 = input("Enter 1st number: ")
num2 = input("Enter 2nd number: ")
print "Before swapping: num1 =", num1, "and num2 =", num2
num1, num2 = num2, num1
print "After swapping swapping: num1 =", num1, "and num2 =", num2
|
cd1bb66c9bdc5b05d8ec8e17a1a1d8b4fa255989 | NaruBeast/Basic-Python-Programs | /kilo-mile.py | 98 | 3.890625 | 4 | x = input("Enter distance in kilometers: ")
y = x * 0.621371
print x, 'kilometers = ', y, 'miles' |
f0a08661d9c12875149f811c016dbbd8fe3d3538 | getHecked/sample-repo | /tests/reading_documentation.py | 1,048 | 3.8125 | 4 | import re
file = open("test1.txt", 'r',encoding='utf-8').read()
words={}
slist=file.replace("\W+",'').split(" ")
for element in slist:
if element in words:
words[element]+= 1
else:
words[element]=1
words
lowest = min(words.values())
highest = max(words.values())
for word,freq in words.items():... |
f4e4beb1d2975fd523ca7dd744aa7a96e686373a | WeiyiDeng/hpsc_LinuxVM | /lecture7/debugtry.py | 578 | 4.15625 | 4 | x = 3
y = 22
def ff(z):
x = z+3 # x here is local variable in the func
print("+++ in func ff, x = %s; y = %s; z = %s") %(x,y,z)
return(x) # does not change the value of x in the main program
# to avoid confusion, use a different symbol (eg. u) instead of x in the function
pr... |
d4391135272c24e27386c954bc887af2c32918f1 | WaaberiIbrahim/pizzapi | /main.py | 1,211 | 3.6875 | 4 | from pizzapy import *
print('Bienvenue au DPPD')
print('Nous avons besoin de quelques informations avant de vous livrer')
name = input('Entrer votre nom (Premom et nom de famille seulement)')
email = input('Entrer votre email: ')
phone = input('Entrer votre numero de telephone')
addresse = input('Entrer votre adresse... |
f402afcc94362754bec35826f5b155d050b256e2 | Muntaha-Islam0019/HackerRank-Solutions | /Problem Solving/Algorithms/Mark and Toys.py | 594 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'maximumToys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY prices
# 2. INTEGER k
#
def maximumToys(prices, k):
# Write your code here
... |
ec7cc31141437232aecb562f0a5c9f75b43e4184 | Muntaha-Islam0019/HackerRank-Solutions | /Problem Solving/Algorithms/Jim and the Orders.py | 705 | 3.75 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'jimOrders' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_INTEGER_ARRAY orders as parameter.
#
def jimOrders(orders):
# Write your code here
s = sorted(enumerate(orde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.