blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
481628c29a53882704da635acaf8adbf86463f8c | codehakase/python-sandbox-commits | /oop/Account.py | 989 | 3.5 | 4 | class Account(object):
counter = 0 # will track how many instances of this class.
def __init__(self, holder, number, balance, credit_line = 1500):
Account.counter += 1
self.__Holder = holder
self.__Number = number
self.__Balance = balance
self.__CreditLine = credit_line
... |
fddc640671b7170ca632c5917d6d6f27f4f73400 | moonclearner/leetcode | /136.SingleNumber.py | 755 | 3.828125 | 4 | '''
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
from collections import Counter
class Solution(object):
def singleNumber(self, nums):
"""
... |
b2ed0c8d21f9bb7a157068ad247ffc0b4764a5a6 | moonclearner/leetcode | /Array/121.BestTimeToBuyAndSellStock.py | 1,486 | 4.125 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
4 + -2 + 3 =5
Output: 5
max. d... |
1bbbcd4b5a434a14901e9eb86a151b3b72440a7b | moonclearner/leetcode | /561.ArrayPartition.py | 826 | 3.796875 | 4 | '''
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.
Note:
n is a p... |
c89bfe328afc22248336befcb69bf72cca84d5c5 | Sibeit/Python | /index/202003011257.py | 1,096 | 3.625 | 4 | class MyDate:
__m = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def __init__(self):
self.__year = 0
self.__month = 0
self.__day = 0
def setYear(self, y):
self.__year = y
def getYear(self):
return self.__year
def setMonth(self, m):
if 1 <= ... |
224fddf07ea7718a9da835735e57e9ef58349b75 | nate-h/Whirling | /whirling/tools/code_timer.py | 1,049 | 3.8125 | 4 | """Code Timer
This class is capable of timing code as a context manager or decorator.
For example:
with CodeTimer():
for i in range(100000):
pass
with CodeTimer('loop 1'):
for i in range(100000):
pass
@CodeTimer(name='test')
def decoratedFn():
for i in range(100000):
pass
decoratedFn()
"""
impo... |
1c8a46387715c7d4958d42732f2ae55b80a1fc68 | fzubowicz/pull_classes | /podstawy/zadanie10 działania.py | 496 | 3.5625 | 4 | liczba1 = float(input('podaj pierwszą liczbę: '))
liczba2 = float(input('podaj drugą liczbę: '))
operacja = input('podaj operację [+-*/]: ')
if operacja == '+':
wynik = liczba1 + liczba2
elif operacja == '-':
wynik = liczba1 - liczba2
elif operacja == '*':
wynik = liczba1 * liczba2
elif operacja == '/':
... |
0f5d489075db432e0a93dd23cd7d3dcffb41926d | fzubowicz/pull_classes | /podstawy/zadanie12 petla while.py | 342 | 3.6875 | 4 | # przygotowane danych przed pętlą
# jak długo pętla ma się wykonywać, kiedy ma się skończyć (nagłówek pętli)
# co pętla ma faktycznie robić (ciało petli)
a = 1 # przygotowanie
while a <= 100: # warunek końca (nagłówek)
print(a**2) # ciało pętli
a += 1 # zmiana zmiennej sterującej
print('po petli')
... |
5268ddefed3616fb14e72de5fc4bf299f8cb1b54 | Jwely/neural_network | /cortex_class.py | 28,390 | 3.765625 | 4 | from random import random, randint, sample, randrange
import numpy
from neuron_class import neuron
import sys
__author__ = "Jeffry Ely, jeff.ely.08@gmal.com"
class cortex:
"""
A cortex is a collection of neurons, a neural network in and of itself
A cortex behaves a lot like a single neuron. One key diff... |
a3ae6a972b931f5a3b03908a8c507a2f24c72239 | suneelkumar-h/practicaldatascience.github.io | /tutorial_final/288/MRtutorial/WordCountReducer2.py | 621 | 3.5 | 4 | #!/usr/bin/env python
import sys
curr_word = None
curr_count = 0
word_count_dict = {}
# input comes from STDIN
for line in sys.stdin:
line = line.strip()
word, count = line.split('\t', 1)
try:
count = int(count)
except ValueError:
continue
if not curr_word:
curr_word = word... |
af1b8e2852c77f76824b26ab587cd1361ad1bcd3 | byasoares/provan1 | /numero5.py | 404 | 3.90625 | 4 | listamensagem = []
numero = []
numero = 0 = " "
listamensagem.append(numero)
1 = "a"
2 = "b"
3 = "c"
4 = "d"
5 = "e"
6 = "f"
7 = "g"
8 = "h"
9 = "i"
10 = "j"
11 = "k"
12 = "l"
13 = "m"
14 = "n"
15 = "o"
16 = "p"
17 = "q"
18 = "r"
19 = "s"
20 = "t"
21 = "u"
22 = "v"
23 = "w"
24 = "x"
25 = "y"
26 = "z"
def traduzir(... |
f247158558bc0252d924dc5d5fbf9d191795c59a | hofernandes/python3-mundo-1 | /ex017.py | 602 | 4.09375 | 4 | # Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e mostre o comprimento da hipotenusa.
# import math
from math import hypot
catop=float(input('Digite o valor do cateto oposto: '))
catad=float(input('Digite o valor do cateto adjacente: '))
print(f'O valo... |
cf1582fa15460fe7fc4fa8356befe3a74985255b | hofernandes/python3-mundo-1 | /ex018.py | 668 | 4.1875 | 4 | # Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
# import math
from math import (radians,sin,cos,tan)
angulo=float(input('Digite o Angulo que deseja calcular: '))
#print(f'O valor de seno de {angulo} é {math.sin(math.radians(angulo)):.2f} \nO valor do cos... |
497f8c3dece5ce12670db8ef04cb7b91257dc292 | kushagra4/Artificial-Intelligence-agent | /assign2/minimax.py | 9,543 | 3.609375 | 4 | #gets a successors of the board
from watchYourBack import Board
from watchYourBack import Game
from evaluationFunctions import Evaluation
import math
import copy
################################################################################
# countMoves calculates all the possible moves a single piece can make an... |
6083f4badfd557fcb739ad4a31f0efe4eb099895 | ikkebr/oldstuff | /ps.py | 615 | 3.828125 | 4 | from itertools import *
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
lista = [1,2,3,4,5,6,7,8,9,10]
a = set(lista)
x = list(powerset(a))
print list(x)
y = [sum(k) fo... |
f56f46eb3fb43be521eaf04a524a4385e97189a3 | pakpake/licence-informatique | /2nd-year/structures-de-donnees-algos-python/tp1/.ipynb_checkpoints/tp1-checkpoint.py | 1,221 | 3.890625 | 4 | # -*- coding: utf-8 -*-
""" Exercice 1 """
# Création tableau et multiplication de ses valeurs
#def double_tab(t):
# t = [i*2 for i in t]
# print(t)
def double_tab(t):
for i in range(len(t)):
t[i]=2*t[i]
return t
tab = [1, 2, 3]
result = double_tab(tab)
print(result)
# 2)
def t1():
t = [... |
e0ab7bdd1454650933bdb381226eec67baa77989 | pakpake/licence-informatique | /2nd-year/structures-de-donnees-algos-python/tp4/tp4-exo2.py | 3,766 | 3.75 | 4 | """ Exercice 2 """
from math import *
class Complex(object):
""" Create Complex class"""
def __init__(self, n1, n2, b):
#Create complex number either in cartesian or polar notaion
self.bcart = b
if self.bcart:
self.real = n1
self.imag = n2
else:
... |
1520c54e0e18696c00552eddff50fb957058741b | pakpake/licence-informatique | /2nd-year/structures-de-donnees-algos-python/tp5/tp5-specification.py | 1,713 | 3.875 | 4 | class Liste:
def __init__(self):
"""
:sortie : self
:post-cond: self est une liste vide
"""
def est_liste_vide(self):
"""
:entree : self
:sortie v: bool
:renvoie True si et seulement si self est vide
"""
def tete(self):
"""
... |
ba7d654bc56122ac17c8a0af0384923292be9014 | JakeCordelli/favoriteMovies | /prototype0/sqlDB.py | 941 | 4.34375 | 4 | import sqlite3
connection = sqlite3.connect("movies.db")
cursor = connection.cursor()
# delete
#cursor.execute("""DROP TABLE movies;""")
'''
sql_command = """
CREATE TABLE movies (
movie_number INTEGER PRIMARY KEY,
mtitle VARCHAR(20),
rating DOUBLE(2),
seen INTEGER(2));"""
cursor.execute(sql_com... |
1120d23339173f2dcd2bd1cedb13678581f1a583 | mangosmoothie/python_starter | /cli/main.py | 436 | 4.125 | 4 | import sys
from generators import get_date, get_numbers
options = """
Please select an option:
1 - get current date
2 - get a list of numbers
3 - exit program
"""
if __name__ == '__main__':
option = ""
while(option != "3"):
option = input(options)
if option == "1":
print(get_date... |
f6ee5ecf4835af41b1d4ee1e40faf744b8c2f131 | Pradeep-Panchariya/Hackerrank_Solutions | /Python_IfElse.py | 706 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 18 19:09:43 2019
@author: marjan
"""
import math
import os
import random
import re
import sys
def n_weird_or_notweird(n):
"""
This function gets n and return a string based on its value
in: n is a positive integer within [1, 100] range
out: a message as ... |
d54d1e32e88be04ab33b404ef28159b4d4aa9906 | cBridges851/colour-palette | /src/tkinter_version/interface_updater.py | 3,767 | 3.6875 | 4 | from colour_converter import ColourConverter
class InterfaceUpdater:
"""
The class that is responsible for updating the UI
"""
def update_colour_box(self, colour_box, colours):
"""
The method that updates the box which displays the inputted colour
Args:
... |
6040d02eeb817d8dce66c1dc393df2ce3ce42b9d | hanu1234/Daily_Update | /TIMING_MODULE/utc_time_ex1.py | 810 | 3.6875 | 4 | import datetime
from time import sleep
utc_time = datetime.datetime.utcnow()
print(utc_time)
# Get UTC TIME After 15 Minutes
utc_time = utc_time + datetime.timedelta(minutes=10)
print(utc_time)
hours = utc_time.strftime("%H")
minutes = utc_time.strftime("%M")
print(hours, minutes)
utc_time = utc_time + datetime.timed... |
41909db5b84b2fe9ba412247e7e637410d66411a | hanu1234/Daily_Update | /Decorator_Study/decorator1.py | 745 | 4.375 | 4 | """
--> Decorator is a design pattern in python which allows user to add new functionality to the existing object without
modifying its structure.
--> Functions in python are first class citizens. means hat they support operations such as being passed as an argument,
returned from a function, modified, and assigned t... |
05b2b15c384a0b0e2f1e8d5ef3c9ccbd1c39241d | hanu1234/Daily_Update | /Decorator_Study/decorator2.py | 447 | 4.1875 | 4 | def decor(func):
def inner(name):
if name == 'Sunny':
print("Hello sunny good morning")
else:
func(name)
return inner
# whenever you call wish function internally decor function will execute
@decor # linking the decorator function to the wish function
def wish(name... |
765fbd63c5d86bca48e9a970314efd74889dc0c0 | HoangYenFL/Pythonlab_Yenc17 | /lab3/bai1.1d.py | 145 | 3.859375 | 4 | nums = list(range(5))
print(nums)
print(nums[2:4])
print(nums[2:])
print(nums[:2])
print(nums[:])
print(nums[:-1])
nums[2:4] = [8, 9]
print(nums) |
d8bd3d41c7cc20654adb29ff460d93322fffa4fb | fpolizzi/jb-academy-python-hangman | /Problems/Small scale/main.py | 191 | 3.625 | 4 | values = list()
input_string = input()
while input_string != ".":
float_val = float(input_string)
values.append(float_val)
input_string = input()
values.sort()
print(values[0])
|
2b608d1d37d264c754b3dd83d185c28d201bbc21 | ngoquoc-git/Summer2021 | /Python/Python Basic Practice/leetcode/week1/ReverseInteger.py | 1,147 | 3.796875 | 4 | class ReverseInteger:
#7. Reverse Integer - Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0
def reverse(self, x: int) -> int:
remainder = 0
myList = []
readR... |
06611778b5874ccceb433c41c4d296589aade143 | godwin15/LeetLearn | /app.py | 240 | 3.71875 | 4 |
def array_reduce(array):
total = 0
while len(array) > 1:
array.sort()
a = array.pop(0)
b = array.pop(0)
total += a + b
array.append(a + b)
return total
a = [1,2=]
print(array_reduce(a)) |
bed3f4450de26ff6e2cc78fd66f73a7bb961ab3a | nikhilslounge/language-learning | /src/parse_evaluator/parse_evaluator.py | 6,981 | 3.5 | 4 | #!/usr/bin/env python
# ASuMa, Mar 2018
# Read parse data in MST-parser format, from reference and test files
# and evaluate the accuracy of the test parses.
# See main() documentation below for usage details
import platform
import getopt, sys
def version():
"""
Prints Python version used
"""
pri... |
c98f9d655ba31eaa5d49e6cc7d6475240daae913 | diogenes1991/Small_Projects | /Graphs/grafo.py | 6,572 | 3.703125 | 4 | import sys
from os import system
from math import *
import random
def PRINT(MATRIX):
for i in MATRIX:
count = 0
aux = "|"
for j in i:
aux += str(j)
count += 1
if(count != len(i)):
aux += " "
aux += "|"
print(aux)
def MULTI... |
c9634b721f38f6c027bbae9a6501a1f64cfe1dc8 | SelmTalha/randomtoplama-sql | /veritabani_random(console)/veritabani.py | 681 | 3.65625 | 4 | import sqlite3
import random
sql=sqlite3.connect("random.db")
cur=sql.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS randomekle(Sayi1 INT,Sayi2 INT,Tahmin INT,Gercek_sonuc INT,Durum TEXT)")
sayi1=random.randint(1,100)
sayi2=random.randint(1,100)
toplam=sayi1+sayi2
print(sayi1,"+",sayi2,":")
a=int(input("Sonucu giri... |
19fede773f5e02a0751dc64f7fe8653afa88907b | WilliamW5/Tkinter | /file.py | 830 | 3.546875 | 4 | from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
root = Tk()
root.title('File Dialog')
root.iconbitmap('Images/WillRagB.ico')
root.geometry("800x600")
def open():
global my_image
global my_label
global my_image_label
# filetypes(("description", filetype), ())
roo... |
b6a12eed08ecbd31ac9670ac8fd8980aa12e6f92 | WilliamW5/Tkinter | /frames.py | 455 | 3.609375 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Frames')
root.iconbitmap('Images\WillRagB.ico')
# puts padding inside of the frame
frame = LabelFrame(root, text="This is my Frame...", padx=50, pady=50)
# packs inside of the outside container
frame.pack(padx=100, pady=100)
b = Button(fra... |
292c07ac90f06d62e27a03fa50ed0d4d82f915da | jazib-mahmood-attainu/Ambedkar_Batch | /W4D3 - OOPS1/main.py | 565 | 3.984375 | 4 | from student import Student
if __name__=="__main__":
name = input("Enter name of student")
age = int(input("Enter age of student"))
birth = int(input("Enter birth year of student"))
student1 = Student(name,age,birth)
print(student1.name)
print(student1.age)
student1.read()
name = inpu... |
46a127707658e21d1803780f7296bfca1e797f69 | jazib-mahmood-attainu/Ambedkar_Batch | /W4D2 - python 10 - dicts/dicts.py | 1,325 | 4.03125 | 4 | """
Dictionary - is another type of DS
property 1:
Syntax
for indexing we use key:value pair in the form of
{
key1:value1,
key2:value2,
.
.
.
}
property 2:
you can have,
integer/float/string/list/tuple/anotherdictionary
as a value inside a dictionary
property 3:
Keys should never repeat/keys ar... |
2c19630468174583ea39969d32c833c3554bd6c8 | jazib-mahmood-attainu/Ambedkar_Batch | /W8D4_ll2/merge.py | 1,379 | 3.953125 | 4 | class Node:
def __init__(self,val):
self.data = val
self.next = None
head3 = None
def merge(head1,head2):
p1 = head1
p2 = head2
global head3
cur = head3
while (p1 is not None) and (p2 is not None):
if p1.data<p2.data:
#if p1.data is smaller
if he... |
f08641eac30b72715889362b2a2faea9f94f284a | jazib-mahmood-attainu/Ambedkar_Batch | /W3D4 - python 7/number_of_vow.py | 565 | 3.5625 | 4 | # s = input("Enter the string")
# va,ve,vi,vo,vu = 0,0,0,0,0
# for ch in s:
# if ch=='a':
# va += 1
# if ch=='e':
# ve+=1
# if ch=='i':
# vi+=1
# if ch=='o':
# vo+=1
# if ch=='u':
# vu+=1
# if va !=0 :
# print("Number of a",va)
# if ve !=0 :
# print("... |
986dcf124a61beacee175dc222dae6bb1b43d424 | jazib-mahmood-attainu/Ambedkar_Batch | /W5D5 - searching/linear.py | 240 | 3.78125 | 4 | arr = [1,23,45,65,98,78,23,56,85]
target = 85
def linear_search(arr,x):
for i in arr:
if i == x:
print("present")
return
print("not present")
if __name__=="__main__":
linear_search(arr,target) |
dc5cf8d9813513dc9e61bd4cbfaea6714d35406a | jazib-mahmood-attainu/Ambedkar_Batch | /Doubt_clearance_W7D5/dummy.txt | 424 | 3.609375 | 4 | """
Public
Protected
Private
"""
class Student:
def __init__(self,x,y):
self.__a = x
self.__b = y
def show(self):
print(self.__a,self.__b)
class ali(Student):
def __init__(self,z, x, y):
self.z = z
super().__init__(x, y)
self.a1 = super().__a
... |
e547a380a4d3101cd069db01439bb1a92f455001 | jazib-mahmood-attainu/Ambedkar_Batch | /W2D3 - Python3/doubt_clr.py | 1,314 | 4.03125 | 4 | # a = int(input("Enter the number"))
print(12%4==0)
# a = input(11)
# b = input(12)
# c = a+b
# print(c)
# a = 5
# b = 7
# c = 5
# print( (a==c) or (a==b) )
# print( (a==c) or (a!=b) )
# print( (b==c) or (a==b) )
# print( (b==c) or (a==c) )
# num=int(input("enter a number"))
# if num%4 ==0:
# print(num,"is ... |
986272e4ccb6c72339742759579fc37f2d9ff8e4 | marianoprisan/MIT6.00x | /lectures/factorial.py | 336 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 25 12:08:42 2016
@author: lvl
"""
def factorial(n):
"""
Returns the factorial of n
Uses recursion
"""
if n == 1:
return 1
else:
return(n * factorial(n - 1))
n = int(input("Enter the factorial you want me to compute: "))
pri... |
451555fca91449e0444533cc6ce9db0e2a20a0ab | ShahrzadFakour/PythonSpecialization | /PythonDataStructure/ex-03.py | 255 | 4.125 | 4 | # Use words.txt as the file name
fname = input("Enter file name: ")
try:
if fname=="words.txt":
fh = open(fname)
except:
print("file is not correct")
quit()
for line in fh:
fline=line.rstrip()
fUpper=fline.upper()
print(fUpper)
|
876c09ae435ba0b82fb030c45e47a8d2875181de | kdsmith500/django_strike | /main_app/physics.py | 620 | 3.734375 | 4 | import math
g = -9.81
theta = math.pi / 3
lat1 = 33.729759
lon1 = -111.431221
lat2 = 36.116203
lon2 = -119.681564
# obtain great circle distance between 2 points:
def R(origin, target):
lat1, lon1 = origin
lat2, lon2 = target
radius = 6371e3 #in meters
dlat = math.radians(lat2-lat1)
dlon = ma... |
3ba729168542a17d1ad57711928e52f9c48a9a83 | MerlanOurBoss/MyWeb | /w6/3/1/I.py | 94 | 3.546875 | 4 | cnt = 0
a = int(input())
for i in range(1, a//2+1):
if a%i == 0:
cnt = cnt +1
print(cnt+1)
|
1300b1b8bcc021e5c7aa40a4c9aeac619d1a78ce | MerlanOurBoss/MyWeb | /w6/3/2/C.py | 121 | 3.765625 | 4 | import math
a = int(input())
p = math.pow(2,0)
i = 1
while(p<=a):
print(int(p), end = ' ')
p = math.pow(2,i)
i = i +1
|
8f9af099e55a7c5b8ea5fbf914ba8a3e7f57bc3f | LUnsworth/BBC-Technical-Assesment | /Bowling.py | 7,899 | 3.65625 | 4 | #Bowling game source code - BBC Technical exercise - Luke Unsworth 19/02/15
#
# Version 1.1 Completed 09/03/15
# TODO:
# Tidy up code and trim it down where necessary.
#
# Import useful things:
from random import randint
#Global game dictionary. I know this is clunky, but there you go.
Game = {}
def PlayerSetup(... |
57a715e0c4bfa4806d2966b95b7f4de6aa973248 | andresrm/ProgramacionF | /Producto2/juego.py | 519 | 3.734375 | 4 | import time
print "Hola! Tratare de adivinar un numero."
import time
time.sleep(5)
print "Piensa un numero entre 1 y 10."
import time
time.sleep(5)
print "Multiplicalo por 9"
import time
time.sleep(5)
print "Si el numero es de dos digitos, sumalos entre si: Ej. 36 -> 3+6=9. Si tu numero tiene un solo digito, sumal... |
0968e05c5384683848b67caec74b86e8a604c411 | bharathiIT90/Python- | /4_script.py | 1,050 | 4.03125 | 4 | def AskForNumberCities():
number = raw_input('Enter the number of cities you would like to visit: ')
try:
n=int(number)
except:
print 'Enter a valid input!!'
else:
AskForCityNames(n)
def AskForCityNames(n):
cities = raw_input('Enter the city names: ')
cities= cities.... |
233a19888278f95ef026fd15f76203ed1a33a369 | amanda-crosby/tic_tac_toe | /newtictactoe.py | 3,503 | 4.40625 | 4 | def create_empty_board():
board = [[None] * 3 for i in range(3)]
return board
#The inner list comprehension creates a list with 3 None elements, and the outer list comprehension creates 3 of those lists.
#This yields a 3x3 matrix where every element is initialized to None.
def draw(board):
prin... |
213b779cc4039ffccde7d09c410c860366ade298 | arnabpro007/HackerRank-Python | /mutableString.py | 311 | 3.890625 | 4 | def mutate_string(string,position,character):
temp = string[:position] + character + string[(position + 1):]
return temp
def main():
s = input("Enter your String: ")
i,c = input().split(" ")
s_new = mutate_string(s,int(i),c)
print(s_new)
if __name__ == '__main__':
main()
|
912bc78437d8f82729ec8e22d224d86c7515b778 | devkimmy/MEImage2Latex | /preprocess.py | 9,464 | 3.5 | 4 | import cv2 # 문자단위로 인식 하기 위해
import numpy as np # 배열 계산 및 조작
import matplotlib.pyplot as plt # 이미지 띄워주기 위함
from keras.models import load_model
from keras.preprocessing import image
def show_images(images, cols=1, titles=None):
assert ((titles is None) or (len(images) == len(titles)))
n_images = len(images)
... |
9e20339e44d354e7291090812c473905d98f374b | jbrewer98/LeetCode | /LongestSubstring.py | 976 | 3.796875 | 4 | # Created by Jack Brewer August 2019
# Description
# Given a string, find the length of the longest substring without repeating characters.
# Strategy
# Iterate through the string letter by letter, while keeping a substring with the current unique string.
# Check if each letter is in the unique string, if it is then ... |
2482bb23271177fe37e8768e33ead2d75759db8b | Lightwing-Ng/DesignPatternAlex | /Adapter.py | 2,149 | 4.0625 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
* @author: Lightwing Ng
* email: rodney_ng@iCloud.com
* created on Apr 29, 2018, 1:10 PM
* Software: PyCharm
* Project Name: Tutorial
"""
# 适配器模式
# 将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
# 应用场景:希望复用一些现存的类,但是接口又与复用环境要求不一致。
def printInfo(info):
pri... |
1d64198ad77a0a2ef9a790c24f67194d0e757dae | Loleiying/LeetCodeExercises | /AddTwoNumbers.py | 1,412 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 30 21:52:50 2020
@author: Liying Lu
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def setNext(self, next):
self.next = next
def setValue(self, value):
self.value = value
... |
bdfd26506d21d238f55e5679e34930c852a99c86 | MariusDL/Python-Steganography | /steganography.py | 2,182 | 3.921875 | 4 | from PIL import Image
import stepic
import easygui
import base64
# show options to the user
print("Choose an option:\n1. Encode text in image\n2. Extract text from image\n")
# loop until the user enters a correct choice
choice = ""
while(not(choice == "1" or choice == "2")):
choice = input("Enter your cho... |
477d9607c10747fcd394518e11b4f7a5ee0befbe | shaneros/excel-sheet-combiner | /combine_sheets_gui.py | 2,138 | 3.59375 | 4 | import tkinter as tk
from tkinter import filedialog
import os
import pandas as pd
import datetime
app = tk.Tk()
app.title('Sheet Combiner')
app.geometry("640x480")
instructions_text = """
Click the 'Choose Excel Workbook' button and select the file that you'd like to combine.
When you've confirmed your choice, click ... |
c4b0431470ec99445f8811d8d0627d82831de3ce | michellegsld/AirBnB_clone | /models/engine/file_storage.py | 2,347 | 3.96875 | 4 | #!/usr/bin/python3
"""
file_storage.py
FileStorage Class
"""
import json
import os.path
class FileStorage:
"""
Serializes instances to a JSON file as storage
Deserializes JSON file to instances to recreate saved instances
Contains the class attributes:
- __file_path -> String. Path to JSON file.
... |
46ead95e15bd60a830b8e5a1e2b3e6d15ae2a4e3 | almyki/color-mixing-sim | /color_mixing_main.py | 3,429 | 3.859375 | 4 |
import colorsys
from colormix_values import *
#### Functions to convert color systems between CMY, RGB, HSV.
def hue_to_cmy(hue_value):
"""Convert a hue value (0 to 255) into CMY."""
# Red-Yellow range. M100 = red. M0 = Yelow.
if hue_value in range(0, 60):
c = 0
m = i... |
dacc7c54c81ca023dcbe9e1a361a919f38f78c05 | ShenDeng75/LeetCode | /4 寻找两个有序数组的中位数.py | 506 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def findMedianSortedArrays(self, nums1: list, nums2: list):
nums3 = nums1 + nums2
snums3 = sorted(nums3)
lenght = len(snums3)
if lenght % 2 == 0:
ans = (snums3[(lenght // 2)] + snums3[(lenght // 2 - 1)])/2
... |
4b88d74b3fcffa157c9dc9c166fba3ebf2939cd0 | V-FOR-VEND3TTA/Customer-Relationship-Management-Tool | /customers.py | 893 | 4.03125 | 4 | class Customer:
def __init__(self, name, email, membership_type):
self.name = name
self.email = email
self.membership_type = membership_type
def membership(self): # the membership type of a customer
return "{} has a {} membership.".format(self.name, self.membership_type)
... |
fa2a8018b46c23559d2554309d7ed21be367572c | teamWSIZ/para-progr-2020 | /etap2/klasy_user.py | 826 | 3.6875 | 4 | class User:
name: str
age: int
__id: str
def change_name(self, new_name: str):
self.name = new_name
def __init__(self, name='anonymous', age=0):
self.name = name
self.age = age
self.__id = name + str(age)
def verify_id(self, expected_id):
return self.__... |
e94b21f2de2f31536ea4ffa9be6447d295ddef85 | teamWSIZ/para-progr-2020 | /etap3_images_dicts/class_dict_in_python.py | 239 | 3.765625 | 4 | class Car:
name: str
brand: str
def __init__(self, name, brand):
self.name = name
self.brand = brand
c = Car('the first ferrari', 'ferrari')
di = c.__dict__
d = Car(**di)
d.name = 'the second ferrari'
print(d.__dict__)
|
20442102273ae6926c4d86c5cefb9b9662e76f1a | tubaDude99/Old-Python-Exercises | /Unit 3/4.2.py | 20,903 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Section 4.2: Variable Scope
# * def
# * global
#
# ### Students will be able to:
# * Define local variables
# * Read and modify the values of local variables
# * Identify the scope of a variable
# * Define global variables
# * Read and modify the values of global variables fr... |
d5259ff031ec988e346c552ec62d3569fa1d689d | tubaDude99/Old-Python-Exercises | /Unit 3/2.1.py | 14,053 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Section 2.1: Boolean Expressions and Compound Conditionals
# * and, or, not
# * if
#
# ### Students will be able to:
# * Describe the fundamental Boolean operators (and, or, not)
# * Use Boolean operators to combine comparisons
# * Recognize that different Boolean expression... |
4f0c05ef624fc4639114b676b38d5979990ee934 | tubaDude99/Old-Python-Exercises | /Unit 1/3Practice3a.py | 4,042 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Lab 3a
# ## Conditionals Practice
#
# -----
#
# ### Student will be able to
# - **Control code flow with `if`... `else` conditional logic**
# - Using Boolean string methods (`.isupper(), .isalpha(), startswith()...`)
# - Using comparision (`>, <, >=, <=, ==, !=`)
#... |
363704a197f99e5af916cd3cb48eb69ce5f2c956 | tubaDude99/Old-Python-Exercises | /Unit 2/1_Practice1.py | 6,208 | 4.75 | 5 | #!/usr/bin/env python
# coding: utf-8
# # Module 1 Lab
# ## Sequence Index Practice
#
# -----
#
# ### Student will be able to
# - Work with string characters
# - Slice strings into substrings
# - Iterate through string characters
# - Use string methods
# ## Task 1: Access String Characters
# ### `working_string[in... |
eb34ce95fc0a7ba7a223e87df9983e8a07caf33c | tubaDude99/Old-Python-Exercises | /Unit 1/4Project4.py | 3,771 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Module 4 Required Coding Activity
# Introduction to Python Unit 1
#
# The activity is based on Modules 1 - 4 and is similar to the Jupyter Notebooks for Module 4 practice, which you may have completed. This activity is a new version of the str_analysis() function.
#
# |... |
71ea9d3d52c6da907494b6dcb45eeee1e909e096 | mattstermh93/Grocery-Helper | /shoppingCartFinal.py | 2,751 | 4.21875 | 4 | class FoodInfo():
def __init__(self):
self.food = ['grapes', 'olives', 'apples', 'oranges', 'donuts', 'bread', 'cheese', 'milk', 'salad', 'burgers', 'tomatos', 'potatos', 'almonds', 'eggs',
'olive oil', 'peaches', 'plums', 'garlic', 'pepper', 'salt', 'bananas', 'chicken', 'meat', 'soy', 'macaroni'... |
db8fad53c765ea7d96d9d32ee5d877c548b9f787 | MGalati/BioInformaticTraining | /rabbit.py | 284 | 3.84375 | 4 | #!/usr/bin/python
# http://rosalind.info/problems/fib/
def rabbit(month, bunny):
if month == 0:
return 0
elif month == 1:
return 1
else:
return rabbit(month-1, bunny) + rabbit(month-2, bunny) * bunny
if __name__ == '__main__':
rabbit(30,5)
|
537041fe20f6deb05178db621094bbdd587aef22 | Jl5her/AdventOfCode | /2015/day-13/solution.py | 1,343 | 3.625 | 4 | import re
PART2 = False
def makeOptions(arr, people, a):
for p in people:
new_people = people[:]
new_people.remove(p)
new_a = a[:]
new_a.append(p)
arr = makeOptions(arr, new_people, new_a)
if len(people) == 0:
arr.append(a)
return arr
... |
c7142fee0e1d30947da8b10692ad622e500840b1 | Jl5her/AdventOfCode | /2015/day-18/part-1/solution.py | 1,112 | 3.78125 | 4 | def read():
with open("../input.txt") as f:
return [ list(line.rstrip()) for line in f.readlines()]
return None
def disp(board):
print()
for row in board:
print("".join(row))
print()
def neighbors(board, pointX, pointY):
neighbors = []
for y in range(max(0, pointY - 1), min... |
64d0edc754d99989cc75d8ce5538136e02926b31 | Jl5her/AdventOfCode | /2016/day-06/solution.py | 813 | 3.6875 | 4 | def frequency(a):
f = {}
for e in a:
f[e] = f[e] + 1 if e in f else 1
f = sorted(f.items(), key = lambda x: x[0])
f = sorted(f, key = lambda x: x[1], reverse= True)
return f
def read():
with open("input.txt") as f:
return f.readlines()
return None
def part1(lines):
... |
47d6b8cbb14380afe706bfe6bf383c7fdb29af29 | Jl5her/AdventOfCode | /2015/day-01/solution.py | 311 | 3.59375 | 4 | def part1(string):
return eval(string.replace("(", "+1").replace(")", "-1"))
def part2(string):
for pos in range(1,len(string)):
if part1(string[:pos]) == -1:
return pos
with open("input.txt") as f:
contents = f.read()
print(part1(contents))
print(part2(contents)) |
99df40c6377a173aed50f7fefe232d78b2762a20 | zxu32/6.00.2x | /sortingAlgorithm/heapSortPractice.py | 1,107 | 4 | 4 | # heapsort
import random as rand
def maxHeapify(aList, i, heapSize):
left = i * 2 + 1 # index of left node
right = left + 1 # index of right node
if left <= heapSize-1 and aList[left] > aList[i]:
largest = left # index of largest value
else:
largest = i
if right <= heapSize-1 an... |
6cfb64a788902434636fb4f8f446e5bc5e4f2ff9 | zxu32/6.00.2x | /finalExam/rabbits.py | 3,432 | 4.25 | 4 | import random
import pylab
# Global Variables
MAXRABBITPOP = 1000
CURRENTRABBITPOP = 500
CURRENTFOXPOP = 30
def rabbitGrowth():
"""
rabbitGrowth is called once at the beginning of each time step.
It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP.
The global variable CURRENTRA... |
720699a011856fd24d7e900ddd8c185e9ef0fbc3 | MPCS-51042/homework | /ch3/problem_6.py | 514 | 3.734375 | 4 | from problem_4 import taxes_owed
def inflection_point():
'''
This function returns a float representing the income at which
Townsville's graduated income tax would be higher than a flat
5% income tax.
'''
pass
## TESTS BELOW
inflection_income = inflection_point()
if inflection_in... |
97c0f0277c2c8f752a264fd5dd4df5a0c43daf5e | lcary/tmp | /python/coins.py | 2,893 | 4.21875 | 4 | from collections import Counter
"""
I would recommend that you check out the `Counter()` class in the `collections` library of Python's stdlib:
https://docs.python.org/2/library/collections.html#collections.Counter
### Using Counters To Keep Tally
Think of the Counter object as an overpowered dictionary, designed fo... |
1008e813c51be1c7cd0b3bd31476a044e82a6e8f | Nouf-Al/Nouf_Alotaibi | /python_stack/_python/OOP/Chaining Methods.py | 965 | 3.75 | 4 | class User:
def __init__(self,name):
self.name = name
self.balance= 0
def make_deposit(self,amount):
self.balance+=amount
return self
def make_withdrawal(self,amount):
self.balance-=amount
return self
def display_user_balance(self):
print("U... |
dca9afecc0a98e0a5e1d47f90634083a9a500462 | bajracae/Othello | /othello_1.py | 2,909 | 3.96875 | 4 | def init_board(r,c):
board = [' ']*r
for i in range(r):
board[i] = [' ']*c
return board
def print_function(board):
print("\n----------------------")
for i in range(len(board)):
for j in range(len(board[i])):
print("|" + board[i][j] + "|", end = "")
if board[i][j] == 'X':
print("|X|", end="")
elif... |
30c05e29e22fdceca2178e52e88021d06ca205f7 | kehillah-coding-2019/turtle-doodle-Elanse | /doodle.py | 1,657 | 3.734375 | 4 | import turtle
import math
bg = turtle.Screen()
cross = turtle.Turtle()
cross2 = turtle.Turtle()
diagonal = turtle.Turtle()
diagonal1 = turtle.Turtle()
diagonal2 = turtle.Turtle()
diagonal3 = turtle.Turtle()
line = turtle.Turtle()
line1 = turtle.Turtle()
line2 = turtle.Turtle()
line3 = turtle.Turtle()
height = 400
... |
0c1454c05d3ea026ff7129f3568f866145639304 | Johnmburu919/operatos | /logical.py | 148 | 3.640625 | 4 | #logical operator
#and operator
y=10
x=11
print(y>4 and x>7)
#or operator
y=1
x=11
print(y>4 or x<7)
#not operator
y=77
x=67
print(not(y>4 and x<7)) |
dd93eee55e9a3f9e22817f2f75884ab218d7f07f | dapng/valid_phone_num | /main.py | 408 | 3.59375 | 4 | import re
# The first option
def verify_number(number):
print(bool(re.search(r'^([\+][7]\s[\(]\d{3,3}[\)]\s\d{3,3}\s\d{2,2}[-]\d{2,2})$', number)))
verify_number("+7 (111) 111 11-11")
# The second option
# def verify_number(number):
# num = (re.search(r'^([\+][7]\s[\(]\d{3,3}[\)]\s\d{3,3}\s\d{2,2}[-]\d{2,2}... |
13b858393fc564c4cb40f87c1d6c1f722fafb820 | yagukom/Python | /对递归的理解(n的阶乘).py | 407 | 3.859375 | 4 | #2021-1-8 15:59
#以下内容来自《自学是门手艺--李笑来》2.4.4递归函数
#递归的意义:即在自身内部调用自身的函数。
#功能:n!的递归处理函数
def f(n):
if n == 1: #即,递归函数内部肯定是有一个终止的条件的。
return 1
else:
return n * f(n-1) #递归函数内部一定存在 自己调用自己 的语句。
print(f(5))
|
c76091376fa420198838132d4f3cb5289b08bd30 | yagukom/Python | /递归函数实现反向打印字符(含Docstring).py | 1,538 | 3.734375 | 4 | #2021-1-11 9:22
#题目来自《自学是门手艺--李笑来》2.4.4递归函数 编程题1165
#递归函数实现反向打印字符
#昨天晚上写的是用for循环实现反向打印字符.py
def StringReverseCoreFunc(string,StringIndex,ResultString):#2字符串反向打印的核心递归函数
"""
2021-1-11 11:26
用于字符串反向打印的递归函数。
参数1:为用户最初从input()输入的字符串。
参数2:为参数1字符串的下标。
参数3:为每次该递归函数处理后的列表型的字符串结果。
"""
if StringIndex==0:
#resu... |
2dfb74d9507e80d4a93ff245bf2894c0f6fb3d32 | Simonnn-a/jiangzy11 | /deme2.py | 6,428 | 3.71875 | 4 | # _*_ coding:utf-8 _*-
# 作者:大汉老师
# 微信:abc554400
# @Time:2020-09-15 20:06
# @Email:896096254@qq.com
# @File: deme2.py
# 常用的数据类型
# 什么是数据类型:一类数据的类型统称
# 特点:python是不需要申明数据类型的
# python中常见的数据类型有那些?
# number、string、tuple、不可变数据类型
# list、dict、set可变数据类型
# 一、number类型(数字类型、不可变类型)
# int float bool
# 运算符
# 算数运算+ — * / // % **
# 比较运... |
a4323b3b8270b6651ea0a6b3e345671782e440f6 | BIGDADDY1974/DAVOR_PY | /CODE_EXAMPLES/testing.py | 267 | 3.984375 | 4 |
while 10:
x = input("Please enter how many persons do we need to store into database?? ")
try:
val = int(x)
print ('integer entered', val)
break
except ValueError:
print (x, ' is not an integer, You must give me a number') |
99ff82c4b6f624f31804630cfb2ca9fb28dff962 | santu-cpu/BMI-Calculator | /BMI_Calc.py | 2,414 | 3.75 | 4 | from tkinter import *
root = Tk()
root.title('BMI Calculator')
root.configure(width=500,height=400,bg='black')
def calc():
BMI = BMI_val(mass.get(),height.get())
s_tat = get_status()
stat.set(s_tat)
bmi_val.set(format(BMI,'.2f'))
def BMI_val(mass,height):
return mass/height**2
def get_height():
return he... |
854658b9206751ceff08c901f0a9a444208d0d4a | Anuragjain20/Programming-Language-Notes-and-Resources | /Python/3.Conditions/If-elif-else.py | 1,302 | 4.34375 | 4 | '''
If statement conditions
If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.
Python relies on indentation to define scope in the code
'''
'''
Syntax:
if (condition):
code1
elif (condition):
code2
els... |
5ba9fc15d4aa262ab921636e6e24cfe7b1118db9 | gitoso/CT-213 | /Lab3/ball_fit.py | 8,250 | 3.9375 | 4 | import numpy as np
import random
from math import pi, cos, sin
from least_squares import least_squares
from gradient_descent import gradient_descent
from hill_climbing import hill_climbing
from simulated_annealing import simulated_annealing
import matplotlib.pyplot as plt
def cost_function(theta):
"""
... |
7a04789351f037ddcaeb5bb803af068a13233dba | gitoso/CT-213 | /Lab5/simple_evolution_strategy.py | 2,635 | 3.765625 | 4 | import numpy as np
import time
class SimpleEvolutionStrategy:
"""
Represents a simple evolution strategy optimization algorithm.
The mean and covariance of a gaussian distribution are evolved at each generation.
"""
def __init__(self, m0, C0, mu, population_size):
"""
Cons... |
c68446bcde2563f45763a22652f1f6baa68a2777 | lafyq/learn_python | /untitled/hm/hm_02_手动实现trim.py | 2,176 | 3.703125 | 4 |
# def trim(s):
# begin = None
# end = None
# flag = False
# for i in s:
# if not flag:
# if i == ' ':
# pass
# else:
# begin = s.index(i)
# flag = True
# else:
# if i == ' ':
# ... |
77edcc42071b869c7c0ae6aaf59e6616c705c6e4 | lafyq/learn_python | /untitled/hm/hm_01_汉诺塔.py | 1,198 | 4.125 | 4 | # 定义一个全局变量 count 用来计数移动了多少次
count = 0
def move(n, from_tower, buffer_tower, to_tower):
"""
所以说一共就三步:
1、把 n-1 号盘子移动到缓冲区
2、把1号从起点移到终点
3、然后把缓冲区的n-1号盘子也移到终点
:param n: 所要移动的盘子
:param from_tower: 起点
:param buffer_tower: 缓冲区
:param to_tower: 终点
:return:
... |
b5bef62e84684aa106ed9500eff61564b8fb4703 | lafyq/learn_python | /untitled/hm/hm_15_继承和多态.py | 2,067 | 4.09375 | 4 | class Animal(object):
def eat(self):
print("animal is eating...")
class Dog(Animal):
def eat(self):
print("dog is eating...")
class Cat(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
# 看来dog不仅仅是Dog,dog还是Animal!
# 所以,... |
6fc5a36a1dd02fe2936f76d277593258bda4bc5c | lafyq/learn_python | /untitled/hm/hm_27_02_01_多线程.py | 4,787 | 4.34375 | 4 | print()
"""
Python的标准库提供了两个模块:_thread和threading,_thread是低级模块,threading是高级模块,对_thread进行了封装。
绝大多数情况下,我们只需要使用threading这个高级模块。
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:
"""
import time, threading
# 新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
... |
8381f9e69a61e236802410ef40129969ed381624 | peaches12/Olga_Python_Projects | /Convert_Temperature_C_F/Convert_temperature_C_F.py | 1,187 | 4.4375 | 4 | # Date: Aug 23,2017
# Project Name: Convert Temperature
# Author: Olga Lazarenko
# Description: the program contains two functions:
# the function to_c(temp) converts the temperature rom F to C
# the function to_f(temp) converst the temperature from C to F
print('to convert from F to C cal... |
eeec7b43398c9aa65031320226cb16cf62b5fc19 | euxuoh/leetcode | /python/sort/merge-sort.py | 775 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
doc string
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/3/5
"""
class MergeSort(object):
def merge_sort(self, nums):
if len(nums) <= 1:
return nums
def merge(l, r):
merged = []
whil... |
0c3cf3e48689f4aebf7be8f7679d312d3574c9a5 | euxuoh/leetcode | /python/two-pointer/remove-duplicates-sorted-array.py | 1,007 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
80. Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, ... |
092a88e454f0b8212e9246657a38fdd1985d6650 | euxuoh/leetcode | /python/hashtable/top-k-freq-elem.py | 1,385 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexit... |
983ac81d28adf598b7c5e96306a5163fa4d639be | euxuoh/leetcode | /python/linked-list/add-list-number2.py | 1,794 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
445. Add Two Numbers II
You are given two linked lists representing two non-negative numbers.
The most significant digit comes first and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.