blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ffb5a52e1df9a118ce17553b7d97dc27cdf2745a
quadrant26/python
/Tkinter/test_tk2.py
668
3.796875
4
''' TKinter ''' import tkinter as tk class App: def __init__(self, master): frame = tk.Frame(master) # side = tk.LEFT 设置位置 # padx 边距 # pady 边距 frame.pack(side=tk.LEFT, padx=10, pady=10) ''' tk.Button(frame, text=按钮内容, fg...
d543b74cc6654bc83ed0c1478a394755dd82be45
quadrant26/python
/function/hanruota.py
525
3.59375
4
def power(x,y): if y == 1: return x else: return x * power(x, y-1) print( power(2, 4) ) def gcd(x, y): t = x % y x = y y = t return gcd(x, y) print() def hanoi(n, x, y, z): if n == 1: print(x, '-->', z) else: hanoi(n-1, x, z, y)# 将前 n-1 个盘子从 x 移动到 y...
b6f19799e2f55e5440cdd0ae60b431f78c750d6c
quadrant26/python
/Tkinter/test_canvas4.py
303
3.53125
4
from tkinter import * root = Tk() w = Canvas(root, width=200, height=100) w.pack() rect1 = w.create_rectangle(40, 20, 160, 80, dash=(4, 4)) arc = w.create_oval(40, 20, 160, 80, fill="pink") t = w.create_text(100, 50, text="python") arc = w.create_oval(70, 20, 130, 80, fill="green") root.mainloop()
d7d634fc982b31e8f27db1abf6b325c7aa9e93cb
quadrant26/python
/magic/m_ex_51.py
495
4.03125
4
# 访问的属性不存在时 class Demo: def __getattr__(self, name): return "该属性不存在" # 编写一个 Demo 可以获取 和 赋值 class Demo2: ''' def __init__(self): self.x = "king" def __getattr__(self, name): return super().__getattr__(name) def __setattr__(self, name, value): return supe...
599f48abc7df997d1ba89b1ef0dd810a43956624
quadrant26/python
/Tkinter/test_PanedWindow.py
233
4.03125
4
''' Tk PanedWinow ''' from tkinter import * m = PanedWindow(orient=VERTICAL) m.pack(fill=BOTH, expand=1) top = Label(m, text="top paned") m.add(top) bottom = Label(m, text="bottom pane") m.add(bottom) mainloop()
b3e0a664fd7178645b5acc2b0e8477b4ddd99f3b
quadrant26/python
/function/fn5.py
1,334
3.953125
4
# 内置函数 和 闭包 count = 5 def myfun(): count = 10 print(count) myfun() print(count) # global 将变量提升为 全局变量 def myfun1(): global count count = 15 myfun1() print(count) def fun1(): print("fun1() 正在被调用") def fun2(): print("fun2() 正在被调用") fun2() fun1() def funx(x): def funy(y): ...
c14af5dc28ce1aee3470e0f9d1d8b4544e412990
phibzy/Contests
/Leetcode/May20/240520/pseudoPalindrome.py
2,101
3.84375
4
#!/usr/bin/python3 import logging import pdb logging.basicConfig(level=logging.DEBUG, format="%(levelname)s - %(msg)s") # 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 # Sp...
a043c67b1abf2335022278ef39bcd549f0d4fcec
phibzy/Contests
/Leetcode/Jun20/140620/runningSum.py
444
3.84375
4
#!/usr/bin/python3 """ Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. """ class Solution: def runningSum(self, nums: List[int]) -> List[int]: total = 0 rList = list() for i in range(len(nums)): ...
e3aa77d1f0022f58f42d2bca2554305a11acc9b1
phibzy/Contests
/Leetcode/Jun20/140620/minimumDaysBouquets.py
468
3.984375
4
#!/usr/bin/python3 """ Given an integer array bloomDay, an integer m and an integer k. We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return...
c440e76591b4a0254094424cf57917b07f6afa92
mingqin-joy/python-crash-course
/PythonCrashCourse/Chapter08/formatted_name.py
626
3.796875
4
def get_formatted_name(first_name, last_name, middle_name=''): if middle_name: full_name = first_name + " " + middle_name + " " + last_name else: full_name = first_name + " " + last_name return full_name.title() def get_formatted_name2(first_name, last_name, middle_name=''): if middle_...
ce13d8ced080d306c7959d9f08de7c70647252a3
mingqin-joy/python-crash-course
/PythonCrashCourse/Chapter03/motorcycles.py
1,677
4.03125
4
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) motorcycles.append('haha') print(motorcycles) bicycles = [] bicycles.append('honda') bicycles.append("yamaha") bicycles.append('suzuki') print(bicycles) bicycles.insert(0, 'ducati') print(bicycles) del bicycles[0...
67083a059aad582a75c21362bc03135a9c8aba0a
zxcvbnm123xy/leon_python
/python1808real/day11/day11-1-object.py
13,277
4.28125
4
""" 第十章 面向对象的特征 二、封装、继承和多态 1、封装 """ # 2). propery # 为了调用者方便调用私有成员 # 两种方式: # (1)property函数 # (2)property装饰器 # (1)property函数 class Computer: def __init__(self): self.__memory="128g" self.cpu="intel5" def setmemory(self,memory): self.__memory=memory def getmemory(self): ...
7390b03026d8cd282298c1a551b41b63b4291a15
zxcvbnm123xy/leon_python
/python1808real/day11/day11-2-model.py
4,519
3.9375
4
""" 第十一章 模块和包 """ # 一、模块 # 1.模块的基本定义 # 模块的定义:一个py文件就是一个模块。————物理的角度 # 模块中包含:定义的语句(类、函数、变量) # 模块在内存中存储的名字就是py文件的文件名。 # 为什么划分模块? # 代码太多,不能都存在在一个文件中;会出现名称冲突 # 划分模块之后的好处: # 1. 定义模块有利于将项目按照功能进行划分,方便协作开发 # 2. 模块提供了独立的命名空间(全局命名空间),解决了命名冲突问题 # 3. 模块可以供多个人使用,提高了程序的复用性。 # 2.模块的使用 # 模块和模块之间的访问:通过导入 # (1)使用import导入 # 导入模块的格式:impo...
f3342e12d97f67dc4913c2d063a9a26bded0f4e2
zxcvbnm123xy/leon_python
/python1808/day9/day8homework.py
1,383
4.0625
4
# 1. # 编写程序,将字典中的键与值互换。 d = {1: "one", 2: "two"} # 字典创建的方式{键:值,} # 对字典进行追加元素 # 字典[key]=value d_new={} print(len(d_new)) for k,v in d.items(): d_new[v]=k print(d_new) # # 2. # 元组是否可以总是可以作为字典的键值? # 元组的元素只有不可变类型时,可以作为字典的key # 如果包含可变类型,则不能作为字典的key t=(1,2,3) # t=(1,2,3,[4]) x={t:"dddd"} print(x,type(x)) # # # 3. # ...
7d8706f262ee14466f0ff7ba10b8315e6965c3d1
zxcvbnm123xy/leon_python
/python1808real/day13/day13-1-exception.py
11,907
3.828125
4
""" 第十二章 错误和异常 """ # 问题归结为两种: # (1)错误:出现在编译期的问题 # (2)异常:出现在执行期的问题 # 在python中对错误和异常都使用异常对象来进行处理。 # 一、异常的相关概念 # 当python解释器遇见异常的时候,会出现异常的位置产生一个【异常类型】的对象. # 当发生异常之后,程序不会马上停止,而是“暂停”,程序会从上下文中查找有没有【异常处理的程序】 # 如果有异常处理的程序,则会走异常处理 # 如果没有异常处理的程序,异常会【向上传播】,一直到走到Python解释器都没有处理,程序才会真正的终止 # 在控制台抛出异常。 # 【异常类型】:处理异常的异常类。 # 【异常处理的程序...
6b11d854568bac16f4eea27c88cbca22e2c74f07
zxcvbnm123xy/leon_python
/python1808/day3/day3-1-oper.py
6,807
4.09375
4
""" 第三章 运算符 运算符:就是有特殊计算规则的符号 操作数:参与运算的数据 运算符可以根据操作数的不同,分为N元运算符 """ # 1+2 二元运算符 # a-b # -1 一元运算符 # 运算符和操作数结合起来,就是表达式 """ 1. 算数运算符 + - * / // 向下取整 % 取模 ** 求幂 """ a=21 b=10 print(a+b) print(a-b) print(a/b) print(a*b) # //向下取整,向负无穷大方向取整 # 做除法运算时,商向下取整 print(10//3) print(-10//3) # %取模 是数学意义上取余数 # 被除数 = 除数 * 商+余数 #...
98dd1f90e56c335a3b957275db0304e86a697d9c
zxcvbnm123xy/leon_python
/python1808real/day14/day13homework.py
5,135
3.765625
4
# 1. # 编写程序,验证AttributeError的产生场合。下面两个都可以。 # 方式一: # class A: # pass # 类属性 # A.a # 实例属性,实例方法 # a=A() # a.b # a.c() # 方式二: # li=[1,2,3] # li.a # 当访问一个对象的时候,对象下没有指定的属性名 # (类属性、实例属性、类方法名、实例方法名、静态方法) # 2.# 输入一个日期,格式为年 / 月 / 日,如果格式正确, # 则返回该日期是当年的第几天,否则日期默认为今天,返回今天是当年的第几天。 def que2(): from datetime import dateti...
112d2477d3965bd704797f3f2b698b54ee286d30
zxcvbnm123xy/leon_python
/python1808real/day15/day15-1-file.py
12,280
3.65625
4
""" 第十四章 文件 """ # 一.文件 # 操作系统中,word文档,图片,音乐,视频,txt # 文件划分成两个类别: # (1)文本文件:.txt .bat # (2)二进制文件:除了文本文件以外都是二进制文件。 .doc # 无论文本文件还是二进制文件在计算机中真正的存储方式都是二进制。 # 二、python文件操作 # 1. 获取文件对象 # 在python中通过open函数来获取文件对象 # open(file,mode) # 【参数】 # file: 文件的路径。 # 相对路径:从当前的路径开始的路径 /a/b/c # 绝对路径: 以盘符开头的就是绝对路径 c:/a...
6de09ffdaccbe825d3d70f03f2cf9e5ebe6651fe
zxcvbnm123xy/leon_python
/python1808real/day1/day-1-base.py
7,788
3.671875
4
""" 第一章 python的入门 """ # 语言:人和人沟通的方式 # 计算机语言:人和计算机沟通的方式 # 利用计算机语言进行编程,让计算机按照人的指令工作。 """ 计算机语言按照级别分为: 机器语言:0 1 代码,高电位,低电位。 汇编语言:通过指令来编写的语言。add 2 3 高级语言: c c++ .net java python php """ """ 计算机语言的执行方式 编译执行:对于源文件,编译一次,编译成对应的二进制文件。 优点:速度快 缺点:可移植性差,对于同样的源文件来说,不同的操作系统编译出来的二进制文件不同。 例子:c c++...
c3b638c602413be4c54e9e7addbbe910e9db70fb
zxcvbnm123xy/leon_python
/python1808real/day15/day14homework.py
7,232
4.09375
4
# 1.是否所有的可迭代对象都是Iterable的实例呢? __getitem__ # from collections.abc import Iterable # import time # class I: # def __getitem__(self, item):# __getitem__跟目前使用__iter__和__next__放在一起使用很像 # # return item # item就是迭代对象的索引 # if item<100: # return item # else: # raise StopIterat...
cd144354e189c6f12227341da708233d8060b7d8
zxcvbnm123xy/leon_python
/python1808real/day13/day12homework.py
1,030
3.84375
4
# 1.使用random.random()函数实现返回[a, b]之间的整数。(a <=x<=b) randint(a,b) # # """ random.randomint(a,b) a<=x<=b random.random() 0<=x<1 [a,b] a,(b-a)+a #只要让你b-a是随机产生的 问题: 1.[a,b) 2.需要得到一个整数,目前是一个小数 (1)向上取整 ceil a a+math.ceil(random.random()*(b-a)) a,b = 0,100 0 0.999*(100-0) 99.9-----100 ...
056d01c2be915345c840b1a11cc8a0f8e7894880
zxcvbnm123xy/leon_python
/python1808real/day2/day2-1-operator.py
5,745
3.953125
4
""" 第三章 运算符 运算符:具有特殊计算规则的符号 操作数:运算时,参数运算的数据 N元 运算符:具有N个操作数 由运算符和操作数结合起来的计算式,称为表达式 """ """ 算术运算符 比较运算符 逻辑运算符 位运算符 成员运算符 身份运算符 注意:有些资料比较运算符、成员运算符、身份运算符都看成是比较运算符 """ # 一、算术运算符 # + - * / a=18 b=6 print(a+b,a-b,a*b,a/b) # // 取整 python中是向下取整,向负无穷大方向取整。 print(-10//3) print(10//3) # % 取模:求余数 # 被除数=除数*商+余数 # 余数=被除数-除数*商 # 商...
4b1ef9590d2c6da476222843a9e1e73632aa7818
Aliena28898/Ollivander-s
/codigo_acceso_a_datos_Ollivander.py
2,832
3.703125
4
"""Estos dos primeros métiodos van a permitir abrir un fichero de texto y extraer de él los casos test en forma de matriz de 3 dimensiones [Primera dimensión: lista de los atributos del ítem. Segunda dimensión: lista de ítems de un día. Tercera dimensión: lista de listas de cada día. Los casos test están escritos en la...
9ee9defc15267f35b493b8ee350359dfde5d7dd0
hikeuchi/bmi-calculator
/After/user.py
1,466
4.0625
4
from __future__ import annotations # User.createで前方参照するのに必要 from dataclasses import dataclass def _calculate_bmi(weight: float, height: float) -> float: return round(weight / (height ** 2), 1) # 小数点以下1位で丸める def _get_bmi_result(bmi: float) -> str: if bmi < 18.5: result = "痩せ型" elif (bmi >= 18.5...
0e4576abfc481ac396e4544be2be06af970011c5
bc2009/Python
/MLDemo/StudyDemo/predict_hourse_price.py
670
3.625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 22 20:15:32 2016 @author: wang_wei52 """ import pandas as pd from sklearn import linear_model def get_data(filename): data = pd.read_csv(filename) x_parameter = [] y_parameter = [] for single_square_feet, single_price_value in zip(data['square_feet'], ...
754ff2b144d817b98af24c9ffa204cb510a822a3
Amareashwar/Computer-Science
/Python/python/pattern/number8.py
149
3.96875
4
n = int(input("Enter number ")) for i in range(1,n+1): for j in range(1,n+1): print(n+1-j,end = ' ') # i is column , j is row print()
8f75f1225938fa0474f1da9fcb8f1ddaf0029eb6
Amareashwar/Computer-Science
/Python/python/pattern/p3.py
109
3.921875
4
for i in range(5): print("*",end =" ") # this end = " " space is new line , by doing we blocking new line
3e5dfb7114a95a5982bd14f11c34e93cf2cb170c
TessCBear/100-Days-of-Code
/Beginner/Day 09/Day9.py
1,105
3.875
4
import os def cls(): os.system('cls' if os.name=='nt' else 'clear') print("Welcome to the Secret Auction \n" + ''' ___________ \ / )_______( |"""""""|_.-._,.---------.,_.-._ | ...
11d2454b42e4ea09eb0aa167b2c92b2c9f241d28
TessCBear/100-Days-of-Code
/Intermediate/Day 27/Day27.py
736
3.984375
4
import tkinter window = tkinter.Tk() window.title("Miles to Kilometers Converter") window.config(padx = 50, pady=50) input = tkinter.Entry() input.grid(column=1, row=0) miles_label = tkinter.Label(text = "Miles") miles_label.grid(column = 2, row=0) equal_label = tkinter.Label(text = "is equal to") equal_label.grid(...
d73e04c0e281533e793512e0dc54305b44ee96be
TessCBear/100-Days-of-Code
/Beginner/Day 04/Day4.py
2,609
3.796875
4
import random import Art print("Let's play rock (R), paper (P), scissors (Sc), lizard (L), spock (Sp)!") user_choice = input("What do you choose? \n") choices = ["R", "P", "Sc", "L", "Sp"] computer_choice = choices[random.randint(0,4)] if user_choice == "R": print("You chose \n" + Art.rock) elif user_choice == "...
c9f91898fb6aa1fd2940f8d2ab89a8a682ab48a4
Muthuanandavalli/beginnerset4
/no_of_special_char.py
108
3.546875
4
s=input() c=0 for d in range(0,len(s)): if s[d].isnumeric() or s[d].isalpha(): c=c+1 a=len(s)-c print(a)
90f666204604d59df438a2d71dbcfad9cea08849
13589080127/stt_project
/test/xt16_1.py
3,388
3.890625
4
# -*- coding: utf-8 -*- # 读写文件 from sys import argv #从sys代码库中导入argv这个方法 script, filename = argv #将argv这个方法进行解包,解包得到script, filename两个变量 #print "We're going to erase %r." % filename #####打开一个存在的文件 #打印“”, % filename 进行替换%r #print "If you don't want that, hit CTRL-C (^C)." #####hit CTRL-C (^C)在这里只是做...
3a6273dd624f4b473492a9553abfee4a10682dc1
PRATHAM1ST/Python-Projects
/Patterns/cristmas_tree.py
939
3.703125
4
length = int(input("how many level do you want: ")) space = 1 + (length - 1)*(2) for h in range(length + 1): if h == 0: inst_level = 0 level_length = length element = "^" part = 1 + (inst_level)*(2) elif h == length: inst_level = length // 2 level_leng...
e617dd12a6176bbebfcce2b8a9967556c06ff22c
MalenaMaffei/configs
/.i3/scripts/binarclock.py
1,222
3.53125
4
#! /usr/bin/python3 import time from itertools import zip_longest def main(): # print(vertical_strings(bcd(time.strftime('%H%M%S'))).replace('1', '${color4}◉${color}').replace('0', '○').replace('2', '${color2}◉${color}').replace('3', '${color7}◉${color}')) print(vertical_strings(bcd(time.strftime('%H%M%S')))....
f621412a132b505af7b447260896850b90ccb70e
thegentil/Projeto_ModSim
/Iteração_3.py
4,946
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 21 16:18:24 2015 @author: Nicolas Gentil e Nicolas Fonteyne Projeto final - Pêndulo de Newton Mod. Sim. - 1B Pergunta: Quanto tempo é necessário para que o pêndulo pare, em função do ângulo em que a bolinha é solta? Considerações Gerais: - O fio que segura a bolinha ...
e7582dd39c66a9303bca8577457e5edb803c642b
justnealpatel/DropToken
/DropToken.py
9,380
4.0625
4
class DropToken: """Allows for operations to mimic functionality of the Drop Token game.""" def __init__(self): """Instantiates an instance of the class. Attributes: board (list): A 4x4 matrix that will contain the values and status of our game. p1 (bool): Represent the ...
8e73474a9ac03600fee353f5f64259dae9840592
Sachey-25/TimeMachine
/Python_variables.py
1,234
4.21875
4
#Practice : Python Variables #Tool : Pycharm Community Edition #Platform : WINDOWS 10 #Author : Sachin A #Script starts here '''Greet'='This is a variable statement' print(Greet)''' #Commentning in python # -- Single line comment #''' ''' or """ """ multiline comment print('We are learning python script...
f486e214e75c90aa118f8992d8e7ab43ad96de28
antaladrien/Python-beginner-exercises
/day-17/main.py
742
3.609375
4
class User: # pass def __init__(self, user_id, username): self.id = user_id self.username = username self.followers = 0 self.following = 0 def follow(self, user): user.followers += 1 self.following += 1 # print("new user being created..."...
c1ed95232784aa3ba503f85378dc7a52a6590b63
nschhina/Competitive-Problems
/leetcode/algorithm-easy/strStr.py
629
3.53125
4
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if (needle=="" or haystack==needle): return 0 substrs=dict() strlen=len(needle) haylen=len(haystack) if(st...
ebb0a6317d9f804a716df2af5592900d770b0dcd
nschhina/Competitive-Problems
/CTCI/palindromic.py
235
3.765625
4
def palindromic(string): letters = dict() count = 0 for s in string: letters[s]+=1 for key in letters: if (letters[key]%2)==1: count+=1 if count <=1: return true return false
967a317abfd13aaa8a135621b847fb2fe04e456f
SargisYonan/Forty-Eight-Hour-Bot
/src/state.py
2,289
3.640625
4
class State: def __init__(self): pass class StateOne(State): def __init__(self): self.name = 'State One' def run(self, event): return def entry(self, event): return def exit(self, event): return class StateTwo(State): def __init__(self): self.na...
fba9bc3a189fdea744a53db3f054e72421156621
Nisarg6892/CodeChef-Codes
/ATM.py
197
3.75
4
# string=raw_input() string='30 120.00' money=map(float,string.split()) if (money[0]>money[1]) or money[0]%5!=0 : # print 'hi' print '%.2f' %money[1] else: print '%.2f' %(money[1]-money[0]-0.5)
564b66916ae951dd36cb3b4f3ae0ea52ebb706d0
skyesyesyo/AllDojo
/python/OOP/Reading/super.py
1,220
3.890625
4
# from human import Human class Human(object): """parent""" def __init__(self, health): self.health = health def display(self): print self.health return self ##################### class Wizard(Human): """super""" def __init__(self, health): super(Wizard, self).__init__(health) # use super to call the Human...
6406dd2c168adc891f19c0ba666b026efe345b05
skyesyesyo/AllDojo
/python/OOP/product.py
1,281
3.703125
4
class Product(object): """Sell, Add tax, Return, Display info""" def __init__(self, price, item_name, weight, brand, cost, status): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.cost = cost self.status = status def display_info(self): print "-" * 20 # self...
1e8e3b23f03923e87e1910f676cda91e93bc02c8
skyesyesyo/AllDojo
/python/typelist.py
929
4.25
4
#input one = ['magical unicorns',19,'hello',98.98,'world'] #output "The array you entered is of mixed type" "String: magical unicorns hello world" "Sum: 117.98" # input two = [2,3,1,7,4,12] #output "The array you entered is of integer type" "Sum: 29" # input three = ['magical','unicorns'] #output "The array you enter...
8ab39cd8b3152e6050e4a2d7b3eeb4d883bcd8b5
benjaminaaron/GO_DILab
/archive/src/play/view/View.py
460
3.59375
4
from abc import ABC, abstractmethod # abstract base class for all Views, can't be instantiated class View(ABC): def __init__(self, game): self.game = game @abstractmethod def open(self, game_controller): pass @abstractmethod def show_player_turn_start(self, name): pass ...
3c401fe8562c88860ee715da204b297ed5850786
jai-aggarwal/Assignment-2
/controller.py
5,416
3.53125
4
# Assignment 2 - Puzzle Game # # CSC148 Summer 2017, University of Toronto # --------------------------------------------- """Module containing the Controller class.""" from view import TextView, WebView from puzzle import Puzzle from solver import solve, solve_complete, hint_by_depth # class Node: # def __init__(...
caae0190f1b9b9e5073080ad0cfd0b13309a9920
sk84uhlivin/sunstonesimulator
/sunstonesimulator.py
653
3.59375
4
import random print() def rolls(): roll1 = random.randint(25, 55) roll2 = random.randint(25, 55) roll3 = random.randint(25, 55) roll4 = random.randint(25, 55) return roll1, roll2, roll3, roll4 a, b, c, d = rolls() if a + b >= 100: print(f"Crystal 1: {a}%") print(f"Crystal 2: {b}%") ...
a60d7394dcc2b73e5627dcdfb42235049ba3875a
Florins13/How-to-Think-Like-a-Computer-Scientist
/7. Iteration.py
7,762
4.0625
4
# ------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: florins # # Created: 25/12/2018 # Copyright: (c) florins 2018 # Licence: <your licence> # ------------------------------------------------------------------------------...
f801cdd77eb97ca0a4ec9c13279ebbde6f1d8025
Florins13/How-to-Think-Like-a-Computer-Scientist
/11. Lists.py
5,469
4.0625
4
import sys import turtle def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) pri...
129428dcd7b75458d8210f0b39c90c8035df1cab
romiof/cc2py
/S04/busca_sequencial.py
489
3.734375
4
def busca(lista, elemento): for i in range(len(lista)): if lista[i] == elemento: return i return False def testa_busca(lista, elemento, re): temp = busca(lista, elemento) if temp == re: print("Teste OK!") else: print("Erro !! Esperado:", re, "Porém recebido", te...
d5cafa92919774f676e4e2ac3e3c2509fea23a70
romiof/cc2py
/S01/tamanho_matriz.py
238
3.5625
4
def dimensoes(matriz): x = len(matriz) for item in matriz: y = 0 y = y + len(item) print(str(x) + "X" + str(y)) #minha_matriz = [[1], [2], [3]] #minha_matriz = [[1, 2, 3], [4, 5, 6]] #dimensoes(minha_matriz)
10c76b6c1e3466af784504b55e09bb4580f8303e
linth/learn-python
/function/base/2_closures_fun.py
1,679
4.15625
4
''' Closure(閉包) - 寫法特殊請注意 - 在 A 函式中再定義一個 B 函式。 - B 函式使用了 A 函式中的變量。 - A 函式返回 B 函式名。 閉包的使用時機 - 閉包避免了全域變數的使用,並可將資料隱藏起來。 - 當你有一些變數想要定義一個類別封裝起來時,若這個類別內只有一個方法時,使用閉包更為優雅 Reference: - https://medium.com/@zhoumax/python-%E9%96%89%E5%8C%85-closure-c98c24e52770 - https://www.pythontutorial.net/...
b73586058504c9ac8246fec05a91b091961be353
linth/learn-python
/data_structure/dict/dict_and_list_example.py
326
4.21875
4
''' dict + list 範例 Reference: - https://www.geeksforgeeks.org/python-ways-to-create-a-dictionary-of-lists/?ref=gcse ''' d = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3']) print([dict(id=v) for v in range(4)]) # [{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}] # d2 = dict(a=[1, 2, 3]) # print(d2...
2f5a29dd06067071a8f4fa4a27ba1f9cd5e77aeb
linth/learn-python
/async_IO/coroutines/base/3_coroutines_using_yield.py
546
3.546875
4
''' coroutines using yield. Reference: - https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb ''' def print_name(prefix): print('searching prefix: ', prefix) try: while True: print('yield: ', (yield)) name = (yield...
95a0c7d5fd0cf60f7782f94f3dff469b636c519b
linth/learn-python
/async_IO/coroutines/base/1_multiple_process.py
928
4.125
4
''' 使用 multiple-processing 範例 Reference: - https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb ''' from multiprocessing import Process def print_country(country='Asia'): print('The name of country is: ', country) # 如果不輸入引數情況下 def not_args(): p ...
886377b8aa15d2883936779974d51aad0e87916e
linth/learn-python
/algorithm/sorting/sort_base.py
943
4.25
4
""" List sorting. - sorted: 原本的 list 則不受影響 - sort: 改變原本的 list 內容 - sorted(x, revere=True) 反向排序 - itemgetter(), attrgetter() Reference: - https://officeguide.cc/python-sort-sorted-tutorial-examples/ """ from operator import itemgetter, attrgetter scores = [ ('Jane', 'B', 12), ('John', 'A', ...
299de4976f97707e5dea0fd958ed97a216c5c6fb
linth/learn-python
/algorithm/sorting/bubble_sort.py
537
4.09375
4
""" bubble sorting (氣泡排序法) - 兩兩比較,左邊數字大則交換,否則繼續。 Reference: - https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm """ def bubble_sort(list): for i in range(len(list)-1, 0, -1): for idx in range(i): if list[idx] > list[idx+1]: list[idx]...
cbfa05c8dac3939119625db6c11e282ad3ec8140
linth/learn-python
/async_IO/multiprocessing/base/5_use_thread_class.py
1,541
3.8125
4
''' downloading file 範例: (使用 multi-thread class寫法) - 使用兩個下載任務,有使用 multi-thread,任務會放到不同的 thread 中同時啟動,總共耗費時間將會是某項最長結果。 - 請跟 use_multi-processing 範例進行比較。 - 此範例使用兩個 thread 來執行,以及各實作 class-based and function-based 方式。 - 多 thread 程式可以共享記憶體資源 Reference: - https://github.com/jackfrued/Python-100-Days...
4ab935817c206896b54b62a41b594b9c47323dd6
linth/learn-python
/utility/sample_ex.py
595
3.515625
4
crypto_list = ['george', 'peter', 'mary'] crypto_str = ', '.join(crypto_list) print('crypto_str: ', crypto_str) poem = '''all that doth flow we cannot liquid name Or else \ would fire and water be the same; But that is liquid which is moist and wet Fire that property can never get. ...
8750cd8ce01b9521305987bd142f4815f4a0629d
linth/learn-python
/function/lambda/filter/filter.py
1,070
4.125
4
""" References: - https://www.runoob.com/python/python-func-filter.html - https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640 - https://wiki.jikexueyuan.com/project/explore-python/Advanced-Features/iterator.html """ import math from collections import Iterable # Iterator 判斷一個object是不是可迭代的 d...
5c8ef7153083c95a453909349501e2c798dac600
linth/learn-python
/data_structure/enum/enum_ex/enum_unique.py
636
3.84375
4
''' unique 範例 - 用來確保枚舉為唯一枚舉值 - 不允許有相同名稱的屬性 - 在enum class增加裝飾器 @unique 即可 enum 範例 - 總共定義4個枚舉類: enum, intenum, flag, intflag - 定義一個裝飾器: unique() - 定義一個輔助類: auto Reference: - https://docs.python.org/zh-tw/3/library/enum.html ''' from enum import Enum, unique @unique class Mistake(Enum): ...
a2423025a2443f0f20f70d8d817aac67aea027eb
linth/learn-python
/async_IO/coroutines/chain_coroutines.py
552
3.71875
4
""" References - https://docs.python.org/3.6/library/asyncio-task.html """ import asyncio async def compute(x, y): print(f"compute {x} + {y} .........") await asyncio.sleep(3) return x+y async def sum(x, y): res = await compute(x, y) print(f"{x} + {y} = {res}") if __name__ == '__main__': l...
018b6acec5f3de7326f50e81d18ae40851f893f3
linth/learn-python
/data_structure/enum/intflag_ex/base_intflag.py
514
3.609375
4
''' IntFlag 範例: - enum 範例 - 總共定義4個枚舉類: enum, intenum, flag, intflag - 定義一個裝飾器: unique() - 定義一個輔助類: auto Reference: - https://docs.python.org/zh-tw/3/library/enum.html ''' from enum import IntFlag class Box(IntFlag): L = 1 B = 2 H = 3 W = 4 LBHW = 10 BH = 5 print(B...
87f5f091b330ecee73867e4fc389b5bc059cfa64
linth/learn-python
/class/classmethod_staticmethod/classMethodBase.py
1,560
3.703125
4
""" How to use classmethod in Python? Reference: - None """ import os class InputData(object): """ interface class. """ def read(self): raise NotImplementedError('the read() must be overridden.') class PathInputData(InputData): """ concrete subclass. """ def __init__(self, path): ...
2c192275ca23c8106e0adf7d97753cb7924da006
linth/learn-python
/decorator/decorator-basic-1.py
1,168
4.03125
4
''' Reference: - https://foofish.net/python-decorator.html ''' import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) ''' [Example 1] This is decorator without parameters. ''' def use_logging(func): def wrapper(): logging.debug('{} is running'.format(func.__name__)) return ...
51593ce6b51ef500321664d47094a20343ed8e00
linth/learn-python
/function/gcd_lcm.py
747
3.84375
4
''' 最大工因數、最小公倍數 - 最大工因數: 找出都可以整除於兩個數,最後將這些數字相乘 - 最小公倍數: 找出都可以整除於兩個數,最後全部數相乘。 Reference: - https://github.com/jackfrued/Python-100-Days/blob/master/Day01-15/06.%E5%87%BD%E6%95%B0%E5%92%8C%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8.md - https://www.youtube.com/watch?v=IikEWljfL94 ''' # 最大工因數 def...
dc4253667890ddff0ba7a5296357e5049af3e218
linth/learn-python
/function/generator/generate-even.py
439
3.546875
4
''' 生成器產生偶數 - 動態產生可疊代的資料,搭配 for 迴圈使用。 - 使用 yield 語法,呼叫時回傳生成器。 Reference: - https://www.youtube.com/watch?v=x6MNOSRY5EM&t=4s ''' def generate_even(max): number = 0 while number < max: yield number number += 2 evenGenerator = generate_even(20) for data in evenGenerator: print(...
04b9655862cad99a67575ba673ca031bf9ecdcbd
linth/learn-python
/generic/defining_generic_classes_stack.py
1,568
4.0625
4
''' Defining generic classes 定義一個 generic class - Stack 泛型範例 - TypeVar - Generic 首先不能使用 Any, 因為這樣無法讓函式可以除錯,return值可以式任何 type。 因此,我們就需要定義好 input/output 的 type,方便我們可以確認。但是直接定義 int, str, ...等,會讓程式變得 scale 很差。 解決的辦法就是使用 type variables: - Type variables allow you to link several types together. - T...
8e018e0b2149ca6dab654c12849004e44761b8ba
linth/learn-python
/class/classAttr_instanceAttr/instance-method/1_InstanceMethod.py
479
4.21875
4
''' 實體方法(Instance Method) - 至少要有一個self參數 - 實體方法(Instance Method) 透過self參數可以自由的存取物件 (Object)的屬性 (Attribute)及其他方法(Method) Reference: - https://www.learncodewithmike.com/2020/01/python-method.html ''' class Cars: # 實體方法(Instance Method) def drive(self): print('Drive is instance method...
8b4a7475433936941c7f9794ec67783a4be5cadf
linth/learn-python
/function/anonymous_function/anonymous_filter.py
1,392
4.34375
4
""" Anonymous function. (匿名函數) - map - filter - reduce lambda程式撰寫方式: - lambda arguments: expression map程式撰寫方式: - map(function, iterable(s)) - 抓取符合的元素。 filter程式撰寫方式: - filter(function, iterable(s)) - 用來過濾序列,過濾掉不符合的元素。 reduce程式撰寫方式: - reduce(function, sequence[, initial]) - 對序列...
f78e6050cae90108b21dc46e48f18e88bc6a4db1
linth/learn-python
/function/function-turtle.py
893
3.953125
4
''' http://openbookproject.net/thinkcs/python/english3e/functions.html ''' import turtle def draw_square(t, sz): for i in range(8): t.forward(sz) t.right(45) def draw_multiple_square(t, sz): for i in ['red', 'purple', 'hotpink', 'blue']: t.color(i) t.forward(sz) t.left...
d09451cfc1aae0949562891a2b0d78a385a4eee2
linth/learn-python
/algorithm/sorting/merge_sort.py
1,809
4.53125
5
""" Merge sorting (合併排序法) - 把一個 list 開始逐步拆成兩兩一組 - 合併時候再逐步根據大小先後加入到新的 list裡面 - Merge Sort屬於Divide and Conquer演算法 - 把問題先拆解(divide)成子問題,並在逐一處理子問題後,將子問題的結果合併(conquer),如此便解決了原先的問題。 Reference: - https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm# - https://www...
223b8b745c803128b9021aa3f838d5387df4a75d
linth/learn-python
/algorithm/sorting/insertion_sort.py
696
4.09375
4
""" Insertion Sort (插入排序法) 1. 順序從左到右開始 2. 從剩下的array, 找出最小的數值 3. 取最小值進行替換 Reference: - https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm# """ def insertion_sort(list): n = len(list) for i in range(1, n): # 從第二個 index 開始 j = i-1 next_element ...
f2010a9b89aaa385dc2a5a11c908ce56e00c00ad
linth/learn-python
/function/lambda/map/map.py
266
3.671875
4
def square(x): return x ** 2 def add(x): return x + 10 def use_map(fn, lst): return list(map(fn, lst)) if __name__ == '__main__': arr = [1, 2, 3, 6] res = use_map(square, arr) print(res) res1 = use_map(add, arr) print(res1)
139447d3a6786a3fe0312574c48924ab83f7c709
linth/learn-python
/async_IO/multithreading/base/5_queue_threads.py
976
4.1875
4
''' 學習如何使用 queue + threads Reference: - https://blog.gtwang.org/programming/python-threading-multithreaded-programming-tutorial/ ''' from threading import Thread import time import queue class Worker(Thread): def __init__(self, queue, num): Thread.__init__(self) self.queue = queue se...
df106548be0c953a9bccebfdbb33deeb7c228375
linth/learn-python
/data_structure/list/list_comprehension/list_comprehension.py
717
4.03125
4
''' List comprehension - 學習不同寫法 Reference: - https://www.youtube.com/watch?v=SNq4C988FjU ''' import time fruits = ['apples', 'bananas', 'strawberries'] def list_used_direct(): for fruit in fruits: # print(fruit) fruit = fruit.upper() #! 不會被覆蓋 print(fruits) # ['apples', 'banana...
584c4e36f9801a63fd17adae4c750647d0afeec8
linth/learn-python
/class/specificMethod-3.py
606
4.3125
4
''' specific method - __str__() and __repr__() - __repr__() magic method returns a printable representation of the object. - The __str__() magic method returns the string Reference: - https://www.geeksforgeeks.org/python-__repr__-magic-method/?ref=rp ''' class GFG: def __init__(self, name): ...
841ce71d933fab4357bc5f14ed404473ed7647f1
linth/learn-python
/class/private_protected/breaking_all_private.py
524
3.8125
4
''' 如何破解Python private members Reference: - https://medium.com/citycoddee/python%E9%80%B2%E9%9A%8E%E6%8A%80%E5%B7%A7-1-private-member-on-python-fb5678b02582 ''' class Animal: def __init__(self): self.__alive = True self.__age = 0 def __print_something(self): print('call _...
0327a82bc12cee3f45ee868f5e4023809e8d70a8
Nazar4ick/Homework-research
/modules_example.py
1,443
3.546875
4
import urllib.request import json import matplotlib.pyplot as plt base_url = 'https://www.quandl.com/api/v3/datasets/WWDI/UKR_NY_GDP_MKTP_CD.json?api_key=2jhCWecEKmuxzVY9ifwp' def get_ukraine_gdp(url): """ Gets Ukraine's GDP from quandl in US dollars :param url: str :return: dict """ ...
64b25ed54bcb7d9a1d640033a73320afc00ed188
tarungoyal1/pythonbtb
/writerecaman.py
450
3.5625
4
import sys from itertools import islice, count def sequence(): """Generate Racaman's sequence.""" seen=set() a=0 for n in count(1): yield a seen.add(a) c = a-n if c<0 or c in seen: c = a + n a=c def writeseqeunce(filename, num): f = open(filename, mode='wt', encoding='utf-8') f.writelines("{0}\n".f...
a7ab0d16e3266d89e3119cfe59447d30062a9140
kelly4strength/intCakes
/intCake3.py
2,264
4.40625
4
# Given a list_of_ints, # find the highest_product you can get from three of the integers. # The input list_of_ints will always have at least three integers. # find max, pop, add popped to a new list_of_ints # add those ints bam! # lst = [11,9,4,7,13, 21, 55, 17] # returns [55, 21, 17] # 93 # lst = [0, 9, 7] # retu...
327906c9cb3d32d3259a897f8aed3459155f1412
ChoSooMin/Web_practice
/python_pratice/todo/01.todos.py
2,439
4.03125
4
# todo 저장하는 시스템 todos = [] todoNum = 0 # { "todoNum": todoNum, "title": title } 데이터 형식 # 등록, 수정, 삭제, 일정 목록 보기, 전체 삭제 기능 while True : print("\n====== TODO ======") print("1. TODO 작성하기") print("2. TODO 수정") print("3. TODO 삭제") print("4. TODO 전체 삭제") print("5. TODO 목록 보기") print("0. 종료") ...
0a3ab7aeeb12e47a41360f067099808b99eeac08
ChoSooMin/Web_practice
/python_pratice/command.py
1,230
4.1875
4
# list type : [str, int, float, boolean, list] [[1, 2, 3], [1, 2]] list 안의 list가 들어갈 경우, 안에 있는 list의 각 길이가 꼭 같을 필요는 없다. list_a = [1, 2, 3] list_b = [4, 5, 6] print(list_a + list_b, " + 연산 후 list_a : ", list_a) # list_a 값을 변하게 하려면 list_a에 할당을 다시 해줘야 한다. # 할당했을 경우 # list_a = list_a + list_b # print("list_a 할당", list_a)...
86a89061d84ce6dcd8822ddbe1d1d9f82c7bafcd
abhira15/Programming-Challenges-Unit-1-6-
/trash/dictionary.py
696
3.578125
4
from collections import defaultdict def contains(sorted_word, sorted_candidate): wchars = (c for c in sorted_word) for cc in sorted_candidate: while(True): if wchars < cc: continue if wchars == cc: break return False return True d = defaultdict(list) with open(r"C...
0cd46aa2da3768230efd5cb9ff79745858d3488c
ryoishizawa/leetcode-py
/217-contains-duplicate.py
387
3.578125
4
''' Time Complexity: O(nlogN) - Sort O(nlogN) - Sweep O(n) Better choice: Use Hash Table Not to use: Brute force (Not Accepted as the time complexity is O(n^2)) ''' class Solution: def containsDuplicate(self, nums: List[int]) -> bool: nums.sort() for i in range(len(nums) - 1): if nums[i...
4c71ad30ffa972d0be24b0f698dc3b77232301d4
feliperod0519/python
/mapping.py
999
3.96875
4
import argparse def get_args(): parser = argparse.ArgumentParser(description='Gashlycrumb', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('letter', help='Letter(s)', metavar='letter', nargs='+', type=str) parser.add_argument('-f','--file', help='Input file', metavar='FILE', ...
fae9bc5cd4a20cded69d719118578eb5dd9f7105
feliperod0519/python
/set-practice.py
1,673
3.84375
4
import argparse def get_args(): parser = argparse.ArgumentParser(description='Dictionary',formatter_class=argparse.ArgumentDefaultsHelpFormatter) args = parser.parse_args() return args def main(): args = get_args() my_set = {1, 2, 3} print(my_set) my_set = {1.0, "Hello", (1, 2, 3)} pri...
2dd796786e667b8867a7d164e0156bc049be0404
feliperod0519/python
/dict.py
1,479
3.578125
4
import argparse def get_args(): parser = argparse.ArgumentParser(description="Jump the Five", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text', metavar='str', help='Input text') return parser.parse_args() def main(): args = get_arg...
4b26c494ee3058c747ab85380c8c27b88d5f5abd
ryanbhayward/crypto
/substn/morse/morse.py
603
3.578125
4
import sys from string import ascii_lowercase def words(text): W = [] wrds = text.split() for w in wrds: #wstr = "'"+ w + "'," #print wstr, W.append(w) return W def MorseEncrypt(txt): out = '' for c in txt: if c in ascii_lowercase: out += M[ord(c)-ord('a')] + ' ' else: out ...
edee018eec1c573b1d0a5ace716c602ad2487ab5
permag/py-crawler
/main.py
1,182
3.609375
4
#!/usr/bin/env python #-*- coding: utf-8 -*- from pycrawler import Crawler def main(): """ Example usages """ url = '' nr = 0 nr_total = 0 crawler = Crawler() while True: search = raw_input('1) BFS\n2) DFS\nSelect search type [1 - 2]: ') if search == '1': ...
f4c64fc63ebd9097cc450cc546586f504d385028
MariaAga/Codewars
/Python/triangle_type.py
335
4.125
4
# Should return triangle type: # 0 : if triangle cannot be made with given sides # 1 : acute triangle # 2 : right triangle # 3 : obtuse triangle def triangle_type(a, b, c): x,y,z = sorted([a,b,c]) if (x+y)<=z: return 0 if (x*x+y*y==z*z): return 2 if z*z > (x*x + y*y): return...
6cc617528370c5af5394c955b2d77267aca0f884
MariaAga/Codewars
/Python/alphabet_position.py
278
3.9375
4
def alphabet_position(text): s="" for x in text: if (ord(x) >= ord('a') and ord(x) <= ord('z')): s+= (str(ord(x)-ord('a')+1)+" ") if (ord(x) >= ord('A') and ord(x) <= ord('Z')): s+= (str(ord(x)-ord('A')+1)+" ") return s[:-1]
ee680b2fb9297b0deaa833514438d90dc62a1df2
panwaranurag/Algo_python
/dynamic_programming/hunter_problem_pat.py
2,571
3.75
4
#!/usr/local/bin/python2.7 from random import randint import sys if __name__ == "__main__" and len(sys.argv) != 3: print "must have 2 number arguments" if __name__ == "__main__" and len(sys.argv) == 3: numInputLists = int(sys.argv[1]) inputListLen = int(sys.argv[2]) inputLists = [] '''inputLists.append([1,...
5120f7206bf6961a69fdee92b0fef49a2b188f3d
panwaranurag/Algo_python
/algorithms/binary_search.py
452
3.984375
4
def binary_search(arr, x): return search(arr, x, 0, len(arr)-1) def search(arr, x, low, high): if low > high: return -1 mid = int(low + (high-low)/2) if arr[mid] > x: return search(arr, x, mid+1, high) elif arr[mid] == x: return mid else: return search(arr, x, lo...
a573d6bbaa8028a81ea8119bb46eb3f4b0a103fe
dan89farhan/ETPracs
/Python/ETPracs/pract3/classEmp.py
411
3.65625
4
class Emp: empCount=0 def __init__(self, name, salary): self.name=name self.salary=salary Emp.empCount += 1 def displayCount(self): print ('Total Employees %d' % Emp.empCount) def dispEmp(self): print('Name:',self.name,' Salary:',self.salary) emp1=Emp('Vjti',200...
a4c0de08891c8924f3a76fa25438bbddbe090243
dan89farhan/ETPracs
/Python/ETPracs/test/tut3.py
176
4.1875
4
list1 = ['apple', 'banana', 'mango'] for word in list1: if word == 'banana': print(word) for i in range(3): print(list1[i]) for j in range(5,9, 2): print(j)
79dcffa68f8488aacf68d2686b71459a611a57db
dan89farhan/ETPracs
/Python/ETPracs/pract5/q4.py
1,352
3.796875
4
from tkinter import * class MyApp(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widget() def create_widget(self): self.instruction_label = Label(self, text = "Only authorised person are allowed.") self.instruction_label.grid(row=...
60777a3eea6eea556eb39bea0e3dc87ce1d28da2
dan89farhan/ETPracs
/Python/ETPracs/pract1/arithmatic.py
90
3.65625
4
x=10 y=20 print('x+y = ',x+y) print('x-y = ',x-y) print('x*y = ',x*y) print('x/y = ',x/y)
d883ba42698a4976c7bdf7f7d85d521abec79ac0
AdiVittala/Python-Development
/fractional_knapsack.py
384
3.78125
4
# Uses python3 def get_optimal_value(capacity, weights, values): value = 0. # write your code here return value data = list(map(int, input().split())) n, capacity = data[0:2] values = data[2:(2 * n + 2):2] weights = data[3:(2 * n + 2):2] #opt_value = get_optimal_value(capacity, weights, values) #print(...