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 |
|---|---|---|---|---|---|---|
29be81fb14c2bcf9ee29d7379094aba2bc9147f4 | Leedokyeong95/PythonWorks | /Ch07/p.198.py | 315 | 3.6875 | 4 | """
날짜 : 2021/02/25
이름 : 이도경
내용 : 파이썬 프로그램 문자열 치환 예제 p.198
"""
from re import sub
st3 = 'test^홍길동 abc 대한*민국 123$tbc'
# (1) 특수문자 제거
text1 = sub('[\^*$]+', '', st3)
print(text1)
# (2) 숫자 제거
text2 = sub('[0-9]', '', text1)
print(text2) |
5e2e4947caf5d876b40326247278193246288d7d | Leedokyeong95/PythonWorks | /Ch07/7_1_RegularExpression.py | 1,573 | 3.78125 | 4 | """
날짜 : 2021/02/24
이름 : 이도경
내용 : 파이썬 정규표현식 실습하기 교재 p.192
정규표현식(Regular Expression)
- 특정한 규칙을 갖는 문자열을 처리하기 위한 문법
- 일반적으로 특정 문자 검색, 매칭 여부를 많이 처리
"""
import re
from re import findall, match
str1 = '1234 abc홍길동 ABC_555_6 이사도시'
# 숫자검색
print(findall('1234', str1))
print(findall('[0-9]', str1)) #[0-9] -> 정규표현식, 숫자 0에서 ... |
ae1a1804b77550b9c2eadcb478b3b953fcd75049 | Leedokyeong95/PythonWorks | /Ch10/10_7_SQLite_CRUD.py | 1,565 | 3.796875 | 4 | """
날짜 : 2021/03/04
이름 : 이도경
내용 : 파이썬 SQLite 실습하기 교재 p.291
"""
import sqlite3
try :
# db 연동 객체
conn = sqlite3.connect("./data/sqlite_db") # db생성 -> 연결 object
# sql 실행 객체
cursor = conn.cursor()
# (1) table 생성
sql = """create table if not exists goods(
code integer primary key,
name tex... |
620ea19959e67278bf5f90f1699b79c4bf5b9bd0 | Leedokyeong95/PythonWorks | /Ch08/p.215.py | 625 | 3.90625 | 4 | """
날짜 : 2021/02/25
이름 : 이도경
내용 : 파이썬 프로그램 중첩 예외처리 예제 p.215
"""
# 유형별 예외처리
print('\n유형별 예외처리')
try:
div = 1000 / 2.53
print('div = %5.2f' %(div))
div = 1000 / 0
f = open('c:\\test.txt')
num = int(input('숫자 입력 : '))
print('num =', num)
# 다중 예외처리 클래스
except ZeroDivisionError as e:
print('오류 ... |
67d7877e7d83ee1572e93a712c22a143cdbd8e29 | NirantK/DSA-BITS-Masti | /Lab7/sanitize.py | 277 | 3.671875 | 4 | import string
put = open('clean.txt','w')
with open('input.txt') as f:
for line in f:
for ch in line:
if ch.isalpha() or ch==' ' or ch=='\n':
if ch=='\n':
put.write(' ')
else:
put.write(ch.lower()) |
c3321ce8c7877a3150aa214240d6de79ca551c56 | dangxthao/Metaheuristics | /AutomataLearning/SA.py | 41,134 | 3.890625 | 4 | import myfunctions as mf
import DFA
class SA:
"""This class represents a Symbolic Automaton."""
def __init__(self,
concrete_alphabet,
symbolic_alphabet,
states,
initial_state,
final_states,
psi,
... |
f8353e56cf475faa63e119f8e284981ed522038e | ZivLi/CodeRogue | /python-example/learn_thread.py | 708 | 3.75 | 4 | import time, threading
def loop():
print 'thread %s is running...' % threading.current_thread().name
n = 0
while n < 5:
n = n + 1
print 'thread %s >>> %s' % (threading.current_thread().name, n)
time.sleep(1)
print 'thread %s ended.' % threading.current_thread().name
balance = 0
lock = threading.Lock()
de... |
0fac1e302275fd8c77181ceca7f85afdf0056bc4 | mackrellr/PAsmart | /rock_paper_scissors.py | 2,208 | 4.1875 | 4 | import random
player_choice = 0
npc_choice = 0
game_on = True
# Indicate choices for win
def choices(p1, p2):
print()
if p1 == 1:
print('Player choose Rock.')
if p1 == 2:
print('Player choose Paper.')
if p1 == 3:
print('Player choose Scissors.')
if p2 == 1:
pr... |
68918f822db5babda0faeb501a0979447d27143d | misrapk/tkinter-Tutorials | /ClickEvents.py | 242 | 3.578125 | 4 | from tkinter import *
root = Tk()
def leftClick(event):
print("Left Press")
def RightClick(event):
print("Right Press")
frame = Frame(root, width = 300, height=300)
frame.bind("<Button-1>", leftClick)
frame.pack()
root.mainloop() |
9a17352f3e5721160fb621e4e8cf29dc7f750568 | wosslr/PythonLearning | /MyFirstPythonProject/multiple_threads_sample.py | 2,085 | 3.984375 | 4 | # encoding: utf-8
from threading import Thread
from threading import Lock
from time import sleep
from random import randint
# 仓库有十个槽位
storehouse = [0] * 10
# 线程锁
lock = Lock()
class Producer(Thread):
u"""生产者,依次往仓库里的十个槽位生产产品"""
def __init__(self):
super(Producer, self).__init__()
... |
a9785a89f9068f60c0bd6d745f5da67539c96d4c | devoncal77/FASHION | /gui/Utils.py | 1,327 | 3.65625 | 4 | from Tkinter import *
class AutoScrollbar(Scrollbar):
# a scrollbar that hides itself if it's not needed. only
# works if you use the grid geometry manager.
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
se... |
9ee2c7e4e8b520c97faf5a6e0c176c1732f991a2 | EharaProgramming/python_introduction | /4/4_1.py | 814 | 4.3125 | 4 | # リストの関数
list1 = ["Banana", "Apple", "Tomate", 4000]
print(list1)
# 要素の追加
list1.append("dddd")
print(list1)
# リストの結合 list += ["z","c","v","b"]
list1.extend(["z","c","v","b"])
print(list1)
# 指定した場所に要素を挿入
list1.insert(4, "n")
print(list1)
# 要素の削除 関数ではない
del list1[4]
print(list1)
# 要素の削除 値指定
lis... |
a41f693540a8e551d59dc79c64619b7f56220c31 | EharaProgramming/python_introduction | /10/10.py | 406 | 4.21875 | 4 | # イテレータ
# まずはリストの確認
list = [1, 2, 3, 4, 5]
for i in list :
if i < 3 :
print(i)
elif i == 3 :
print(i)
break
for i in list :
print(i)
# リストからイテレータを生成
it = iter(list)
for i in it :
if i < 3 :
print(i)
elif i == 3 :
print(i)
break
... |
ff6a155ec9e76ad970a15c602f83e3545c97e87f | EharaProgramming/python_introduction | /3/3_2.py | 651 | 4.09375 | 4 | #elif else
a = 5
b = 5
if a <= b :
print("a は b 以下")
elif a >= b :
print("a は b 以上")
else :
print("どちらでもないよ")
# if a <= b :
# print("a は b 以下")
# if a >= b :
# print("a は b 以上")
# 入力してもらう
bmi = int(input())
if bmi < 18 :
print("もっとごはん食べて!")
elif bmi <= 25 :
print("標... |
5264cd0430732ec72c6dd40202da4702cf786a94 | Narvaez0993/producto | /punto2.py | 164 | 3.65625 | 4 | #Generar una lista con los 10 primeros de la siguiente sucesión: 7,11,15,19,23…
"""numero = 7
for i in range(10):
print(numero)
numero = numero + 4""" |
f446c8bc2c2e0d758915affeee9057348a7d2588 | karrupt/Basics-of-Python-Image-Library | /hands_on_PIL.py | 2,630 | 3.9375 | 4 | #HANDS-ON PIL (Python Image Library, aka pillow)
from PIL import Image, ImageDraw, ImageFont
#create a new image
size = 500,300 #w,h
bg_color = 242,247,151
canvas = Image.new('RGB', size, bg_color)
#get the drawing pen for the canvas
pen = ImageDraw.Draw(canvas)
#dimension
dim = (50,50), (450,250) #x1y1, x2y2
dim2 =... |
bde72147f0609811ecca5e12bd8a2b56f1c8d06f | kaliadevansh/data-structures-and-algorithms | /data_structures_and_algorithms/challenges/array_reverse/array_reverse.py | 2,916 | 4.53125 | 5 | """
Reverses input array/list in the order of insertion.
"""
def reverseArray(input_list):
"""
Reverses the input array/list in the order of insertion.
This method reverses the list by iterating half of the list and without using additional space.
:param input_list: The list to be reversed. Returns No... |
dee9aa10abe79a67ab1863b4b6543bb0eae257b1 | FarmCodeGary/PyEvoSim | /src/utils/pygameutils.py | 8,751 | 3.515625 | 4 | '''
This module provides miscellaneous tools for use with pygame.
Created on Sep 28, 2011
@author: garrison
'''
import pygame as _pygame
from coords import Coords
def mouseButtonName(buttonNum):
"""
Returns the name of the given mouse button number. (This is intended to be
used with the "button" or "but... |
e50d57019354f864843163e06037a3734e59d8f4 | Wu-Xiang123/FastMaxFlow | /congestion_approx.py | 1,090 | 3.75 | 4 |
# A congestion approximator represents (abstractly) a matrix R such that:
# ||Rb||_inf <= opt(b) <= alpha ||Rb||_inf
# IE, it hits node demand vectors, b, and gives an estimation of the congestion
# incurred along some subset of edges within some factor alpha.
class CongestionApprox:
# For a congestion approxima... |
62d98ccd4b772bc826540333d5565195becbb6a0 | aowashim/python-programs | /fibonacci.py | 217 | 4 | 4 | num = int(input("Enter your nuber : "))
lst = [0, 1]
for i in range(2, num+1):
n_no = lst[i-1] + lst[i-2]
if n_no > num:
break
lst.append(n_no)
print(f"The fibonacci series upto {num} is : {lst}")
|
0264462beebe9d06dc2990285df762a2a38dfb32 | aowashim/python-programs | /bubbleSort.py | 522 | 4.09375 | 4 | # bubble sort function
def bubbleSort(arr, size):
for i in range(size - 1):
flag = 1
for j in range(size - 1 - i):
# swap the values if arr[j] > arr[j + 1]
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
flag = 0
if fla... |
bb720751c62379ec04581ce06ee143da53d99d14 | MouDas/PythonFoundations | /miniproject_shapes.py | 1,453 | 3.859375 | 4 | import turtle
def draw_triangle(some_turtle):
some_turtle.left(35)
some_turtle.forward(50)
some_turtle.right(35)
some_turtle.forward(50)
some_turtle.right(145)
some_turtle.forward(50)
some_turtle.right(35)
some_turtle.forward(50)
some_turtle.right... |
a41a499a78fc0dc44174812b5b3b7db1e12239b3 | FranVeiga/games | /Sudoku_dep/createSudokuBoard.py | 1,654 | 4.125 | 4 | '''
This creates an array of numbers for the main script to interpret as a sudoku board.
It takes input of an 81 character long string with each character being a number and
converts those numbers into a two dimensional array.
It has a board_list parameter which is a .txt file containing the sudoku boar... |
d4114840d285bbe77c3ae7dd5417b7f5a170ae3d | Alieinstein2008/Throwing-Dice_Jogo-de-dados | /Codigo.py | 644 | 3.59375 | 4 | import random as rd
from os import system
import time
user_move = input('Jogar o dado? (S/n)').upper()
def roll_the_dice(user_move):
while True:
if user_move == 'S':
random_number = rd.randrange(1,7)
print('O dado girou e girou e parou no numero:{}'.format(random_number))
... |
5e88af71d6a60b06c8afbbc35936d8d0f24a836b | gopricy/HelpMeOut | /session.py | 9,408 | 3.5625 | 4 | import math
import random
feedback_map = ["Punishment", "Nothing", "Praise"]
# the student's status at time t
class Emotion:
# 0 - 1 elemental
def __init__(self):
self.anger = 0
self.contempt = 0
self.disgust = 0
self.fear = 0
self.happiness = 0
self.sadness = 0
... |
f09d16aa3678919d67c0ae941221c9f41ccb7ec8 | dsukeeper/something | /cs50/pset6/credit.py | 1,001 | 3.59375 | 4 | import cs50
def get_num():
while True:
print("enter a cardnumber: ", end="")
num = cs50.get_string()
if num.isdigit():
return num
number = get_num()
leng = len(number)
summ=0
namecard = 0
if leng<13 or leng >16:
print("INVALID")
if number[0] == '3' and (number[1] == '4' o... |
785c1a17f7aa8f0dc00726e9f06acd9e29d30315 | Tigpan-Bytes/CTF-AI-BATTLE | /ADMIN,TEST/hackerBot.py | 1,347 | 3.625 | 4 | import random
import math
from class_data import *
class AI:
def __init__(self, index):
self.world = None
self.index = index
def update_tiles(self, food_changes, bee_changes, lost_hive_changes):
"""It is not recommended to change this function unless you are ABSOLUTELY sure you know w... |
50a57a4b60210a9436acd5fae4c81caf1909717a | Shilpa106/Todo-CLI | /cli_practice/datastructure/grid_city.py | 238 | 3.625 | 4 | # take a m*n grid(matrix) as input
# print the sum of all the elements,max,sum of left_diagonal
n,m=map(int, input().split())
matrix = []
for r in range(n):
row = list(map(int,input().split()))
matrix.append(row)
print(matrix)
|
91247cbf68c494ba465263ab304f68c120682898 | Shilpa106/Todo-CLI | /cli_practice/ex.py | 3,031 | 3.90625 | 4 | # fruits = ["apple","banana","cherry","kiwi","mango"]
# newlist = []
# for x in fruits:
# if "a" in x:
# newlist.append(x)
# # print(newlist)
# newlist1 = [x for x in fruits if "a" in x]
# print(newlist1)
# newlist = [x for x in fruits if x != "apple"]
# print(newlist)
# newlist = [x for x in... |
c54a2a2d4d19863203d7e7a3c11dd5b70e2b1e00 | Nilesh-Devda/PythonCode | /HelloWorld.py | 110 | 3.59375 | 4 | This is the "hello world" program in python.
print("Hello World!")
name = input()
print("My name is", name)
|
4f13a8a6b55cc8481e5b514d463dff3a38361d1d | Emceelamb/eroft | /mindful-computing/mindful-computing.py | 1,562 | 3.5625 | 4 | from blessings import Terminal
import datetime
from time import sleep
import os
t = Terminal()
height = t.height
width = t.width
def tod():
currentTime = datetime.datetime.now()
if currentTime.hour < 12:
return "morning"
elif currentTime.hour < 18:
return "afternoon"
else:
retu... |
8a97c5b089446b6bf6c6675b2287fc17636fc8d1 | AndresFWilT/MisionTIC-2022_C1 | /venv/Scripts/perreo_cosmico.py | 1,950 | 3.78125 | 4 | ##Libreria para el reto 5
def tipo_melenudos(lista):
'''
:param lista: lista de alienigenas
:return lista sin repetir:
'''
l = [];
for elemento in lista:
if elemento not in l:
l.append(elemento);
return l;
def si_son(turno,alien,validar):
'''
:param turno: turnos... |
fc6d4e396891c3d59e7adadcbabfd3a010e8c61f | AndresFWilT/MisionTIC-2022_C1 | /venv/Scripts/retos.py | 583 | 4 | 4 | ###IMPORTS
import random;
##Reto hola mundo
print("hola mundo");
##Reto operaciones con numeros
a = int(input("ingrese el numero a: "));
b = int(input("Ingrese el numero b: "));
print("suma: "+str(a+b));
print("resta: "+str(a-b));
print("mult: "+str(a*b));
print("div: "+str(a/b));
##reto numero mayor
if(a>b):
prin... |
6e77ecc508b782c07e09962d0351bb08efa69786 | jorgeaninoc/CodingProblems | /133A - HQ9+.py | 91 | 3.828125 | 4 | l = raw_input()
if "H" in l or "Q" in l or "9" in l:
print("YES")
else:
print("NO") |
50afd475eb8da6e7a5ef222fd80ac73e79ff9693 | jorgeaninoc/CodingProblems | /ZeroMatrix.py | 435 | 3.71875 | 4 | def zeroMatrix(matrix):
positions = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
positions.append((i,j,len(matrix),len(matrix[i])))
for i,j,r,c in positions:
for x in range(c):
matrix[i][x] = 0
for y in... |
5ed10909f7de7a90549c62ff22eb53ff55085614 | bogus-py/misc | /python-snippets/iterable-object.py | 288 | 3.734375 | 4 | #!/bin/env python
class itertest:
def __init__(self, n):
self.n = n
self.counter = 0
def __iter__(self):
return self
def next(self):
if self.counter <= self.n:
self.counter += 1
return self.counter
else:
raise StopIteration
a = itertest(5)
for x in a:
print x
|
d7a5bcf121a185f9f5f7a63b52a67d02259bc849 | neethucmohan/solutions | /chapter3/zip.py | 176 | 3.703125 | 4 | # Problem 11
def zipfil(fname,f):
z=ZipFile(fname,"w")
for i in f:
z.write(i)
print "zip file created"
import sys
from zipfile import *
zipfil(sys.argv[1],sys.argv[2:])
|
0a9dcc5147de5a0f0b3118d39779b2af5ace9275 | neethucmohan/solutions | /chapter2/reverse.py | 183 | 3.953125 | 4 | # Problem 6
def reverse(list):
l=len(list)
s=l
newlist=[None]*l
for i in list:
s=s-1
newlist[s]=i
return newlist
print reverse([1,2,3,4])
print reverse(reverse([1,2,3,4]))
|
90f733816530430ada007dab313d6c12d644b40a | neethucmohan/solutions | /zip.py | 201 | 3.734375 | 4 | # Problem 24
def zip(a,b):
lb=len(b)
i=0
nlist=[None]*lb
list=[(x,y) for x in a for y in b]
k=0
while i<lb:
nlist[i]=list[k]
i=i+1
k=k+lb+1
return nlist
print zip([1,2,3],["a","b","c"])
|
519eece072046eefca08080d5fe0ad391503080e | sooryanivedhaashokan/Quick-Trip-planning-Assistant | /mysite/kunju/tests/test_weather.py | 1,377 | 4 | 4 | """
We cannot use assert statements here, since the weather summary is not constant everyday
If the output of running this test is
Example Output:
Minimum, Maximum and summary of Temperature on each day is MIN: 63.11 MAX: 63.11 Summary: Partly cloudy throughout the day.
Minimum, Maximum and summary of Temperature on... |
16d33ebc8a54c6c6e73862b14a4010bb11ceb37a | superwenqistyle/1803 | /12day/名品测试系统.py | 1,293 | 3.75 | 4 | print("名片v1.0测试系统".center(60,"*"))
print("名片系统功能".center(60,"*"))
print(" 1.新增名片 ".center(60,"*"))
print(" 2.查找名片 ".center(60,"*"))
print(" 3.修改名片 ".center(60,"*"))
print(" 4.删除名片 ".center(60,"*"))
print(" 5.遍历名片 ".center(60,"*"))
print(" 6.退出名片 ".center(60,"*"))
cards=[] #名片库
while True:
function = int(input("选择要执行的... |
26642bb7250f18aff7f9a14f168baef5fed0d797 | superwenqistyle/1803 | /07day/6.py | 435 | 3.96875 | 4 | height = float(input("请输入身高"))
shenjia = float(input("请输入身价"))
yanzhi = float(input("请输入颜值"))
if height > 180 and shenjia > 1000000 and yanzhi > 90:
print("高富帅哥")
elif height < 180 and shenjia > 1000000 and yanzhi > 90:
print("富帅")
elif height < 180 and shenjia < 1000000 and yanzhi >90:
print("帅")
elif heig... |
08a6c9b6b1a9260cac4bfd44f5e6bafd62850c91 | superwenqistyle/1803 | /14day/5.py | 57 | 3.734375 | 4 | list=[1,2,3,4,5,6,7,8]
for i in list:
type(i)
print(i)
|
c24f36e82251ff9f3f675a2d2ff789b49f3f66ea | superwenqistyle/1803 | /07day/计算器.py | 230 | 3.875 | 4 | x = int(input("请输入数字"))
y = int(input("请输入数字"))
tar = input("请输入运算符号")
if tar == "+":
print(x+y)
elif tar== "-":
print(x-y)
elif tar== "*":
print(x*y)
elif tar == "/":
print(x/y)
|
b4404e85e08118d228cf5e67e2e7eebb9538a26d | superwenqistyle/1803 | /09day/等腰三角星.py | 121 | 3.75 | 4 | l = 1
n = int(input("请输入数字"))
while l < n:
print(" "*(n-l),end = "")
print("*"*(2*l-1))
l += 1
|
885acba642656109f5594a7d617995107e73be66 | superwenqistyle/1803 | /09day/清明.py/1小明.py | 514 | 3.5625 | 4 | d = int(input("请输入每天的距离"))
t = int(input("请输入每月的天数"))
sum = 0
for i in range(1,2*t): #while i <= 2*t:
if d <= 6:
m = 3
elif d > 6 and d <=12:
m = 4
elif d > 12 and d <= 22:
m = 5
elif d >22 and d <=32:
m = 6
else:
if (d-32)%20 == 0:
m = int((d-32)/20) + 6
else:
m = int((d-32)/20) + 7
if sum > ... |
2c27c4f287ccb54809bc69131ca83db6205a5ac5 | superwenqistyle/1803 | /08day/奇偶条件.py | 103 | 3.90625 | 4 | number = int(input("请输入数字"))
if number%2 == 1:
print("奇数")
else:
print("偶数")
|
6934ef21086c77c3c247c31cbf487a526c5c30b8 | junnhssn/Python-Projects | /S01Q01.py | 149 | 3.703125 | 4 | def user_name():
res = input("Enter your name : ")
return res
#main starts from here
name = user_name()
print("Hello", name)
|
036729670b8b2fe48e3abfaed14fa683ca42c7f4 | dahem/handbook | /uri/ad-hoc/1087.py | 368 | 3.53125 | 4 | def run():
x1, y1, x2, y2 = map(int, input().split())
if x1 == 0:
raise Exception()
if x1 == x2 and y1 == y2:
print(0)
return
if x1 == x2 or y1 == y2:
print(1)
return
if abs(x2 - x1) == abs(y2 - y1):
print(1)
return
print(2)
while True:
... |
549637de8d85c87fd2bc424d976dab159333dd0e | dahem/handbook | /uri/beginner/2554.py | 500 | 3.75 | 4 | def by_day(date):
day, month, year = map(int, date.split('/'))
return day + month * 12 + year * 365
def run():
n, m = map(int, input().split())
sol = []
for i in range(m):
arr = input().split()
pos = [int(x) for x in arr[1:]]
if sum(pos) == n:
sol.append(arr[0])... |
3f2b832e983afc34664b33e5937e63f93b42e1cd | dahem/handbook | /uri/beginner/2712.py | 529 | 4 | 4 | import re
n = int(input())
for x in range(n):
cad = input()
if re.match("^[A-Z]{3}-[0-9]{4}$", cad):
if cad[-1] == '1' or cad[-1] == '2':
print("MONDAY")
elif cad[-1] == '3' or cad[-1] == '4':
print("TUESDAY")
elif cad[-1] == '5' or cad[-1] == '6':
... |
eab948a536e8ed2f6cfa031d928cb9cd3e6589a9 | dahem/handbook | /uri/beginner/1066.py | 347 | 3.515625 | 4 | c = 0
d = 0
e = 0
f = 0
for x in range(5):
a = float(input())
if a % 2 == 0:
c += 1
if a % 2 == 1:
d += 1
if a > 0:
e += 1
if a < 0:
f += 1
print(c, "valor(es) par(es)")
print(d, "valor(es) impar(es)")
print(e, "valor(es) positivo(s)")
print(f, "valor(es) negativo(s)... |
67197798b979d852fb222a2302b986d3c30d7953 | westleft/Decorator | /decorator.py | 273 | 3.828125 | 4 | x = int(input('請輸入分子'))
y = int(input('請輸入分母'))
def zero(func):
def wrap(n, d):
if d == 0 :
return 0
else:
return n / d
return wrap
@zero
def divide(n, d):
return int(n / d)
print(divide(x,y)) |
f77e34657656c09ead24a320137cd757e21b27b1 | wlane/autoops | /foundations/diff-simple.py | 861 | 3.640625 | 4 | # This Python file uses the following encoding: utf-8
#比较两个文件内容的差异
import difflib
import sys
try:
textfile1=sys.argv[1]
textfile2=sys.argv[2]
except Exception,e:
print "ERROR:"+str(e)
print "Usage: python diff-simple.py filename1 filename2 > result.html"
sys.exit()
def readfile(filename):
try:... |
7d3f2ffb31bd0de1bba24f8888cb9ec5ed36e2cf | codenigma1/Tkinter_GUI | /tk_fileDialog_13.py | 955 | 3.5625 | 4 | from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
root = Tk()
root.title('Practice Window')
root.iconbitmap('D:/Vaibhav/TKinter Project/app/favicon.ico')
# initialdir set none it will open default directory
# It returns a path
# root.filename = filedialog.askopenfilename(initialdir... |
c4956c6cf2abc52ac8365712c8e82fad9b502773 | codenigma1/Tkinter_GUI | /tk_msgbox_11.py | 1,363 | 3.515625 | 4 | from tkinter import *
from PIL import ImageTk, Image
from tkinter import messagebox
root = Tk()
root.title('Practice Window')
root.iconbitmap('D:/Vaibhav/TKinter Project/app/favicon.ico')
# askyesno
def popup6():
response = messagebox.askyesno("This is my Popup!", "Hello World!")
Label(root, text = response).pack()... |
38ce7d1a6dece47b2ec383bb0f963d7a3fa2bdd2 | plaidlemming/Assignment1 | /Code/agentframework.py | 3,870 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 2 11:47:57 2021
@author: Eliza
"""
# Import required libraries.
import random
# Create "Agent" class.
class Agent():
# Set up class constructor, to deal with the "environment" and "agents" lists.
def __init__(self, environment, agents):
self.y = ra... |
53c83b42f6a8ea87af0d4ae7a6549e667720f0db | AnetkaC/learning-git | /Init project.py | 489 | 3.53125 | 4 | print("Lista zakupów".center(50, '='))
print()
shopping_list = ["chleb", "bułki", "pączek", "marchew", "seler", "rukola"]
shopping = {
"piekarnia": ["chleb", "bułki", "pączek"],
"warzywniak": ["marchew", "seler", "rukola"]
}
lenght = len(shopping_list)
for k, v in shopping.items():
print("Idę do " +... |
b1acafeca378a52e04c04b3935c2cf65a6c65445 | chengguobiao/SortAlgorithm | /SelectionSort.py | 1,466 | 4.28125 | 4 | #!usr/bin/env python
#-*- coding: utf-8 -*-
'''
名字:直接插入排序(选择排序)
思想:从所有序列中先找到最小的,然后放到第一个位置。之后再看剩余元素中最小的,放到第二个位置
直至排序结束,程序中首轮一般会选第一个元素作为最小值。
'''
import time
import random
def randomnumber_generate(total_num=100, max_num=1000):
num_list = []
n = 1 #得到1000以内的100个随机数
while n <= total_num:
lin... |
828066159ed3f735e0ea6b16ce8c81b23e62ff1d | DipeshDhandha07/Data-Structure | /infix to postfix2.py | 1,310 | 4.1875 | 4 | # The main function that converts given infix expression
# to postfix expression
def infixToPostfix(self, exp):
# Iterate over the expression for conversion
for i in exp:
# If the character is an operand,
# add it to output
if self.isOperand(i):
self.output.append(i... |
68126ba1dfff2afd32df34699f4a5961933ff8b7 | DipeshDhandha07/Data-Structure | /set.py | 2,063 | 4.09375 | 4 | #To create a set
set1=set()
set1.add("Dipesh")
set1.add("Harshit")
set1.add("Shubham")
set1.add("Ganesh")
set1.add("Aayush")
print(set1)
#To create two sets and find common names
set2=set()
set2.add("Dipesh")
set2.add("Harshit")
set2.add("Aayush")
print(set2)
set3=set()
set3.add("Dipesh")
set3.add("... |
b54045b242e6b27a8fa66acd13c3c8fa60d805f7 | neerajbardia/algorithms | /search/binary_search.py | 869 | 4.03125 | 4 | # binary search with comparison count
list_of_no=[]
flag=0
comparison_count=0
def binary_search(list_of_no, x):
min = 0
max = len(list_of_no) - 1
mid = 0
global comparison_count
while min <= max:
mid = (max + min) // 2
comparison_count+=1
if list_of_no[mid] < x:
... |
e5fa1fb66308690536dcb3ea0ca0ee494226c3a1 | kaushikamaravadi/Python_Practice | /DataStructures/queue.py | 917 | 4.09375 | 4 | class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def print(self):
... |
ca1ad7d1ad24c77156a97b54683f63dc205c2730 | kaushikamaravadi/Python_Practice | /Transcend/facade.py | 888 | 4.125 | 4 | """Facade Design Pattern"""
class Vehicle(object):
def __init__(self, type, make, model, color, year, miles):
self.type = type
self.make = make
self.model = model
self.color = color
self.year = year
self.miles = miles
def print(self):
print("vehicle ty... |
ff5ca971a1feac7ea7c26d34f8e3b63e4a4c2ea5 | kaushikamaravadi/Python_Practice | /DataStructures/linked_list.py | 2,244 | 4.1875 | 4 | """Linked List"""
class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_next(self, new_next):
self.next = new_next
class LinkedList(... |
98dbb8522901dbbc9af3fc2f30eecf2a88dce9b9 | toopazo/static_MT_BET_analysis | /python_code/eg_abstract.py | 1,252 | 4.125 | 4 | # Python program showing
# abstract base class work
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
def classname(self):
print('Base class method: type(self) %s ' % type(self))
class Triangle(Polygon):
def noofsides(self):
p... |
a80c87614a06de6b2c9b0293520196b93418e5ea | Rokesshwar/Coursera_IIPP | /miniproject/week 2_miniproject_3.py | 2,291 | 4.1875 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
# initialize global variables used in your code
range = 100
secret_num = 0
guesses_left = 0
# helper function to start... |
b20c926de5d3951d135cd7b7c97cb40db18c659b | pythonzhicheng/analysis-of-data | /day02--代码/07.切割.py | 291 | 3.5625 | 4 | import numpy as np
#切割数组
# 1.hsplit()和vsplit()
arr1 = np.array([[1,1,3,3],[2,2,4,4]])
print('arr1:\n',arr1)
arr6_subarray = np.hsplit(arr1,2)
print(arr6_subarray,type(arr6_subarray))
a1 = arr6_subarray[0]
print(type(a1))
arr7_subarray = np.vsplit(arr1,2)
print(arr7_subarray)
|
65b521fe10bca9b8e1200876453198811f2b243d | pythonzhicheng/analysis-of-data | /day03--代码/04.可视化基础.py | 997 | 3.578125 | 4 | # Matlab--
import matplotlib.pyplot as plt
import numpy as np
#创建画布
# F = plt.figure()#创建一个空白画布,可以指定画布的大小、像素
# F.add_subplot()#创建并选中子视图,可以指定子视图的行数、列数和选中图片的编号
# 案例:绘制直接y = 2*x+1
# x = np.linspace(-1,1,50)
# y = 2*x+1
# print(x,y)
#创建画布
# plt.figure()
#
# # plot(x,y)绘制曲线
# plt.plot(x,y)
#
# #保存成图片
# plt.savefig('img/案例... |
2f8f75664f8a9e4b291a1f8dcbff6fc106832019 | pythonzhicheng/analysis-of-data | /day02--代码/01.随机数.py | 839 | 3.796875 | 4 | import numpy as np
#1.生成随机数
# (1)random(n)函数
# 格式:np.random.random(n)
# 说明:生成一个数组,元素值域:[0,1),其中n表示个数
r1 = np.random.random(10)
print(r1)
#(2)rand()
# np.random.rand(m,n,....)
# 说明:生成一个M x N x ...维的数组,元素值域:[0,1)
r2 = np.random.rand(3,4,5)
print(r2)
#(3)randn()
# 说明:生成数组,数组元素为正态随机数
r3 = np.random.randn(10000)#生成1000个随机... |
316f2609242d4eda77c3e44a70abe78b20bc2426 | asperaa/back_to_grind | /Trees/post_order_traversal_iterative.py | 751 | 3.59375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""145. Binary Tree Postorder Traversal [Iterative]
"""
class Solution:
def push_left_nodes(self, root, stack):
while root:
stack.append((root, False))
root = root.left
def pos... |
33dc4d63b9c275c7cb72739b75a7183755b037b1 | asperaa/back_to_grind | /array/125. Valid Palindrome.py | 682 | 3.8125 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""125. Valid Palindrome
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
... |
c4b1bf103a857f171fc1278872661d8af8dbc6ae | asperaa/back_to_grind | /Binary_Search/1095. Find in Mountain Array.py | 1,814 | 3.84375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""1095. Find in Mountain Array
"""
class Solution:
def findInMountainArray(self, target, mountain_arr):
length = mountain_arr.length()
left, right = 0, length - 1
max_element_index = -1
... |
662e783ac12e7058c6669a3236f06f380b8a8bae | asperaa/back_to_grind | /Linked_List/rotate_list.py | 1,619 | 4.0625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""61. Rotate List
"""
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, val):
... |
72e67f1d79d4469a9eb8afe64dbfc402148a7dab | asperaa/back_to_grind | /Binary_Search/34. Find First and Last Position of Element in Sorted Array_Template.py | 1,201 | 3.703125 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""34. Find First and Last Position of Element in Sorted Array [Template]
"""
class Solution:
def find_left_boundry(self, nums, target):
left, right = 0, len(nums) - 1
while left < right:
mi... |
52d8f0071c056dcbab445e05ae84b4863fe78ed3 | asperaa/back_to_grind | /DP/403. Frog Jump_Quadratic.py | 838 | 3.53125 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through
"""
"""403. Frog Jump [Space and Time - O(n2)]
"""
class Solution:
def canCross(self, stones):
if stones[1] != 1:
return False
cache = {}
for stone in stones:
cache[stone... |
e2e7728332d884a0357dedddc662efc9a9fd03a9 | asperaa/back_to_grind | /DP/474. Ones and Zeroes.py | 1,070 | 3.59375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through."""
"""474. Ones and Zeroes [Naive]
"""
class Solution:
def findMaxFormHelper(self, zeroes_and_ones, zeroes, ones, n):
if n == 0:
return 0
if zeroes >= zeroes_and_ones[n-1][0] and ones >= ze... |
03f31905ee6dcf6f15a0eb6077b7009954062aaa | asperaa/back_to_grind | /Linked_List/remove_duplicates_from _sorted_lists_2.py | 1,250 | 3.78125 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""82. Remove Duplicates from Sorted List II
"""
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
d... |
44fde8c662c32f7cb83285804164dfe88a4261db | asperaa/back_to_grind | /Trees/LCA_in_BST.py | 742 | 3.625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""235. Lowest Common Ancestor of a Binary Search Tree [Recursive] T - O(h) and S - O(h)
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class S... |
eed3afbb97e48fae80a14a977c246d46fc89030a | asperaa/back_to_grind | /Binary_Search/374. Guess Number Higher or Lower.py | 528 | 3.546875 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""374. Guess Number Higher or Lower
"""
def guess(num):
pass
class Solution:
def guessNumber(self, n):
left, right = 0, n
while left <= right:
mid = left + (right - left) // 2
... |
ee945326827a65692f738dce88072c076ab1042c | asperaa/back_to_grind | /bactracking/39. Combination Sum.py | 713 | 3.59375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""39. Combination Sum
"""
class Solution:
def combinationSum(self, nums, target):
n = len(nums)
self.total_length = n
self.ans = []
self.target = target
self.helper(nums, [... |
2a0cc124faa866da992b4524fa9cb4c4c3403cf4 | asperaa/back_to_grind | /Graphs/207. Course Schedule.py | 1,091 | 3.59375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""207. Course Schedule
"""
class Solution:
def canFinish(self, n, edges):
visited = [False] * n
rec_stack = [False] * n
graph = {i: [] for i in range(n)}
ordering = [-1] * n
... |
d03e68ae42ce8872a11fe82c02706b94956b897a | asperaa/back_to_grind | /Trees/701. Insert into a Binary Search Tree_iterative.py | 811 | 3.84375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""701. Insert into a Binary Search Tree [Iterative]
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def insertIntoBST(self,... |
31a053b4a741f46861b7d1106093da0822c87496 | asperaa/back_to_grind | /Graphs/785. Is Graph Bipartite?.py | 814 | 3.53125 | 4 | """We are the captains of ships, and we stay 'till the end. We see our stories through.
"""
"""785. Is Graph Bipartite?
"""
class Solution:
def isBipartite(self, graph):
n = len(graph)
visited = [False] * n
color = [False] * n
self.is_same = False
def dfs(i):
... |
eecb784fc4e3a8cb01995068e064468cbe4f2ad8 | asperaa/back_to_grind | /bactracking/1079. Letter Tile Possibilities.py | 852 | 3.5625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""1079. Letter Tile Possibilities
"""
class Solution:
def numTilePossibilities(self, s):
n = len(s)
s = sorted(s)
self.total_length = n
self.ans = 0
visited = [False for i in r... |
ae43bf350715fa72c2c95d37ab2c2104400a9a9c | asperaa/back_to_grind | /Trees/longest_univalue_path_clean.py | 862 | 3.515625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""687. Longest Univalue Path
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def dfs(self, root):
if not root:
... |
f687b64bcb793d69e5b48e8f6ecc87667bc2eb65 | asperaa/back_to_grind | /bactracking/47. Permutations II.py | 933 | 3.6875 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""47. Permutations II
"""
class Solution:
def permuteUnique(self, nums):
n = len(nums)
self.total_length = n
if not nums:
return []
self.ans = []
visited = [Fal... |
41bbb461b7ce47ab55f1b1a7eff3b1de367b2bca | asperaa/back_to_grind | /DP/213. House Robber II.py | 583 | 3.65625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""213. House Robber II
"""
class Solution:
def rob_helper(self, nums):
if not nums:
return 0
n = len(nums)
dp = [0 for _ in range(n+1)]
dp[1] = nums[0]
for i in ran... |
d40fe25d7ba3e8e78e35176b949e7a7b09febedc | asperaa/back_to_grind | /DP/0_1_Knapsack | DP 10.py | 880 | 4.1875 | 4 | """We are the captains of our ships and we stay 'till the end. We see our stories through.
"""
"""https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem/0
[Naive Recursion]
"""
def knapsack(weight, value, capacity):
number_of_items = len(weight)
return knapsack_helper(number_of_items-1, 0, weigh... |
da32f772cc519a171c2557b75fdd9ad48ab75b45 | asperaa/back_to_grind | /DP/656. Coin Path_Top_Down.py | 1,131 | 3.703125 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""656. Coin Path [Top Down]
"""
class Solution:
def cheapestJump(self, coins, k):
n = len(coins)
result = []
dp = [None] * n
next_arr = [-1 for _ in range(n)]
self.jump_hel... |
3bf4fb60abde48daeb16f392763e8a6830213ec4 | asperaa/back_to_grind | /Trees/leaf_similar_trees.py | 700 | 3.59375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""872. Leaf-Similar Trees [T - O(n1 + n2) and S - O(n1+n2)]
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def dfs(self, r... |
4e9e17012e6ce4e686890e24fd35558b0b44a606 | asperaa/back_to_grind | /DP/GFG. Minimum_Sum_Partition_Top_Down.py | 954 | 3.828125 | 4 | """We are the captains of our ships, and we stauy 'till the end. We see our stories through.
"""
"""https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0
[Top Down]
"""
def min_sum_partition_helper(nums, dp, n, curr_sum, total_sum):
if dp[n][curr_sum]:
return dp[n][curr_sum]
if n == 0:
... |
79daa413b3f273170ae2270d63b40ebcaaafd070 | asperaa/back_to_grind | /Trees/814. Binary Tree Pruning.py | 756 | 3.65625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""814. Binary Tree Pruning
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def pruneTree(self, root):
if not root:
... |
be196337e48b760eef2dceb8c3cfd8b22626cf54 | asperaa/back_to_grind | /Graphs/947. Most Stones Removed with Same Row or Column.py | 851 | 3.765625 | 4 | """We are the captains of our ships, an we stay 'till the end. We see our stories through.
"""
"""947. Most Stones Removed with Same Row or Column
"""
class Solution:
def removeStones(self, stones):
visited = {tuple(stone): False for stone in stones}
def dfs(s1, visited):
... |
e2254d357afebaf78c97ce440405f86aacc9c67d | asperaa/back_to_grind | /Trees/invert_tree.py | 532 | 3.71875 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""226. Invert Binary Tree
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def invertTree(self, root):
if not root:
... |
3d7ebe3eade134ff4c2baee8ccf8ff8ff1c0d8cd | asperaa/back_to_grind | /Graphs/802. Find Eventual Safe States.py | 751 | 3.578125 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""802. Find Eventual Safe States
"""
class Solution:
def eventualSafeNodes(self, graph):
n = len(graph)
visited = [0] * n
def dfs(i):
if visited[i] == 1:
return Tr... |
e7f176d08a086c248ac4b237227423ee497692f8 | asperaa/back_to_grind | /Binary_Search/1283. Find the Smallest Divisor Given a Threshold.py | 844 | 3.890625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""1283. Find the Smallest Divisor Given a Threshold
"""
class Solution:
def is_valid(self, nums, threshold, divisor):
sum_of_quotients = 0
for i in range(nums):
sum_of_quotients += (nums[i... |
d6984cbd8267a3fde1fabefea909c3088f1e4a5d | asperaa/back_to_grind | /array/1365. How Many Numbers Are Smaller Than the Current Number.py | 613 | 3.84375 | 4 | """We are the captains of our ships, and we stay through the end. We see our stories through.
"""
"""1365. How Many Numbers Are Smaller Than the Current Number
"""
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]):
sorted_nums = sorted(nums)
smaller_count = {}
for i in ... |
54cd364a2683c83692c8e220bc929aeedbc40f46 | asperaa/back_to_grind | /Graphs/323. Number of Connected Components in an Undirected Graph_BFS.py | 977 | 3.546875 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""323. Number of Connected Components in an Undirected Graph [BFS]
"""
from collections import deque
class Solution:
def countComponents(self, n, edges):
visited = [False for _ in range(n)]
graph = {... |
367a9ee80355f1ad33684d281cf1d7623d8e44ed | asperaa/back_to_grind | /Binary_Search/1482. Minimum Number of Days to Make m Bouquets_Template.py | 949 | 3.5625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""1482. Minimum Number of Days to Make m Bouquets
"""
class Solution:
def minDays(self, nums: List[int], m: int, k: int) -> int:
left, right = 1, max(nums)
if len(nums) < m*k:
return -1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.