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
a6c894153ab19e3e4b50adb7934bfa7c70bb8ef6
baidongbin/python
/疯狂Python讲义/codes/07/7.3/raise_test.py
330
3.609375
4
def main(): try: # 使用try...except来捕获异常 # 此时即使程序出现异常,也不会传递给main函数 mtd(3) except Exception as e: print('程序出现异常:', e) mtd(3) def mtd(a): if a > 0: raise ValueError('a的值大于0,不符合要求') main()
1a37b20c82ba98065848cb479e06b669b32251b9
baidongbin/python
/疯狂Python讲义/codes/05/5.2/dict_transfer_test.py
401
3.890625
4
def swap(dw): # 下面代码实现dw的a、b两个元素的值交换 dw['a'], dw['b'] = dw['b'], dw['a'] print('在swap()函数里,a元素的值是', dw['a'], ';b元素的值是', dw['b']) # 把dw直接赋值为None,让它不再指向任何对象 dw = None dw = {'a': 6, 'b': 9} swap(dw) print('交换结束后,a元素的值是', dw['a'], ';b元素的值是', dw['b'])
af87db731b08c739ee0d3886da1df50b8bc2a331
baidongbin/python
/疯狂Python讲义/codes/10/10.8/ChainMap_test.py
403
3.515625
4
from collections import ChainMap # 定义三个 dict 对象 a = {'Kotlin': 90, 'Python': 86} b = {'Go': 93, 'Python': 92} c = {'Swift': 89, 'Go': 87} # 将三个 dict 对象链在一起,就像变成了一个大的 dict cm = ChainMap(a, b, c) print(cm) # 获取 Kotlin 对应的 value print(cm['Kotlin']) # 获取 Python 对应的 value print(cm['Python']) # 获取 Go 对应的 value print(cm['Go'...
c52d4fbcc439c3ad2ac89770752df495c44dc960
baidongbin/python
/疯狂Python讲义/codes/06/6.3/modify_class_var.py
795
3.96875
4
class Inventory: # 定义两个类变量 item = '鼠标' quantity = 2000 # 定义实例方法 def change(self, item, quantity): # 下面赋值语句不是对类变量赋值,而是定义新的实例变量 self.item = item self.quantity = quantity # 创建Inventory对象 iv = Inventory() iv.change('显示器', 500) # 访问iv的item和quantity实例变量 print(iv.item) print(iv.q...
7e2d50779e4aed5e893261d11d1a15e11b5ca89b
baidongbin/python
/疯狂Python讲义/codes/05/5.1/function_doc.py
369
3.5
4
def my_max(x, y): ''' 获取两个数值之间较大数的函数 my_max(x, y) 返回x、y两个参数之间较大的那个数 ''' # 定义一个变量z,该变量等于x、y中较大的值 z = x if x > y else y # 返回变量z的值 return z # 使用help()函数查看my_max的帮助文档 help(my_max) print(my_max.__doc__)
7505b339bb908d006e9d2b7ee8eb8dbc43140bdc
baidongbin/python
/疯狂Python讲义/codes/05/5.2/default_param_test2.py
448
4.25
4
# 定义一个打印三角形的函数,有默认值的参数必须放在后面 def printTriangle(char, height=5): for i in range(1, height + 1): # 先打印一排空格 for j in range(height - 1): print(' ', end='') # 再打印一排特殊字符 for j in range(2 * i - 1): print(char, end='') print() printTriangle('@', 6) printTria...
f622626e54e197fb2941aa193b8a19b2fdd21ec3
baidongbin/python
/疯狂Python讲义/codes/08/8.3/iter_test.py
935
4.0625
4
# 定义一个代表斐波那契数列的迭代器 class Fibs: def __init__(self, len): self.first = 0; self.sec = 1 self.__len = len # 定义迭代器所需的__next__方法 def __next__(self): # 如果__len属性为0,结束迭代 if self.__len == 0: raise StopIteration # 完成数列计算 self.first, self.sec = self....
6f90a49fc5bb60e8a7f3d2491df7f67e1991c519
baidongbin/python
/疯狂Python讲义/codes/11/11.2/extend_frame.py
1,303
3.765625
4
# Python 2.x 使用这行 # from Tkinter import * # Python 3.x 使用这行 from tkinter import * # 定义继承 Frame 的 Application 类 class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() # 调用 initWidgets() 方法初始化界面 self.initWidgets() def initWidgets(self...
af16aa7da0c5a621ca3990d899e2fc1cdaa64f84
baidongbin/python
/疯狂Python讲义/codes/05/5.5/lambda_map.py
237
3.921875
4
# 传入计算平方的lamdba表达式作为参数 x = map(lambda x: x * x, range(8)) print([e for e in x]) # 传入计算平法的lamdba表达式作为参数 y = map(lambda x: x * x if x % 2 == 0 else 0, range(8)) print([e for e in y])
885164afa77587579b39de996c882617f793fec0
baidongbin/python
/疯狂Python讲义/codes/14/14.6/Event/Account.py
2,111
3.921875
4
import threading class Account: # 定义构造器 def __init__(self, account_no, balance): # 封装账户编号、账户余额的两个成员变量 self.account_no = account_no self._balance = balance self.lock = threading.Lock() self.event = threading.Event() # 因为账户余额不允许随便修改,所以只为 self._balance 提供 getter 方法 ...
d9a50f8e16289efe296b77e54f5f214567f20bbb
baidongbin/python
/疯狂Python讲义/codes/06/6.2/Item.py
229
3.71875
4
class Item: # 直接在类命名空间中放置可执行代码 print('这在定义Item类') for i in range(10): if i % 2 == 0: print('偶数:', i) else: print('奇数:', i)
7b401e17c911ce7719acb61163ab55946880b7c1
Lightwing-Ng/ASwordToOffer
/52.py
789
3.90625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Apr 18, 2018, 11:12 PM * Software: PyCharm * Project Name: Tutorial """ class Solution: def multiply(self, A): """ 题目描述 给定一个数组A[0, 1, ..., n-1],请构建一个数组B[0,1,...,n-1],其中B...
899564358c3e1d02874a84ddbb8ab8f074bffc1e
Lightwing-Ng/ASwordToOffer
/20.py
881
3.796875
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Mar 31, 2018, 11:32 AM * Software: PyCharm * Project Name: Tutorial """ # 题目描述 # 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 class Solution: def __init__(self): self.stack = [] self.mi...
f8179bd373a047b10d35895f8d24cec1b2d97539
Lightwing-Ng/ASwordToOffer
/61.py
1,079
3.671875
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Apr 19, 2018, 4:26 AM * Software: PyCharm * Project Name: Tutorial """ # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None c...
fb42297db270c059e1ee045d9779036112b25709
Lightwing-Ng/ASwordToOffer
/56.py
693
3.734375
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Apr 19, 2018, 2:37 AM * Software: PyCharm * Project Name: Tutorial """ # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryN...
7d03778110069c565ede5397c885e57fec21ac7b
Lightwing-Ng/ASwordToOffer
/30.py
1,144
3.546875
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Apr 18, 2018, 12:42 AM * Software: PyCharm * Project Name: Tutorial """ class Solution: def FindGreatestSumOfSubArray(self, array): """ 题目描述 HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天...
6f25dc8edb7c500ada01f5816b194fe8a80eba4c
Lightwing-Ng/ASwordToOffer
/29.py
690
3.640625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Apr 18, 2018, 12:28 AM * Software: PyCharm * Project Name: Tutorial """ class Solution: def GetLeastNumbers_Solution(self, tinput, k): """ 题目描述 输入n个整数,找出其中最小的K个数。例如输入4, ...
674001d4dbded92236ca0e5a425c5c73b492e922
Lightwing-Ng/ASwordToOffer
/12.py
692
3.921875
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ * @author: Lightwing Ng * email: rodney_ng@iCloud.com * created on Mar 27, 2018, 4:10 AM * Software: PyCharm * Project Name: Tutorial """ # 题目描述 # 给定一个double类型的浮点数base和int类型的整数exponent。 # 求base的exponent次方。 class Solution: def Power(self, base, exponent): ...
79078d4c48b887e3aaf086a398496553fc96da95
Vinicius-de-Morais/Exercicios
/Desafios_6/exercício_2/exercício_2.py
2,205
3.625
4
import random as r import os import winsound from time import sleep class PalavraSecreta: def __init__ (self): self.palavra = None self.anagrama = None def escolhe_palavra(self): palavras = [] # abre o arquivo txt with open('Desafios_6\exercício_2\palavras.txt'...
a79ecea24549ae9a724e98aa216d8043dab1bb76
Vinicius-de-Morais/Exercicios
/1-10/2.py
310
3.875
4
def saudar(): boas_vindas = int(input(''' 1 - Boas vindas em Português 2 - Welcome in English 3 - Boas vindas zica ''')) if boas_vindas == 1: print('Seja Bem Vindo!') elif boas_vindas == 2: print('Be Welcome') elif boas_vindas == 3: print('Que isso lek TMJ!') saudar()
b37a727c6653dafcfa480283e68badbd87c408f2
skynette/Solved-Problems
/Collatz.py
1,737
4.3125
4
question = """The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an inte...
0081eac284bb86e948aeef7e933796385df12000
ddbs/Accelerating_Dual_Momentum
/functions.py
374
4.15625
4
from datetime import datetime, date def start_of_year(my_date): """ Gives the starting date of a year given any date :param my_date: date, str :return: str """ my_date = datetime.strptime(my_date, '%Y-%m-%d') starting_date = date(my_date.year, my_date.month, 1) starting_date = starti...
d545e90149dfca91045aed7666b8456644c8f9a8
jyotisahu08/PythonPrograms
/StringRev.py
530
4.3125
4
from builtins import print str = 'High Time' # Printing length of given string a = len(str) print('Length of the given string is :',a) # Printing reverse of the given string str1 = "" for i in str: str1 = i + str1 print("Reverse of given string is :",str1) # Checking a given string is palindrome or not str2 = 'abb...
a0d271e1278620ba550819d63a42e1a0da449b79
DanB28/Data-Structures
/Tree Project/Tree_Project_Testing/Main.py
6,406
3.515625
4
############################################################################################## ''' Dan Bailey Project Three 11/23/16 This program's objective is to read in a file that has a list of characters that have a code associated with them, and based on if the code reads a one or zero, the program will c...
94809d36b3e628a6eee120ede814151ab9263b25
d1spell/theory
/OOP/decorators.py
2,233
3.65625
4
def counter_add(start): def step(): nonlocal start start += 5 return start return step k = 7 cnt = counter_add(k) print(cnt()) def counter_add(n): def step(star): nonlocal n star += n return star return step # k = int(input()) # cnt = counter_add(2...
68e1c2d9bb2acf76e182e1ed6200678d371ac856
lazyminds0499/Snake-game
/main.py
1,251
3.84375
4
from turtle import Screen import time from snake import Snake from food import Food from scoreboard import ScoreBoard screen = Screen() game_is_on = True screen.bgcolor("black") screen.setup(width=600, height=600) screen.title("Snake Game") screen.tracer(0) snake = Snake() screen.listen() screen.onkey(...
d09b8900482ad5f4658c8fa0e78100b35f2d966c
AineNicD/pands-project
/analysis.py
2,880
3.796875
4
#Aine Nic Dhonnacha #This program analysis.py #-outputs a summary of each variable to a single text file. #-saves a histogram of each variable to png files, and #outputs a scatter plot of each pair of variables. #I worked on each task separately and then put them all together. #import libraries import num...
4995faf0f69685203b72f4e07cfaf60db4e25a93
webxiimao/python-study
/study-05-urllib2/02-模拟百度接口.py
780
3.515625
4
from urllib.request import Request, urlopen from urllib.parse import urlencode class baidu_port(object): def __init__(self): self.url = "http://www.baidu.com/s" def search(self, keyword): word = { 'wd':keyword } search_word = urlencode(word) fullurl = self.url + '?' + search_w...
12140b4c5fac11e3acde68e449abb931d37649ba
BasSondag/stars
/stars.py
119
3.609375
4
def draw_stars(arr): for i in range(len(a)): arr[i] *= "*" print arr[i] return a = [1, 2, 3, 4, 5] draw_stars(a)
2ceb6231b39d450ca39a80d68bbf83e12653ba61
Hubert-HD/ProyectoADAGrupoC
/P1_Ordenamiento/main.py
1,559
3.796875
4
from util import arrayGenerator from heapsort import heapSort from quicksort import quickSort def validateSortInteger(): arr1 = arrayGenerator(type="int", maxSize=15) arr2 = arr1.copy() print("lista 1: ", arr1) print("lista 2: ", arr2) heapSort(arr1) quickSort(arr2) print("lista 1 ordenada:",arr1) ...
3a343e31eb59fc6571fc4ef0f95fd295d3fd97ab
CSolitaire/regression-exercises
/explore.py
1,164
3.53125
4
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from math import sqrt from scipy import stats import warnings warnings.filterwarnings("ignore") ###################### Explore Telco Data ###################### def plot_variable_pairs(df): ''' Function that plots all...
cb8f47945f7304b3e4e6e67bc482dd91599a9a40
gunjan01/coding-interview-gym
/leetcode.com/python/314_Binary_Tree_Vertical_Order_Traversal.py
1,106
3.640625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque from collections import defaultdict class Solution(object): def verticalOrder(self, ...
3929c429a5480acc70bcb7f20e8434fe089a9299
haryadwi/learn-py
/LEARN/branch/ifelifelse.py
238
3.671875
4
# program penguji bilangan positif, nol, dan negatif bilangan = -4 if bilangan > 0: print(bilangan, "Merupakan Bilangan Positif") elif bilangan == 0: print(bilangan, "Bernilai Nol") else: print("Merupakan Bilangan Negatif")
9ec31b44a6f0f293b592a5b90197104f530aa9f2
lcordero/progra-uno
/examples/sum_nums.py
322
4.03125
4
# This program adds two numbers #num1 = 1 #num2 = 6 # Get numbers from user num1 = float(input('Ingrese el valor para numero1: ')) num2 = float(input('Ingrese el valor para numero2: ')) # Add two numbers sum = float(num1) + float(num2) # Display the sum print('La suma de {0} y {1} es: {2}'.format(num1, num2, sum)...
c58d8c5a7ec8454f090d0aed1352511910c82b01
Hemanthtm2/pythoncodes
/raisecondition.py
152
4.09375
4
#!/usr/bin/python def inputNum(): num=input("Enter a number") if num==13: raise ValueError,'13 is a bad number' return num inputNum()
61a6eeb2ede35b0a722558bd1d47de7f76a3362c
Hemanthtm2/pythoncodes
/joinsplit.py
145
4.0625
4
#!/usr/bin/python import string st="It's raining in india" print string.split(st) chs=["The","rain","in","spain"] print string.join(chs)
67eb2533affaf7ff77c47c064d363ac08db48edb
Hemanthtm2/pythoncodes
/prlog.py
188
3.796875
4
#!/usr/bin/python import math def printLog(x): if x<0: print "Err..Positive numbers only!!!" return result=math.log(x) print "result=",result printLog(20) printLog(-3)
5f6d30226b619482eddab169e8166f824d747635
Hemanthtm2/pythoncodes
/functest.py
100
3.53125
4
#1/usr/bin/python import math degree=45 angle=degree*2*math.pi/360.0 s= math.sin(angle) print s
8c7c6c7e696f5bc9224e86a1501700865363cfa9
GomesMarcos/python4hk
/basics/funcoes_anonimas.py
192
3.609375
4
lista = list(range(1, 101)) print(lista) def dobro(x): return x*2 lista_dobro = map(dobro, lista) print(lista_dobro) lista_dobro = map(lambda x: x * 2, lista) print(list(lista_dobro))
f330c016aec429442f7cc2d650f41214ac7a870a
GomesMarcos/python4hk
/basics/funcoes.py
236
3.9375
4
print("Criando funções em Python: uso da palavra reservada 'def'.") def media(n1, n2): return (n1 +n2)/2 print("O valor médio da soma entre 2 e 6 é: ", media(2,6)) print("O valor médio da soma entre 1 e 2 é: ", media(1,2))
aae84839bcd0c91b994768e2d92c1d89ece06e9c
CAWilson94/HelloWorldPython_Genetic
/Population.py
691
3.59375
4
""" Created on 14 November 2016 @author: Charlotte Alexandra Wilson Last revision: 14 Nov 2016 Creates the population needed for chromosomes """ from Constants import Constants from Chromosome import Chromosome class Population(): def getRandPop(self): popSize = Constants.POP_SIZE; if((popSize...
edfc06069c70bd868a0511aab602ae8df91e1d56
marcopared/face-recognition-ece196
/project_1/hello_world.py
271
3.515625
4
""" hello_world.py Simple Hello World program. ECE196 Face Recognition Project Author: Will Chen 1. Write a Write a program that prints "Hello World!" and uses the main function convention. """ # TODO: Write a program that prints "Hello World!" and uses a main function.
2da8440d81680aeaba088e3492535094d0ed8a2c
programmingrocks/code
/Python/if1.py
372
4.03125
4
correct = "The people were married." number = True while number: n = str(input("""You see many people on a boat which never sinks, but when you look again, there isn't a single person on the boat. How is that?""")) if n == correct: print("Correct!") break number = False elif n != co...
d5e49df7f61a6e15cf1357aa09e33a81e186627b
Botany-Downs-Secondary-College/password_manager-bunda
/eason_loginV1.py
2,002
4.4375
4
#password_manager #store and display password for others #E.Xuan, February 22 name = "" age = "" login_user = ["bdsc"] login_password = ["pass1234"] password_list = [] def menu(name, age): if age < 13: print("Sorry, you do not meet the age requirement for this app") exit() else...
d79e6eaf1ab98fcd273188fd049fb9e95d8488d9
dimDamyanov/PythonOOP
/09. Decorators/LAB/demo_debug.py
570
3.546875
4
def debug(func): """Print func name with args, kwargs and result""" def wrapper(*args, **kwargs): args_str = [str(e) for e in args] kwargs_str = [f'{key}={value}' for key, value in kwargs.items()] arguments_str = [] arguments_str.extend(args_str) arguments_str.extend(kwa...
3d112bbd243f84cf545e6b34815b590a737488eb
dimDamyanov/PythonOOP
/01. Defining classes/Exercise/06_pokemon_battle/trainer.py
863
3.625
4
from .pokemon import Pokemon class Trainer: def __init__(self, name: str): self.name = name self.pokemon = [] def add_pokemon(self, new_pokemon: Pokemon): if new_pokemon not in self.pokemon: self.pokemon.append(new_pokemon) return f'Caught {new_pokemon.pokemon_...
4f1b72081c0cc75d2914ff05c669de6d2cd9ab69
dimDamyanov/PythonOOP
/03. Attributes and Methods/LAB/demo.py
1,027
3.765625
4
# class Person: # max_age = 150 # # def __init__(self, name: str, age: int): # self.validate_age(age) # self.name = name # self.age = age # # @staticmethod # def validate_age(age: int): # if age < 0 or age > Person.max_age: # raise ValueError('Age is invalid')...
eabf1ff58d65a4653e8c9de074610712764734c3
dimDamyanov/PythonOOP
/07. SOLID/LAB/03_LSP/robots.py
449
3.671875
4
from abc import ABC, abstractmethod class Robot(ABC): @abstractmethod def sensors_count(self): pass class Android(Robot): def senzors_count(self): return 4 class Chappie(Robot): def senzors_count(self): return 6 def count_robot_senzors(robots: list): ...
e7a9dacc04076090fa95081d86898816bdd1d696
SinCatGit/leetcode
/00188/best_time_to_buy_and_sell_stock_iv.py
1,844
3.953125
4
from typing import List class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: """ https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to fin...
be3c877447b3dd9a7508fc3dfe5efedf397f3dba
SinCatGit/leetcode
/00266/palindrome_permutation.py
1,662
4.0625
4
from typing import List class Solution: def canPermutePalindrome(self, s: str) -> bool: """ https://leetcode.com/problems/palindrome-permutation Given a string, determine if a permutation of the string could form a palindrome. Example 1: Input: "code" Output: fal...
a985c7cfa173f12859fb0b3f6baad071326c95a3
SinCatGit/leetcode
/00366/find_leaves_of_binary_tree.py
1,618
4.09375
4
from typing import List from heapq import heappop, heappush class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: def findLeaves(self, root: TreeNode) -> List[List[int]]: """ [366. Find Leaves of Binary Tree](https://leetco...
0b438710ac8f28ec5648d3ead137d9fe67061f61
SinCatGit/leetcode
/00687/longest_univalue_path.py
1,750
4.09375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.longest_path = 0 def longestUnivaluePath(self, root: TreeNode) -> int: """ https://leetcode.com/problems/longest-univalue-path/ ...
3c799b032b5a188de73719fd542ffdcbbfaad502
SinCatGit/leetcode
/00938/range_sum_of_bst.py
1,414
3.78125
4
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: """ https://leetcode.com/problems/range-sum-of-bst/ Given the root nod...
7f999a6e130c69c0bbec6bb0415576b2e68c051e
SinCatGit/leetcode
/00219/contains_duplicate_ii.py
1,388
3.6875
4
from typing import List class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: """ https://leetcode.com/problems/contains-duplicate-ii/ Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array s...
86a9feb5e99763cb68750a4e4afc22ceeb844b59
SinCatGit/leetcode
/00776/split_bst.py
3,115
4.03125
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def splitBST(self, root: TreeNode, val: int) -> (TreeNode, TreeNode): """ https://leetcode.com/problems/split-bst/ Given a Binary Search Tree (BST) with roo...
187e9284f74106545b544f60fbd496d77f803fd1
SinCatGit/leetcode
/00437/path_sum_iii.py
2,598
3.84375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pathSum(self, root: TreeNode, s: int) -> int: """ https://leetcode.com/problems/path-sum-iii/ You are given a binary tree in which each node contains an...
baa45a884596594e89c2ca311973bf378c756e77
SinCatGit/leetcode
/00122/best_time_to_buy_and_sell_stock_ii.py
1,574
4.125
4
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: """ https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maxim...
8da2a824e0fe827e1d10cba4741f64c70e986938
SinCatGit/leetcode
/00161/one_edit_distance.py
1,771
3.96875
4
from typing import List class Solution: def isOneEditDistance(self, s: str, t: str) -> bool: """ https://leetcode.com/problems/one-edit-distance/ Given two strings s and t, determine if they are both one edit distance apart. **Note:** There are 3 possiblities to satisify...
edad5ed9456ceef0e9c7782d10cd9d7fbba73539
SinCatGit/leetcode
/00245/shortest_word_distance_iii.py
1,452
3.96875
4
from typing import List class Solution: def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: """ https://leetcode.com/problems/shortest-word-distance-iii This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2. ...
56e7d9911612ffffa191caf4cce2ba938061203e
SinCatGit/leetcode
/00666/path_sum_iv.py
2,459
4.0625
4
from typing import List class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class Solution: def pathSum(self, nums: List[int]) -> int: """ https://leetcode.com/problems/path-sum-iv/ If the depth of a tree is smaller than...
5ddef42b3ba502c3357bfa114d74ef5fd57c9dbd
SinCatGit/leetcode
/01246/palindrome_removal.py
2,430
3.9375
4
from typing import List from functools import lru_cache class Solution: def minimumMoves(self, arr: List[int]) -> int: """ #### [1246. Palindrome Removal](https://leetcode.com/problems/palindrome-removal/) Given an integer array `arr`, in one move you can select a **palindromic** subarray ...
574f59a0aa1a4e8d8bc950b522737fd7773f2c88
SinCatGit/leetcode
/00697/degree_of_an_array.py
1,726
3.921875
4
from typing import List class Solution: def findShortestSubArray(self, nums: List[int]) -> int: """ https://leetcode.com/problems/degree-of-an-array/ Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of i...
b8b640b0eb0196e48ebd1e1bee584f3013b0b479
SinCatGit/leetcode
/00305/number_of_islands_ii.py
3,083
3.6875
4
class Point: def __init__(self, a=0, b=0): self.x = a self.y = b class Solution: def numIslands2(self, n, m, operators): """ https://leetcode.com/problems/number-of-islands-ii/ Given a n,m which means the row and column of the 2D matrix and an array of pair A( size k)....
1e59b1fda81ad29f224e5897dd0eb0e0b964ea4a
SinCatGit/leetcode
/00545/test_boundary_of_binary_tree.py
1,512
3.609375
4
import unittest from boundary_of_binary_tree import Solution, TreeNode class TestSolution(unittest.TestCase): def test_Calculate_Solution(self): sol = Solution() # 1 # \ # 2 # / \ # 3 4 node1 = TreeNode(1) node2 = TreeNode(2) ...
d39995fb032fd92e9d2ac8ef2a55239e41d566af
SinCatGit/leetcode
/00053/maximum_subarray.py
1,225
4.03125
4
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: """ https://leetcode.com/problems/maximum-subarray/ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. ...
222d0e68676415d83061c90b7be517bb84e2c01b
SinCatGit/leetcode
/00783/test_minimum_distance_between_bst_nodes.py
633
3.671875
4
import unittest from minimum_distance_between_bst_nodes import Solution, TreeNode class TestSolution(unittest.TestCase): def test_Calculate_Solution(self): sol = Solution() # 5 # / \ # 3 7 # / \ # 1 4 node1 = TreeNode(5) node3...
01e59b8ce636604ad2c157a200f3ab7272bab757
SinCatGit/leetcode
/00046/test_permutations.py
526
3.5625
4
import unittest from permutations import Solution class TestSolution(unittest.TestCase): def test_Calculate_Solution(self): sol = Solution() self.assertEqual( [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]], sorted(sol.permute([1, 2, 3])) ) ...
9b5c4518cce6c3123ea7425d6223a87a1cdbe17a
SinCatGit/leetcode
/00503/next_greater_element_ii.py
1,447
3.828125
4
from typing import List class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: """ https://leetcode.com/problems/next-greater-element-ii/ Given a circular array (the next element of the last element is the first element of the array), print the Next Greater ...
c5eadaf692c43bc0ad5acf88104403ca6b7266dc
HarryVines/Assignment
/Garden cost.py
323
4.21875
4
length = float(input("Please enter the length of the garden in metres: ")) width = float(input("Please enter the width of the garden in metres: ")) area = (length-1)*(width-1) cost = area*10 print("The area of your garden is: {0}".format(area)) print("The cost to lay grass on your garden is : £{0}".format(cost)) ...
e8511086a19a33359f08150992292300602a749a
JRocks1092/Project97
/NumberGuessingGame.py
1,154
3.515625
4
import random appRun = True luckyNumber = random.randint(1,9) attempts = 0 def getRand(): global luckyNumber luckyNumber = random.randint(1,9) def getInp(): LoopRun = True value = None while LoopRun: print("") inp = input("Play Again?(Y/N)") if inp == "Y": ...
408c4d5f241d26072488548aeb5af536b1b48d39
rshelbyruiz/cms_workshop
/geometryanalysis_2.py
2,299
4
4
""" Functions and script for geometry analysis. """ import numpy import os import sys def calculate_distance(atom1, atom2): """ Calculate the distance between the two atoms. Parameters ---------- atom1: list A list of coordinates [x, y, z] aotm2: list A list of coordinates [x,...
74ff6f984fe4a195a487cf0f634224521a93cb8a
danobook/EjerciciosPython3DanielFernandezRamon
/FuncionCrearLista.py
232
3.671875
4
def CrearLista(elementos): Lista = [] aux = 0 while aux < elementos: elemento = int(input(f"Lista[{aux}]=")) Lista.append(elemento) aux += 1 print(f"Lista original = {Lista}") return Lista
0058567d8a504619316fe05d2ca5e9d058f4ea60
ujwalphuyal/ooo
/hw.py
310
3.703125
4
print("welcome to nepal telecome.") duration=int(input("please dail theduration of the call in a min:")) if duration>=10: bonus=duration/2 print(f"Your total bonus is Rs{bonus}") print("HAPPY CALLING") else: print("HAPPY CALLING \n you did'nt reach the limit of call to " "to make bonus")
bbf25807dc06062c1b364c73cecc0a0e40342213
guilistocco/Matrix_Structural_Analysis
/MATRIX STRUCTURAL ANALYSIS – THE STIFFNESS METHOD/Matrix_Structural_Analysis/Stiffiness_Matrix.py
1,376
3.703125
4
class Stiffiness_Matrix(): """ This class initiate the stiffiness matrix on a local system of coordinates of a 2D structure. This means that, after been stablished all degrees of freedom of a Frame, Truss or Grill (not supported), the structure has it's stiffiness determined. This class works ...
64b3cae31b0a05815ea2b06279e4a81dc8878465
queenpriya/assignment-2-
/1st.py
683
4.0625
4
'''print('My Name is priya Singh')''' from itertools import product print('now we take an experiment is of tossing two coins') n=2 sample_space=set(product(['H','T'],repeat=n)) print('Here sample space is = ',sample_space,' : here total number of possible outcomes is = 4') length=len(sample_space) print('here ...
192f7c1967eb6528bcabd7317a7e02d97e05e281
kitten404/PythonProgramacao
/ex024.py
141
3.609375
4
cidade = input('informe a cidade: ') cidade = cidade.lower() cidade = cidade.capitalize() cidade = cidade.split() print(cidade[0] in 'Santo')
fdbddf3393f83acf59ab7dfcab1a1bc31311cf28
kitten404/PythonProgramacao
/ex075.py
350
4.0625
4
n = (int(input('Digite o numero: ')), int(input('Digite o numero: ')), int(input('Digite o numero: ')), int(input('Digite o numero: ')), int(input('Digite o numero: '))) print('o numero 9 apareceu {} vezes'.format(n.count(9))) print('o numero 3 está na posicao {}'.format(n.index(3))) #print('o numero 3...
bc81f93d67de41bf9152d4eadeb99892e5c8f511
kitten404/PythonProgramacao
/ex065.py
520
3.875
4
sair = "" c = 1 media = 0 soma = 0 maior = 0 menor = 0 while sair in 'Ss': n = int(input('Digite o numero: ')) if(c == 1): maior = n menor = n if(n < menor): menor = n if(n > maior): maior = n soma = soma + n print('a soma ...
409b7db5e544866518eb95bf4b813ce699495aab
kitten404/PythonProgramacao
/ex012.py
105
3.5
4
preco = float(input('Digite o valor do produto: ')) print('O preço é R$ {0}'.format(preco-preco*0.05))
5911ff32c36aa94078217006f713b1fc1b99dfb8
kitten404/PythonProgramacao
/ex028.py
229
4.0625
4
import random numero = int(input('informe o número: ')) rand = random.randint(0,5) if numero == rand: print('Vc Acertou, eu pensei no numero {}'.format(rand)) else: print('Vc Perdeu, eu pensei no numero {}'.format(rand))
6e423f9913dcff73cd7bf423fc3bd7a70db06984
garrettleising/algorithms
/divide_and_conquer/closest_pair/closest_pair.py
1,413
3.53125
4
# idk if this code runs correctly btw def closest_pair(P): # len(P) = len(x) = len(y) im pretty sure n = len(P) # partition into two regions mid = n / 2 L = P[:mid] R = [mid:] # get closest pairs line1 = closest_pair(L) line2 = closest_pair(R) # min pair between gradient li...
d11da27eb0f533aeb21d30cc900ba762652f4210
madanreddy-dev/CSV
/wordfeq.py
3,121
3.953125
4
# The following program implements part of a text processing library # importing sys module to use sys.exit() method import sys # converts a string to integer and returns integer value def mk_int(s): s = s.strip() return int(s) if s else 0 # converts input text into a list sorted by most frequent...
a8b857e7c7a7777150af95c03e1efd2ba8a2bb9d
quophil/tictactoe
/main.py
6,075
3.703125
4
from os import system import math #function for clearing the terminal, displaying certain strings and for resetting the grid to its default state def title_display(): system('cls') print('\t###############') print('\t# Tic O X #') print('\t# O Tac X #') print('\t# X O Toe #') print...
0bdffe98db2c467010bd2773db78815ca6cd0d6d
pf1990623/py-gs-lean
/student_day6/xml_module.py
1,870
3.515625
4
""" xml是实现不同语言或程序之间进行数据交换,跟json差不多,但json使用起来更简单,不过,古时候 在json还没诞生的黑暗年代,大家只能选择用xml,至今很多传统金融航悦的很多系统接口主要还是xml """ """ <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"...
704e56acdeed7f6a8ee2535e68d0123c73526585
pf1990623/py-gs-lean
/student day2/oldboy_9.py
269
3.671875
4
# 9、计算用户输入的内容中有几个整数(以个位数为单位)。 # 如:content = input("请输入内容:") # 如fhdal234slfh98769fjdla s = input(">>>") count = 0 for i in s: if i.isdigit() : count +=1 else: continue
e792ad34cb60111537a620dba9b1e40534a5fa80
pf1990623/py-gs-lean
/student_day6/os_module.py
3,610
3.65625
4
import os """ os 模块,俗称系统模块,显 在自动化测试中,经常需要查找操作文件, 比如说查找配置文件(从而读取配置文件的信息), 查找测试报告(从而发送测试报告邮件), 经常要对大量文件和大量路径进行操作, 这就依赖于os模块,所以今天整理下比较常用的几个方法。 网上这方面资料也很多, 每次整理,只是对自己所学的知识进行梳理,从而加深对某个模块的使用。 """ """ os.getcwd() 获取当前文件所在目录,返回字符串类型 #返回当前工作目录 """ os_module = os.getcwd() print(type(os_module)) print(os_module) """...
6f72a28fb04253b29154b8b02a18be29d5f66b7a
pf1990623/py-gs-lean
/student day2/oldboy_3.py
120
3.59375
4
# 3、使用while或for循环分别打印字符串s = "asdfer"中每个元素。 s = "asdfer" for i in s: print(i)
8de41be731b5cb3f3705ce5754171bfd7b2d1aa2
pf1990623/py-gs-lean
/student_day7/总结.py
1,795
3.625
4
#!/usr/bin/env python # encoding: utf-8 """ @version: 1.0 @author: panfeng @license: Apache Licence @file: 总结.py @time: 2018/12/19 14:56 """ """ 1、什么是面向对象编程? 以前使用函数 类 + 对象 2、什么是类,什么是对象,又有什么关系 class 类 def 函数1(): pass def 函数2(): pass # obj是对象,实例化的过程 obj = 类() ...
979f45ff9a1d46849ad0016cc6bec930b5cb78ce
pf1990623/py-gs-lean
/student_day3/oldboy_4.py
844
3.625
4
# 4、 写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。 # dic = {"k1": "v1v1", "k2": [11,22,33,44]} # PS:字典中的value只能是字符串或列表 dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]} def fun4(dict_data): for k in dict_data.keys(): print(k, dict_data.get(k)) if len(dict_data.get(k)) > 2: ...
9c976a39c1695f333ba153af36094abee9c1f0d0
pf1990623/py-gs-lean
/student_day4/装饰器_导入模块.py
907
3.515625
4
import auth """ 此方法调用,需要写模块名+函数名 例如 auth模块的login方法,就要使用下面的方法: auth.login 另外一种方法from 导入模块 from 模块名 import 函数名 """ def home(): print("--------首页--------") def America(): print("------美国专区------") @auth.login def henan(): print("------河南专区------") @auth.login def Japan(): print("------日韩专区------") # ...
fd889c08bf44410c2fdb6840bd10c92eb7669e8c
pf1990623/py-gs-lean
/student day2/oldboy_练习2天.py
18,043
4.46875
4
# 练习题: name = " aleX leNb " # 1、有变量name = "aleX leNb" # 完成如下操作: # 1) 移除name变量对应的值两边的空格, 并输出处理结果 print(name.strip()) # 2) 移除name变量左边的"al"并输出处理结果 print(name.lstrip('al')) # 3) 移除name变量右面的"Nb", 并输出处理结果 print(name.rstrip('Nb')) # 4) 移除name变量开头的a"与最后的"b",并输出处理结果 print(name.rstrip('b').lst...
1b9da2d5898ed249f7a609c62ad202a9f5d7261b
pf1990623/py-gs-lean
/day3/数字位数判断.py
347
3.78125
4
num = int(input("输入1-99999范围的整数:")) print(len(num)) if 1 <= num <= 9: print("1位数") elif 10 <= num <= 99: print("2位数") elif 100 <= num <= 999: print("3位数") elif 1000 <= num <= 9999: print("4位数") elif 10000 <= num <= 99999: print("5位数") else: print("输入的数错误,请重新输入")
6487717bfd3065b175553849f2c7c705ec18f2db
Eddielopez11/dailyWorkandAssignments
/week_2/selectingFirstCharacter.py
152
3.59375
4
# coding: utf-8 s = 'never will i be able to forget piglatin' s = s.split() s for word in s: print([0]) for word in s: print(word[0])
c9dadcd37ac16013e6a9c23aa3afe411bacd400e
jhuang09/GWC-2018
/Data Science/attack.py
2,488
4.34375
4
# This project checks to see if your password is a strong one # It works with longer passwords, but not really short ones. # That's because since each letter is considered a word in the dictionary.txt file, # any password that contains just letters will be considered as a word/not a strong password. # To alleviate ...
32c4a398d4cc157611fb6827fce531ecbb82f431
GeraldShin/PythonSandbox
/OnlineCode.py
1,851
4.28125
4
#This will be snippets of useful code you find online that you can copy+paste when needed. #Emoji Package #I don't know when this will ever be helpful, but there is an Emoji package in Python. $ pip install emoji from emoji import emojize print(emojize(":thumbs_up:")) #thumbs up emoji, check notes for more. #List ...
b9982c58ff12aa05a6bcf1369ea7c0ec2cbec49e
Deepaksinghmadan/Class-behaviour
/ExcepionPractise.py
529
3.59375
4
class MobileNumberError(Excepion):pass class MobileNuberNot Valid(Exception):pass try: number = int(input("?")) if len(str(number))!=10: raise MobileNumberError if int(str(number)[0])<6: raise MobileNuberNot Valid except valueerror: print(" error") except MobileNumberError: print("not a ten digit") ...
9e304793cd98bac00cc967be51c1c3da49dd8639
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/ReverseEveryAscending.py
2,396
4.46875
4
# Create and return a new iterable that contains the same elements as the argument iterable items, but with the reversed order of the elements inside every maximal strictly ascending sublist. This function should not modify the contents of the original iterable. # Input: Iterable # Output: Iterable # Precondition: I...
b440d0252e9ed8a9bc3f84b569a31f819225302a
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/DateTimeConverter.py
1,685
4.5
4
# Computer date and time format consists only of numbers, for example: 21.05.2018 16:30 # Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes # Your task is simple - convert the input date and time from computer format into a "human" format. # example # Input: Date and time as a string # ...
da0e4fcf1b6b2d494d1a5ecb1611cc544e1722f5
Isaac-D-Dawson/Homework-Uploads
/Co-19-HW/AcronymQuirkedV2.py
4,621
3.640625
4
#AcronymQuirked.py 23.03.2020, Version 2 created 26.03.2020 # PATCH NOTES: # V1.0: initial release. # -Function takes strings and retuns acronyms of them. # V2.0: # -New function: pre_format() takes in a string and removes any special chars that would skew the output. # -Clarified existing Logic. # FUTURE PLANS: #...
239f81592f5c85411d53ced66e13b7ec94218b97
Isaac-D-Dawson/Homework-Uploads
/PyCheckIO/MedianOfThree.py
1,536
4.375
4
# Given an iterable of ints , create and return a new iterable whose first two elements are the same as in items, after which each element equals the median of the three elements in the original list ending in that position. # Wait...You don't know what the "median" is? Go check out the separate "Median" mission on Ch...