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 |
|---|---|---|---|---|---|---|
df16725150980de62752fa83d810ac40677eecd9 | gaulghost/py4e | /Intro/Practice.py | 1,253 | 3.921875 | 4 | for i in range(1,4) :
'''
type(anything)
will give its type
st1 + str2 will concatenate the strings
operator precedence
parenthesis
power
division Multipication
addition substraction
left to right
max() and min()
for i in range(5) :
print(i)
... |
53f1f2049a3a31a4a63a0fc38fb77d1466e3ffa3 | therealrooster/fizzbuzz | /fizzbuzz.py | 740 | 4.21875 | 4 | def fizzbuzz():
output = []
for number in range (1, 101):
if number % 15 == 0:
output.append('Fizzbuzz')
elif number % 3 == 0:
output.append('Fizz')
elif number % 5 == 0:
output.append('Buzz')
else:
output.append(number)
... |
0d96c6c4315e24ac784d7164967a5014007fc597 | belemizz/mimic2_tools | /clinical_db/mutil/graph.py | 18,161 | 3.578125 | 4 | """A class for controling graph."""
import numpy as np
import matplotlib.pyplot as plt
from math import log10, ceil, sqrt
from more_itertools import chunked
import cPickle
from .type import is_number, float_list
class MGraph:
"""Control graphs and visualizaton."""
def __init__(self):
self.dir_to_save ... |
07ad67d0d95db75c4c880d2bbdfd81c6f0829c1f | Luke-TE/trending-tweet-generation | /trendingtweet/utils/string_functions.py | 501 | 3.6875 | 4 | from collections import namedtuple
def nested_dict_to_obj(d, name="NamedTuple"):
if isinstance(d, dict):
d = dict(d)
for attr_name, attr_value in d.items():
d[attr_name] = nested_dict_to_obj(attr_value)
return namedtuple(name, d.keys())(**d)
elif isinstance(d, list):
... |
5252ffd945d0e89cc83b53ebae7ed66cd8fb3a9c | zagara2/PythonEncryptDecrypt | /Pigify.py | 5,064 | 3.6875 | 4 | '''
Created on February 9, 2016
@author: Marimikael Seibert
'''
def isVowel(chara):
'''
returns True if a character is included in "aeiou" or "AEIOU"
'''
if chara in "aeiouAEIOU":
return True
else:
return False
def noVowels(word):
'''
returns True if a word (other than t... |
7a91119c3ff70309cad921f39b06f4fddf8df587 | taeyoungchoon/taeyoungchoon.github.io | /dhms_simple.py | 579 | 3.796875 | 4 | #!/usr/bin/env python3
#
# seconds to dhms(days, hours, minutes, seconds) without if
# simple but hard to understand
i = 24 * 60 * 60 + 60 * 60 + 60 + 1
dv = 24 * 60 * 60
hv = 60 * 60
mv = 60
# d = int( i / (24 * 60 * 60) )
# h = int( int( i % (24 * 60 * 60) ) / (60 * 60) )
# m = int( int( int( i % (24 * 60 * 60) ) ... |
81c8b00713bdc7169f2dcaf7051c1dc376385a5a | zeyuzhou91/PhD_dissertation | /RPTS/bernoulli_bandit/auxiliary.py | 1,561 | 4.15625 | 4 | """
Some auxiliary functions.
"""
import numpy as np
def argmax_of_array(array):
"""
Find the index of the largest value in an array of real numbers.
Input:
array: an array of real numbers.
Output:
index: an integer in [K], where K = len(array)
"""
# Simple but does... |
f059f3f2319782c8e288bbbef3b1597674267daf | iCodeIN/HandOnPython | /basic/strings.py | 1,686 | 3.9375 | 4 | s = "hello munai"
# print(s)
# print "hel"
# print(s[0:3])
# print(s[3:5])
# forward index
# h e l l o
# 0 1 2 3 4
# backward index
# h e l l o
# -5 -4 -3 -2 -1
# print(s[0], s[-5])
# print(s[3:5], s[-2:])
# print(s[::-1])
# s = "hello munai"
# print "munai hello"
# m = s[-5:]
# p = s[0:5]
# print(m+" "+p)
... |
7fbacf05d3be62b984eda6478981fc5ae95fa1e0 | iCodeIN/HandOnPython | /basic/recursion.py | 11,061 | 3.96875 | 4 | # fibonacci number
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
# def fib(n):
# if n <= 1:
# return n
# else:
# return (fib(n-1) + fib(n-2))
# print([fib(i) for i in range(20)])
# def fact(n):
# if n == 1:
# return n
# else:
# return n * fact(n-1)
# print(fact(5))
# fact(5) = 5*... |
69db8941c7befdd16deeb8150b8a8c08a47e4008 | chris4540/algorithm_exercise | /leetcode/tree/zigzag_level_order_traversal.py | 926 | 3.828125 | 4 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
... |
253361e2df9827fda9ca743ff806dc365fe1a932 | chris4540/algorithm_exercise | /codejam/nesting_depth/sol.py | 1,300 | 3.875 | 4 | """
Outline:
1. insert parantheses according to digits depth (relaxation)
2. merging anti-paranthese pairs {i.e. ")(" } recusively (constraints)
"""
import re
def insert_parantheses(digit_string):
ret = ""
for c in digit_string:
depth = int(c)
# add left parantheses
ret += ''.join(['(... |
2a135f0df8abebeb0fb768b9d21d5d8d20af2f63 | chris4540/algorithm_exercise | /general/dna/dna.py | 3,105 | 3.953125 | 4 | import sys
import csv
def argparser():
# Check for correct number of args
if len(sys.argv) > 3:
print("Usage: python dna.py data.csv sequence.txt")
sys.exit(1)
db_file = sys.argv[1]
seq_file = sys.argv[2]
return db_file, seq_file
def get_STR(seq, motifs):
"""
Obtain the ... |
b87cafe0bec26f966a8c027f0aa4e3311be3a18f | chris4540/algorithm_exercise | /basic/arr_search/rotated_arr/simple_approach.py | 1,736 | 4.3125 | 4 | """
https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/
1) Find out pivot point and divide the array in two
sub-arrays. (pivot = 2) /*Index of 5*/
2) Now call binary search for one of the two sub-arrays.
(a) If element is greater than 0th element then
search in l... |
6883ccc47c89d0718052a4f1ac19ee1829a25a1c | chris4540/algorithm_exercise | /hackerrank/sort/fraudulent/workable.py | 1,413 | 3.609375 | 4 | from collections import deque
# Complete the activityNotifications function below.
def activityNotifications(expenditure, d):
"""k << d, n --> counting sort approach"""
k = max(expenditure)
historic_counts = [0] * (k+1)
trailing_history = deque([])
num_notifications = 0
for day in range(len(ex... |
8bbffb57ca622a1dcf0ab09a210ebf0fb4c1e7ca | chris4540/algorithm_exercise | /basic/recusion/swap_nodes_in_pairs.py | 1,110 | 4 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def print(self):
n = self
while n:
print(n.val, end="")
n = n.next
if n:
print("->", end="")
print("")
def swap_nodes(node: ListNod... |
c0c5ac402b6a28c5159f696d7e62c4c0df3c9cac | varshaahuja/IS601-1 | /MyCalc/Calculator.py | 1,621 | 4.03125 | 4 | class Calculator:
answer = 0
def __init__(self):
pass
@classmethod
def add(cls, num):
cls.answer += num
return round(cls.answer,6)
@classmethod
def subtract(cls, num):
cls.answer -= num
return cls.answer
@classmethod
def multiply(cls, num):
... |
e475e1cbb62c334ba4021ce8c59100e2dcfed696 | muskaanisrani/CECS451-Artificial-Intelligence | /board.py | 7,291 | 4.25 | 4 | """
Constructs a Board data structure made using a 2D array to mimic a matrix
Date: 20th July 2020
Authors: Muskan Israni & Keval Varia
Student ID: 017537908, 017834282
Class: CECS 451- Artificial Intelligence
"""
import numpy as np
class Board(object):
# default constructor
def __init__(self, maze_file):
... |
e57687af8cfa425ef9a824070db859cac05eb06d | lord12-droidd/Colokvium-AP | /Coloc 24.py | 823 | 3.8125 | 4 | """Знайти суму елементів масиву цілих чисел, які діляться на 5 і на 8
одночасно. Розмірність масиву - 30. Заповнення масиву здійснити випадковими
числами від 500 до 1000.
Мельник Д.В. 122А
"""
import random
massive = [random.randint(500, 1000) for i in range(30)] # Створюємо масив генератором списку
print(massive)
su... |
1ea98720fdf12d944ef6d7040f69d358e260e902 | lord12-droidd/Colokvium-AP | /Coloc 59.py | 780 | 3.53125 | 4 | """Дан одновимірний масив з 10 цілих чисел. Підрахуйте кількість різних
чисел в ньому.
Мельник Д.В. 122А
"""
import random
massive = [random.randint(1,8) for i in range(10)] # Створюємо масив генератором списку
print(massive)
count_set = set() # Створюємо пусту множину
for i in range(len(massive)):
count_set.ad... |
485c22525c25b0c8d5655d56b4bd9857b093fa8d | lord12-droidd/Colokvium-AP | /Coloc 54.py | 991 | 3.84375 | 4 | """Введіть масив з 20 елементів і визначте, чи є в ньому елементи з
однаковими значеннями.
Мельник Д.В. 122А
"""
import random
massive = [random.randint(-30,30) for i in range(20)] # Ініціалізуємо масив
print(massive)
count = 0 # Лічильник
for i in range(20):
count += massive.count(massive[i]) #Рахуємо входження... |
a6a31fcc0d947607662ea8d384c80c9c52412302 | lord12-droidd/Colokvium-AP | /Coloc 56.py | 1,750 | 3.6875 | 4 | """Якщо в одновимірному масиві є три поспіль однакових елемента, то
змінній r привласнити значення істина.
Мельник Д.В. 122А
"""
# Порівнюю поточний елемент з наступним тому так багато іфів(щоб програма не вилітала)
import random
massive = [random.randint(1,8) for i in range(15)] # Створюємо масив генератором списку
... |
d5ef05ead14901bf8170a35368bf8ebcb8cd8e9c | lord12-droidd/Colokvium-AP | /Coloc 53.py | 1,487 | 3.703125 | 4 | """В масиві X (1: n) кожен елемент рівний 0, 1 або 5. Переставити елементи
масиву так, щоб спочатку розташовувалися всі нулі, потім все одиниці, а потім всі
п'ятірки. Додаткового масиву не заводити.
Мельник Д.В. 122А
"""
import random
def selection_sort_ascending():
for i in range(n - 1):
min = i # Припу... |
f4ed928ad9ffb4f1bd0b940a3fd57fa98835dfba | lord12-droidd/Colokvium-AP | /Coloc 40.py | 766 | 3.703125 | 4 | """Обчислити суму парних елементів одновимірного масиву до першого
зустрінутого нульового елемента.
Мельник Д.В. 122А
"""
import random
massive = [random.randint(-10,10) for i in range(20)]
print(massive)
summa = 0
for i in range(len(massive)): # Проходим по елементам масиву
if massive[i] % 2 == 0 and massive[i] ... |
435a5a34727544444bcb1093280f49f585c0a87e | lord12-droidd/Colokvium-AP | /Coloc 42.py | 546 | 3.59375 | 4 | """Підрахувати кількість елементів одновимірного масиву, для яких
виконується нерівність i*i<ai<i!
Мельник Д.В. 122А
"""
import random
import math
count = 0
massive = [random.randint(4,110) for i in range(12)]
print(massive)
for i in range(len(massive)): # Проходим по елементам масиву
if i*i<massive[i] <math.fact... |
6642f04ca2c0d3a507647f4bbbe589e68bd0ca2b | felixfrz/python-oop | /attributes_methods.py | 645 | 3.609375 | 4 | # OOP Attributes and Methods
# from turtle import Turtle, Screen
# timmy = Turtle()
# timmy.shape('turtle')
# timmy.color('green')
# timmy.forward(distance=100)
# my_screen = Screen()
# print(my_screen.canvheight)
# my_screen.exitonclick()
#=========================
# PyPi.org
# first install the package e.g pr... |
c307c01c982ec0bed942d4372fb715f4c6d8d43b | georgeRenard/CrackingTheCodingInterview | /linked-lists/sumLists.py | 4,602 | 3.8125 | 4 | import sys
def problem():
"""
Sum Lists: You have two numbers represented by a linked list, where each node contains a single
digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a
function that adds the two numbers and returns the sum as a linked l... |
b59acc0f52f899006f2d55ea471fed06d36d5f7b | georgeRenard/CrackingTheCodingInterview | /stacks-and-queues/multistack.py | 3,894 | 4.0625 | 4 | import sys
STACK_1 = 1
STACK_2 = 2
STACK_3 = 3
class Multistack:
# Simulation of a standard array that is initialized
def __init__(self, size):
self.arr = [0] * size
self.capacity = size
self.stack_1_head = 0
self.stack_2_head = 1
self.stack_3_head = 2
... |
f857bf43291d133bafe0ba054ca4112c295e0b6e | georgeRenard/CrackingTheCodingInterview | /ds/stack.py | 1,730 | 3.890625 | 4 |
class Stack:
def __init__(self):
self.head = None
self.count = 0
def size(self):
return self.count
def push(self, item):
new_node = self.StackNode(item)
self.count += 1
if item is None:
raise Exception("You cannot push a None value into ... |
0bbc859c3a27b281348c958db33b7e98026f724a | georgeRenard/CrackingTheCodingInterview | /strings/urlify.py | 1,388 | 3.859375 | 4 | import sys
# Assumption 1 : We don't want to shuffle the original string -> Therefore, we exclude sorting
# Assumption 2 : We need to allocate +2 buffer size for each white space since %20 has 3 characters while a white space is a single byte character
# Question 1 : How do we find the value 32(whitespace) in the... |
c7403313da7b2a161cd26f7cc82e4b3f4180e4c2 | lowellausen/parabola_detector | /parabola_detector.py | 14,145 | 3.640625 | 4 | import cv2 # biblioteca opencv utilizada para funções de imagem
import numpy as np # biblioteca numpy para funções matemáticas, como a SDV
import sys
import random
from math import floor
# classe representando uma parábola
class Parabola:
def __init__(self, points, angle, imgsize):
# os pontos represen... |
d4fb07b218f8d69f4a8fd99d1ff6f251506b36db | A1rsenij/rep1 | /ADC_1.py | 1,258 | 3.5 | 4 | import RPi.GPIO as GPIO
import time
dac = [26, 19, 13, 6, 5, 11, 9, 10]
bits = len(dac)
levels = 2**bits
maxVoltage = 3.3
troykaModule = 17
comparator = 4
comparatorvalue = 1
GPIO.setmode(GPIO.BCM)
GPIO.setup(dac, GPIO.OUT, initial = GPIO.LOW)
GPIO.setup(troykaModule, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(comparato... |
1dc51c71b75330152a8618cb22f388c69ef34490 | R0dn3yS/Hangman | /hangman.py | 2,161 | 3.671875 | 4 | import random
import os
lines = open("./words.txt").read()
line = lines[0:]
words = line.split()
hWord = random.choice(words)
faults = 0
def status(guessDict, faults, guessedLetters):
print("\n\n-----------------------\n\n")
position = 1
gGuessCount = 0
if faults == 6:
print("You have lost")
print("\nThe ... |
0dd5474e53c8f6d6c09fe012a6e005499d595646 | smosciatti/Python | /GuessN/BinarySearch/guessNum.py | 696 | 3.875 | 4 | low =1
high = 1000
print ("Please think if a number between {} and {}".format(low,high))
input("Press ENTER to start")
guesses = 1
while True:
guess = low +(high -low) //2
high_low = input("My guess is {}. Should I guess highter or lower? "
"Enter h or l, or c if my guess was correc... |
f3c5c31448e03a4064ee2fddd9bbb369eb14c123 | hj424/bril | /tasks/t1/count_add.py | 1,148 | 3.703125 | 4 | # input: .json file
# output: total number of add instructions
import argparse
def main(args):
file_name_base = args.name
file_name = file_name_base + ".json"
if file_name_base == "":
print("Analyzing default file: "+file_name+"...")
# open the file
f_ptr = open(file_name, "r")
if (not f_ptr... |
8cd6104d061eba1d0a5c8f232a8973f8ce0180f2 | asabattz/python | /Ej7.py | 724 | 4.0625 | 4 | def encontrarNumeroAmigo(numero):
numeroAmigo = 0
for i in range(int(numero / 2) + 1, 0, -1):
if numero % i == 0:
numeroAmigo += i
return numeroAmigo
def sonAmigos(numero1, numero2):
if encontrarNumeroAmigo(numero1) == numero2 and numero1 == encontrarNumeroAmigo(numero2):
re... |
934bd21a86cf0a20a2bb8c85c3e8911702c2c773 | yashu17071997/intern_assessment | /main.py | 931 | 3.609375 | 4 | """
to create simple api in flask framework
"""
import re
from flask import Flask
from flask_restful import Api, Resource, reqparse, request
APP = Flask(__name__)
API = Api(APP)
class Sanitize(Resource):
""" to create rest api for http post """
request_parser = reqparse.RequestParser()
def check_for_sql... |
4a3368612d71c0d50ea714669551caf6922696ba | Sakshipandey891/sakpan | /vote.py | 285 | 4.3125 | 4 | #to take age as input & print whether you are eligible or not to vote?
age = int(input("enter the age:"))
if age==18:
print("you are eligible for voting")
elif age>=18:
print("you are eligible for voting")
else:
print("you are not eligible for voting")
|
d31784ca65ceec68e77a589810f40b3248edbef9 | Jack-Rutland/WorkoutStats | /src/workout.py | 698 | 3.515625 | 4 | class Lift :
def __init__(self,name='UNNAMED',sets=3,reps=8) :
self.name = name
self.sets = sets
self.reps = reps
def __str__(self) :
return self.name
class Workout :
def __init__(self,name="UNNAMED") :
self.name = name
self.lift_list = []
... |
d4fc59edb7222118899818e3a6bfb3e84d57797e | MikhaelMIEM/NC_Devops_school | /seminar1/1.py | 574 | 4.21875 | 4 | def reverse_int(value):
reversed_int = 0
while value:
reversed_int = reversed_int*10 + value%10
value = value // 10
return reversed_int
def is_palindrome(value):
if value == reverse_int(value) and value%10 != 0:
return 'Yes'
else:
return 'No'
if __name__ == '__main_... |
92060e729aa35effa96fd47f4d4e1bdd9f2dcc7b | micahweston/FinalProjectCS499 | /FinalProjectCS499/script.py | 3,029 | 3.84375 | 4 | # Stephen Weston
# 11/1/2020
# User Management System
# import additional files
from login import Login
from customer import Customer
import pandas as pd
# import databases, and database connections
import sqlite3
conn = sqlite3.connect("user_management.db")
cursor = conn.cursor()
# Welcome screen
def welcome():
... |
24531c8b64bd5e1cd2e6dc939a4df4960f07ccd6 | susanooxd/curso-de-python | /exercicio11.py | 530 | 4.09375 | 4 | #========= Desafio 11 ============
#Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessário para pintá-la, sabendo que cada litro de tinta, pinta uma áre de 2m quadrados
altura = float (input('Informe a altura da parede em Metros: '))
largura = ... |
eeeecde75470e4d59fb9c5e732e272e330080aad | susanooxd/curso-de-python | /exercicio018.py | 364 | 3.96875 | 4 | #
# ======== Desafio 018 =========
#Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo
import math
angulo = int(input('Informe o ângulo: '))
print('O seno é {:.2f}, o cosseno é {:.2f}, e a tangente é {:.2f}, do angulo{}'.format(math.sin(angulo),math.cos... |
a7a491545a756348fd6665eba1e774e7080da475 | hfoley03/weather-app | /main.py | 4,168 | 3.5 | 4 | from flask import Flask
from flask import request
import requests
import geopy
from geopy.geocoders import Nominatim
app = Flask(__name__) #creat instance of Flask
@app.route("/") #python decorator wraps code below to url endpoint
def index():
location = request.args.get("location", "") #fetch lo... |
b578ed9ea162a40f7e72f5d9d84239e179921fdf | ederst/exercism-python | /high-scores/high_scores.py | 433 | 3.671875 | 4 | def latest(scores: list[int]) -> int:
return scores[-1]
def personal_best(scores: list[int]) -> int:
return max(scores)
def personal_top_three(scores: list[int]) -> list[int]:
return sorted(scores, reverse=True)[:3]
def personal_top_three_slice_magic(scores: list[int]) -> list[int]:
"""
This u... |
9bc67c03d554778d6eee4364b1c7d52bb7bfe2f4 | ederst/exercism-python | /pangram/honorable_mentions/pangram_3.py | 225 | 3.546875 | 4 | from string import ascii_lowercase
# source: https://exercism.io/tracks/python/exercises/pangram/solutions/4b7a98e2e756491c9577debae86ac305
def is_pangram(sentence):
return set(sentence.lower()) >= set(ascii_lowercase)
|
0a13ab36d5d53e333a5c35aeb4367ec2d1e2df18 | ederst/exercism-python | /allergies/allergies.py | 2,979 | 3.96875 | 4 | from typing import List
class Allergies:
_allergens: List[str] = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats",
]
def __init__(self, score: int):
self._score: int = score
def allerg... |
948365b1b94b1c7f8cf825019b3f696787a40d91 | hitanshkadakia/snakegame | /Snake.py | 5,790 | 3.875 | 4 | import tkinter as tk
import random
SNAKE_COLOR, FOOD_COLOR= "light green", "red"
BG_COLOR, TEXT_COLOR = "black", "white"
WIDTH = 40
FOOD_WIDTH = WIDTH * 3 / 4
SPEED = 100
CUSHION = 1
SCREEN = WIDTH * 30, WIDTH * 17
FONT = "ms 70"
MAX_T = 1000 // SPEED * 5
FOOD_PROB = 0.04
CONTROLS = LEFT, RIGHT, UP, DOWN = "Left"... |
50e4910a3b33259d110e2147dfc73c6ef99f09da | JakeGeiser/python-challenge | /PyBank/main.py | 1,631 | 3.921875 | 4 | # import modules
import os
import csv
# Get file path
csvpath = os.path.join("Resources","budget_data.csv")
# Open csv file
with open(csvpath) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Read the header row first
csv_... |
fafb1b93badd783b13e36fbe62b1be499ea83bf5 | ashwani99/ds-algo-python | /graph/traversal.py | 1,567 | 3.90625 | 4 | from graph import UndirectedGraph
from collections import deque
def bfs(graph, start_node):
visited = [start_node]
print('Visited', start_node)
q = deque([start_node])
while q:
popped_node = q.popleft()
for node in g.adjacents(popped_node):
if node not in visited:
... |
b4b5b23dff3ef54135b31a52c397ab7bb347c298 | ashwani99/ds-algo-python | /sorting/merge_sort.py | 1,092 | 4.34375 | 4 | def merge_sort(arr):
l = len(arr)
return _merge_sort(arr, 0, l-1)
def _merge_sort(arr, start, end):
if start < end:
mid = (start+end)//2
_merge_sort(arr, start, mid)
_merge_sort(arr, mid+1, end)
merge(arr, start, mid, end)
return arr
def merge(arr, start, mid, end):
... |
8839d7b99405de758cab6ca4c4bd04718891c34c | ashwani99/ds-algo-python | /sorting/mergesort_inplace.py | 872 | 4.125 | 4 | def merge_sort(arr):
n = len(arr)
return _merge_sort(arr, 0, n-1)
def _merge_sort(arr, start, end):
if start < end:
mid = (start+end)//2
_merge_sort(arr, start, mid)
_merge_sort(arr, mid+1, end)
_merge(arr, start, mid, end)
return arr
def _merge(arr, start, mid, end):... |
3c870fb9966a02a8ab8769189be7e6ba11b3720d | antonkrupin/algorithms | /recursion/findMaxSecondNumber.py | 823 | 3.859375 | 4 | def findSecondMaxNumber(numbers):
if len(numbers) >= 2:
numbers.sort()
max1 = numbers[0]
max2 = numbers[0]
def recursion(max1, max2):
if numbers != []:
if numbers[0] > max1:
test = max1
max1... |
f724869edc4865b9bd987772e70d8284cd7df888 | antonkrupin/algorithms | /algorithms_part1/orderedList/orderedList.py | 4,330 | 3.8125 | 4 | class Node:
def __init__(self, v):
self.value = v
self.prev = None
self.next = None
class OrderedList:
def __init__(self, asc):
self.head = None
self.tail = None
self.__ascending = asc
def compare(self, v1, v2):
if v1 > v2:
... |
c95e8598bce52f7d85d4d9b00265b111b20d6d20 | antonkrupin/algorithms | /algorithms_part1/deque/deque.py | 745 | 3.59375 | 4 | class Deque:
def __init__(self):
self.deque = []
def addFront(self, item):
appendEl = [item]
self.deque = appendEl + self.deque
def addTail(self, item):
appendEl = [item]
self.deque = self.deque + appendEl
def removeFront(self):
if len(self... |
5a0ffdc8363e3d2107b8b420f51035457c5a758e | antonkrupin/algorithms | /28_tasks/SynchronizingTables.py | 781 | 3.53125 | 4 | def SynchronizingTables(n,ids,salary):
nonSortedIds = []
for x in range(len(ids)):
nonSortedIds.append(ids[x])
sortedIds = []
sortedSalary = []
rightSalary = []
dict = {}
def bubble(array):
N = len(array)
for i in range(N-1):
for j in range(N-i-1... |
7024125f920382245e33eae4f71d857d6b3f24b7 | shensleymit/HapticGlove | /Haptic Feedback Code/RunMe2.py | 1,725 | 4.375 | 4 | #################################################
# This asks the user which function they would #
# like to see, and loads that one. Ideally, #
# this won't be needed, and instead the choice #
# of function and the function will all be part #
# of one file. #
####################... |
9764177ff2480ac73c7bfbb95926f85f1dd9fbb3 | jscsegura/Lab9 | /Labo9.py | 4,256 | 3.578125 | 4 | # class Contador():
# rebase = int(0)
# def __init__(self, c, m):
# self.c = c
# self.m = m
# def getCuenta(self):
# return self.c
# def getMax(self):
# return self.m
# def getRebase(self):
# return rebase
# def setCuenta(self, c):
# self.c = int(c)
# def setMax(self,m):
# self.m - int (m)
... |
fbd4aceb46dd774c6fbd3bf508a2bee00b27a35b | mttmartin/herd_immunity_simulator | /herd_immunity_simulator.py | 6,293 | 3.84375 | 4 | #!/usr/bin/env python3
# A very simple epidemic simulation
import random
import matplotlib.pyplot as plt
class World:
def __init__(self):
self.world_size=20
self.people = list()
self.population=0
self.immune_num=0
self.infected_num=0
def add_person(self,person):
... |
7a77161690f3f6a5fb050ea374c1ac1b94ace6a2 | thiklock/bootcamp_carrefour | /desenvolvimentodeferramentasparte1/ch.py | 448 | 3.625 | 4 | import hashlib
file1 = 'a.txt'
file2 = 'b.txt'
hash1 = hashlib.new('ripemd160')
hash1.update(open(file1, 'rb').read())
hash2 = hashlib.new('ripemd160')
hash2.update(open(file2, 'rb').read())
print(f' Hash value of {file1} is:', hash1.hexdigest())
print(f' Hash value of {file2} is:', hash2.hexdigest())
if hash1.d... |
b0dbc6e3dff7c9ad1ef878859082522567b8f8fa | B3r4ti0n/repo_py | /main.py | 1,539 | 3.765625 | 4 |
répertoire={
}
a = False
def create_contact(name, nbPhone, fav2):
contact1={
"name": name,
"nbPhone": nbPhone,
"fav": fav2,
}
return contact1
def add_contact(contact1):
name = contact1["name"]
répertoire[ name ] = contact1
return répertoire
boucle1 = False
def get... |
51b9a231cd167cf0a1db1ad6dd468f339a471bbd | mrwsy1/sudoku | /main.py | 784 | 3.71875 | 4 | import backtrack
sample = [
[2,5,6,4,0,3,0,9,1],
[0,0,0,0,0,6,0,0,5],
[3,4,0,8,0,0,0,2,0],
[4,2,0,5,0,8,0,1,3],
[0,0,5,0,0,0,6,0,7],
[6,8,0,1,0,0,0,0,4],
[5,0,8,7,3,0,0,6,0],
[1,0,0,6,8,0,0,0,9],
[0,0,0,2,1,0,0,3,0]]
def print_grid(sample):
for i in range(9):
if i%3==0 ... |
37af5a4c59de2b4bcbb817db147ce79e52cb72c5 | sanketpanasuriya/Python-CRUD-operation | /Database.py | 5,123 | 4.0625 | 4 | import sqlite3
class Queries:
con = ""
cursor = ""
def __init__(self):
try:
self.con = sqlite3.connect('Employee.db')
self.cursor = self.con.cursor()
self.cursor.execute('''CREATE TABLE IF NOT EXISTS employee(
ID INTEGER,
emp_no TEX... |
222b1c7a41018ac6c3a230a3aee9bfca05690ba4 | betsybaileyy/Core_Data_Structures | /Code/word_jumble_final.py | 1,844 | 4.0625 | 4 |
# getting the computer's default dictionary and
def get_file_lines(filename='/usr/share/dict/words'):
"""Return a set from the given text file with
any leading and trailing whitespace characters removed from each line."""
# Open file and remove whitespace from each line
with open(filename) as file:
... |
5facb5b17b207e55e60d7ff85c301891de7b46c2 | hstringfield5455/Project-Euler | /Euler 3.py | 515 | 3.96875 | 4 | # Euler Third Problem
# Holden Stringfield
# This returns the largest prim factor of a number
def main():
num = int(input("What is the number? "))
comp(num)
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def comp(num):
if isPrime(num) == ... |
bbf839f1f419d100d89b6061d699eaed3a3f95bd | wangrongming/pythonBase | /AcknowledgePoints/Demo0base/图像识别与文字处理.py | 776 | 3.796875 | 4 | 图像识别与文字处理
OCR:光学文字识别
Pillow
from PIL import Image,ImageFilter
kitten = Image.open("G:\\Pincure\\sdfx.png")
blurryKitten = kitten.filter(ImageFilter.GaussianBlur)
blurryKitten.save("G:\\Pincure\\kitten_blurred.jpg")
blurryKitten.show()
Tesseract
一个OCR库
下载地址:https://code/google.com/p/tesseract-ocr/downloads/list
#linux... |
970f3b7fb2b282018e3a14013c97825d446e781a | aaronbushell1984/Python | /Day 1/Day 1 Exercises.py | 5,368 | 4.5625 | 5 | import math
# 2. Write a Python program that prints (displays) your name, address, and telephone number.
# 3. Evaluate the following code at a shell prompt:
#Then assign name an appropriate value, and evaluate the statement again. -COMBINED ANSWER
name = input('enter your name: ')
address = input('enter your address: ... |
fea8cb352c69934a5d9af8ff0b41f0bd7502ddc2 | aaronbushell1984/Python | /Day 2/Loops.py | 3,480 | 4.34375 | 4 | # ***LESSON***
# Create a list syntax - any data type
numbers = [1,2,9,4,33,6]
# Set variable total to zero, loop and add running total to number
# NB. Python uses indents to start and end blocks (not brackets)
# NB. Variables are available outside of loop unlike other languages
total = 0
for number in numbers:
t... |
9d272a9c8c1733568d01335040bc94a3bec2eb1c | aaronbushell1984/Python | /Day 1/Inputs.py | 1,596 | 4.3125 | 4 | # Python has Input, Output and Error Streams
# Python executes code sequentially - Line by Line
# Python style guide https://www.python.org/dev/peps/pep-0008/
# Add items to input stream with input - Print variable to output stream
name = input('enter your name: ')
print("Your name is", name)
# Input takes input and ... |
68de2543505d545b4829aa7637ceb6d8fb7f89a7 | aaronbushell1984/Python | /Day 4/q2-test.py | 4,736 | 3.71875 | 4 | """
##### #####
# # # # ###### #### ##### # #### # # # #
# # # # # # # # # # ## # #
# # # # ##### #### # # # # # # # #####
# # # # # # # # # # # # # # # ... |
9c0b81361905459031d7c14ba81184265affe5d8 | aaronbushell1984/Python | /Day 4/q3-test.py | 5,837 | 3.6875 | 4 | """
##### #####
# # # # ###### #### ##### # #### # # # #
# # # # # # # # # # ## # #
# # # # ##### #### # # # # # # # #####
# # # # # # # # # # # # # # ... |
8453721e40f2b002907b3c926bc82711f92b8dea | mingkzhou/Python-Core-Application | /itcast/threading/02-thread.py | 682 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@author by mkzhou
@time 2020/6/14 13:59
"""
import threading
import time
def sing():
for i in range(3):
print('正在唱歌{}'.format(i))
time.sleep(1)
def dance():
for i in range(3):
print('正在跳舞{}\n'.format(i))
time.sleep(1)
if __name__ == '__main__':
... |
aa37ea447af7b87f183166a5c55f6313f2a24524 | YahyaQandel/CodeforcesProblems | /Gravity_Flip.py | 323 | 3.625 | 4 | cols = input()
row = []
numberOfCubesPerCol = input()
cubesList = numberOfCubesPerCol.split(' ')
cubesList = list(map(int, cubesList))
cubesList.sort(key=int)
cubesString = ""
counter=0
for i in cubesList:
cubesString+=str(i)
counter+=1
if counter < len(cubesList):
cubesString+=" "
print(cubesStri... |
103c83238f652ffd3575c52f14835ab683d321f7 | YahyaQandel/CodeforcesProblems | /datastructure/src/BubbleSort.py | 429 | 3.9375 | 4 | class BubbleSort:
data = [5, 4, 3, 2, 1]
def __init__(self, data):
self.data = data
def sort(self):
for i in range(len(self.data) - 1):
for j in range(len(self.data) - 1 - i):
if self.data[j] > self.data[j + 1]:
self.swap(j, j + 1)
def s... |
8df411f4ac5c713cab242a1f1a152c2db3f64b68 | kwag93/Py_Algorism | /chap5/5-1.py | 334 | 3.9375 | 4 | # stack 기초
stack = []
# python에는 이를 지원하는 라이브러리가 따로없음
# 리스트가 스택과 같이 작동
# append 와 pop 을 사용해보자
stack.append(5)
stack.append(2)
stack.append(3)
stack.pop()
stack.append(1)
stack.pop()
print(stack)
# 5 2
print(stack[::-1])
# 2 5 최상단부터 출력해줌
|
932b8fa027f22a35e3fd311388ee39bf9a55dd20 | leo-ware/logical-python-pilot | /package/variable.py | 5,138 | 3.8125 | 4 | from package import Logical
class Variable(Logical):
"""Class for representing package variables
Args:
value (any, optional): initializes the variable with this value --- not recommended, you
should probably use Constant for this
Attributes:
bound (bool): whether the variable is b... |
48d4a7a9dbc3f6f9fd6b05fcd0a667baf7f23eef | FuYuanDe/Follow-up-of-MyPython | /py-code/final-exam/3.py | 967 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/24 10:31
# @Author : Chen Shan
# Function :
from pandas import Series,DataFrame
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
csv_file = "3.csv"
csv_data = pd.read_csv(csv_file,engine='python')
csv_df = DataFrame(csv... |
62488f64145148750b61eb343253a16b050c0b0a | FuYuanDe/Follow-up-of-MyPython | /py-code/final-exam/2.py | 535 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/24 10:31
# @Author : Chen Shan
# Function :
class rangeError(Exception):
pass
while True:
a = int(input("请输入一个整数(a):"))
b = int(input("请输入一个整数(b):"))
try:
a = int(a)
b = int(b)
if b == 0:
... |
c64b9f300bfa7b4cd418ed2553f412cf4513d664 | sofiassr97/proyectos-py | /Problem2_Week1.py | 485 | 3.90625 | 4 | '''
Problem 2
10.0/10.0 points (graded)
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
'''
s = 'azcbobobegghakl'
count = 0
for char in range(0, len(s)-2):
... |
3f9216d1c66025fe10d0b40619a033932bc6afd9 | bolducp/MIT-6.00SC-OpenCourseWare-Solutions | /Set 6/ps6.py | 12,817 | 3.9375 | 4 | # Problem Set 6: Simulating robots
import math
import random
import ps6_visualize
import pylab
# === Provided classes
class Position(object):
"""
A Position represents a location in a two-dimensional room.
"""
def __init__(self, x, y):
"""
Initializes a position with coordinates (x, ... |
e24d82a2699dd90ef9551b67975fad2f77bd84a1 | bolducp/MIT-6.00SC-OpenCourseWare-Solutions | /Set 1/problem_2.py | 1,235 | 4.15625 | 4 | # Problem Set 1, Problem 2: Paying Off Debt in a Year
def get_outstanding_balance():
outstanding_balance = round(float(raw_input("Enter the outstanding balance on the credit card: ")), 2)
return outstanding_balance
def get_annual_interest_rate():
annual_interest_rate = round(float(raw_input("Enter the a... |
007e31e0b3b0b3da203ab7e858c0a437ed69e78e | rociof/community-starter-kit | /s6red.py | 5,252 | 3.625 | 4 | #El módulo 'os' nos permitirá consultar si un archivo existe.
import os
def mostrar_bienvenida():
print("Bienvenido a ... ")
print("""
_ __
____ ___ (_) ________ ____/ /
/ __ `__ \/ / / ___/ _ \/ __ /
/ / / / / / / / / / __/ /_/ /
/_/ /_/ /_/_/... |
1564137dce26a1cb9dfdeab8552a7246d5ee491a | keerthiballa/PyPart5 | /palindrome.py | 447 | 4.34375 | 4 | def is_palindrome(value: str) -> bool:
"""
This function determines if a word or phrase is a palindrome
:param value: A string
:return: A boolean
"""
return value.replace(" ", "").lower() == value[::-1].replace(" ","").lower()
# ballakeerthi@zipcodes-MacBook-Pro-3 PyPart5 % python3 -m unittes... |
e40491485806248d115ec33a11eceb09de302c32 | gabrielratao/curso_python | /Códigos Curso/04 condições/temperatura_agradavel.py | 883 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 19:41:19 2021
Criar um programa que le, nome, n habitantes, temperatura e chuva
de uma cidade. E armazenar tudo em um dicionario
Mostrar qual foi a temperatura registrada
se a temperatura for maior que 32° ta calor, se tiver entre 25 e 32
ta agradavel e se tiv... |
345bb34d6071af1bce409e61f803b5f6c1763761 | yangzhiyu/learn-python | /test1-1.py | 264 | 3.640625 | 4 | #-*- coding:utf-8 -*-
#file: quadratic.py
import math
a, b, c = input(“请输入3个系数a,b,c: ”)
discRoot = math.sqrt(b*b – 4*a*c)
x1 = (-b + discRoot) / (2 * a)
x2 = (-b – discRoot) / (2 * a)
print “第1个解x1=”, x1
print “第2个解x1=”, x2
|
18b02c409cd1a5eb76dfdb646f8a55ef8cb5b6b3 | cs144caltech/pandemaniac | /pandemaniac-modelism/models/most_common_colored.py | 937 | 3.5 | 4 | from collections import Counter
from model import Model
class MostCommonColored(Model):
"""
Class: MostCommonColored
------------------------
A node takes on the color that is the most common among its neighbors..
"""
def update(self, node_color, node):
neighbors = self.adj_list[node]
colored_neig... |
a9043ab0af0c7565464d084ee5282d41d88b43c0 | DirtNap/trivialserver | /fizz_engine.py | 2,844 | 3.890625 | 4 | """A class to produce FizzBuzz-like results."""
import gmpy2
_ENGINE_CACHE = {}
def fizz_factory(max_size=64):
"""Create and cache a FizzEngine.
Arguments:
max_size: As per FizzEngine(max_size)
Returns:
A configured FizzEngine. For any given max_size, only one FizzEngine
will be crea... |
5e9124c0f984d3611095ed161d824a0373dc4f41 | acarlson99/advent-of-code | /2019/01/solve.py | 351 | 3.78125 | 4 | #!/usr/bin/env python3
import fileinput
def findReal(n):
extraFuel = int(n / 3) - 2
if extraFuel <= 0:
return (n)
return (n + findReal(extraFuel))
totalA = 0
totalB = 0
for line in fileinput.input():
n = int(int(line) / 3) - 2
totalA += n
totalB += findReal(n)
print("Part one:", tota... |
12cd0d6eb1f99ba577ea570c54061852190e135a | mattdinhnguyen/algos | /rope.py | 1,969 | 4.03125 | 4 | # a) Each node when it enters has its "value" (Number of people greater in height) as its initial value. I am calling it the "current node" (till it reaches its final position).
# b) A "current node" goes "left" to the existing node, when its value is <= the existing node's value. At that time it increments the existin... |
84c6467c862c40d21c4a6b491bbce13776d3714e | mattdinhnguyen/algos | /addLinkedList.py | 2,669 | 3.625 | 4 | from insertNodeLinkedList import _reverseList as reverse_list
class Node:
def __init__(self, value):
self.value = value
self.next = None
def gen_list(num):
last = Node(num[0])
start = last
for digit in num[1:]:
node = Node(digit)
last.next = node
last = node
... |
1e44fa180216755f5be642905e75ad6b82a664e2 | mattdinhnguyen/algos | /bestFirstSearchDP.py | 2,440 | 3.53125 | 4 | from heapq import heappop, heappush
# https://www.teamblind.com/post/Who-can-leetcode-hard-q1vFGBam
# you are given an integer N, and a permutation, P of the integers from 1 to N, denoted as (a_1, a_2, ..., a_N).
# You want to rearrange the elements of the permutation into increasing order, repeatedly making the follow... |
d9f63f993a7c1e667f252422e3b729e89de5a332 | mattdinhnguyen/algos | /isBST.py | 1,134 | 3.546875 | 4 | #!/usr/local/bin/python
import random
random.seed(0)
lst = [0]
lst += [random.randint(1, 10) for _ in range(10)]
print(lst)
def parent(n):
return (n-1)//2
def lchild(n):
return 2*n+1
def rchild(n):
return 2*n+2
def lchildV(l, n): # left child value
return l[lchild(n)]
def rchildV(l, n):
return l[rch... |
279341793e965867098d334d51c1354074f26194 | mattdinhnguyen/algos | /aboveAvg.py | 1,955 | 3.984375 | 4 | # You are given an array A containing N integers.
# Your task is to find all subarrays whose average sum is greater than the average sum of the remaining array elements.
# You must return the start and end index of each subarray in sorted order.
# A subarray that starts at position L1 and ends at position R1 comes befo... |
7bebabb724173757ed3185d640790f867db12c32 | suvarna03/python_project | /Book.py | 1,223 | 3.6875 | 4 | from BookItem import BookItem
class Book:
itemList = []
def __init__(self, name, author, publish_date, pages):
self.name = name
self.author = author
self.publish_date = publish_date
self.pages = pages
self.total_count = 0
self.book_item = []
... |
93fb4f4dab9e74fa1da1499eaa5f874cb2710e15 | danielblignaut/movie-trailer-application | /media.py | 1,185 | 4.15625 | 4 | class Movie() :
""" This class provides a way to store movie related data """
VALID_RESTRICTIONS = ["G", "PG", "PG-13", "R"]
def __init__(self, title, storyline, image_poster, youtube_trailer, rating, restriction) :
self.title = title
self.storyline = storyline
self.image_p... |
f82ce61ec72fcdcc3fd6caaa3f921bc371e2e7c1 | emilylu123/pythonProjects | /basic.py | 1,907 | 3.921875 | 4 | print('Python:')
print('hello world')
# do not change new line
print('Python:', 'Hello', 'World')
# write to document
''' multiple line comments or ' * 3 or " * 3
fp = open('./output.txt', 'a+')
print('Multiple','Line', 'Commets', '!', file=fp)
fp.close()
'''
# escape character \ 转义字符 -> \n \r \t \b \\ \' \"
prin... |
a19a846b151903f2569a575fae5844d60f4c26d2 | ProgFuncionalReactivaoct19-feb20/clase04-SantiagoDGarcia | /ejercicio4.py | 247 | 3.625 | 4 | """
Ejercicios clase04
@SantiagoDGarcia
"""
paraleloA = [(19, 10, 20), (20, 20, 10), (20, 10, 9)]
nombres = ["Ángel", "José", "Ana"]
prom = lambda x: (x[0]+ x[1]+ x[2])/3
prom2 = list(map(prom, paraleloA))
print(list(zip(prom2,nombres)))
|
2134dde3da45d97bed30599df119beb184f15eaa | kwahome/python-escapade | /fun-with-problems/in_place_string_reverse.py | 1,685 | 4.3125 | 4 | # -*- coding: utf-8 -*-
#============================================================================================================================================
#
# Author: Kelvin Wahome
# Title: Reversing a string in-place
# Project: python-escapade
# Package: fun-with-problems
#
#
# Write a function to reverse ... |
e6d862918789ec834318bd3878e292a99dea8777 | kwahome/python-escapade | /balanced-brackets/improved_balanced_brackets.py | 3,438 | 3.765625 | 4 | # -*- coding: utf-8 -*-
#============================================================================================================================================
#
# Author: Kelvin Wahome
# Title: Balanced Brackets Search
# Project: python-escapade
# Package: balanced-brackets
#
# This is a simple program to check... |
4d0abce8ba9fe0926b4f51472fbdc1ea64d5af88 | kwahome/python-escapade | /fun-with-problems/two_eggs_problem.py | 2,502 | 3.921875 | 4 | # -*- coding: utf-8 -*-
#============================================================================================================================================
#
# Author: Kelvin Wahome
# Title: Two eggs problem
# Project: python-escapade
# Package: fun-with-problems
#
#
# A building has 100 floors. One of the f... |
37fbd89015c920e3aeed4129586daeaabf538f7d | vm-raccoon/python-currency-banks | /classes/Database.py | 3,091 | 3.71875 | 4 | import os
import sqlite3
from datetime import datetime
class Database:
def __init__(self, filename):
self.__filename = filename + ".sqlite3"
self.__createFile()
def __createFile(self):
connection = None
try:
connection = sqlite3.connect(self.__filename)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.