blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
88a84c0dca713f2af23b236fbcbbc2e1cd3d141c
conalryan/python-notes
/serializing_data/json_read.py
638
3.78125
4
#!/usr/bin/env python import json # Open JSON file for reading with open('data/solar.json') as solar_in: # Load from file object and convert to Python data structure solar = json.load(solar_in) # json.loads(STRING) # json.load(FILE_OBJECT) # print(solar) # Solar is just a Python dictionary print(solar...
bca0fd15f3827b518dd3e583156466aa93752b80
WonderLuc/brother-bootcamp
/python 101/tasks/skeletonsModule/base.py
988
3.546875
4
# Basic functions def createSkeleton(name, id, health=20, damage=10): id = id + 1 return { 'name' : name, 'health' : health, 'damage': damage, 'id': id } def add(skeleton, army): army.append(skeleton) def find(id, army): for unit in army: if (unit['id'] == id): return unit return 0 d...
c2213b7e4e4fa9ce72a6770ff20d214bb1125ef5
melissamangos/ProjectEuler
/problem1.py
333
3.96875
4
# Melissa Mangos # Project Euler Problem 1 # Find the sum of all the multiples of 3 or 5 below 1000 # Answer: 233168 # General function, takes final range as a parameter def sumMultiples(rng): s = 0 for i in range(1, rng): if (i % 3 == 0 or i % 5 == 0): s += i; return s # Case of multiples 3, 5 below 1000 pri...
09172aacd60e7d7b00b39fffe191ccb571fe0665
brdyer/DAEN_500_Fall_2020_Final_Exam
/DAEN_500_final_prob_1.py
892
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 8 08:21:51 2020 @author: braddyer """ # get user input of range for analysis usr_range_start = int(input('Enter the low end of the range you want to try: ')) usr_range_end = int(input('Enter the high end of the range you want to try: ')) # determ...
ab61c9a7b637d62752dafe6351fbf36903a45f70
TF-185/cra-princess-cp1
/src/cp1_src/cp1/common/exception_class.py
13,939
3.546875
4
"""exception_class.py Module contains custom exception classes. Author: Tameem Samawi(tsamawi@cra.com) """ class ChannelGeneratorException(ValueError): """Raise for inavalid values passed into the ChannelGenerator.generate() function""" def __init__(self, message, source=''): """Constructor ...
e993a36199c89bd88467b9bf6eb9e3d3ba4aa573
CiQiong/Python
/month.py
182
3.59375
4
#month.py months="JanFebMarAprMayJunJulAuqSepOctNovDec" n=input("请输入月分数(1-12):") pos=(int(n)-1)*3 monthAbbrev=months[pos:pos+3] print("月份简写是:"+monthAbbrev+".")
0416cb23cfefbd5c34d8f52e7dc9198cf96c9f83
MrRaisin/SFO2
/human class.py
1,599
3.90625
4
class Human(): def __init__(self, age = 0, name = "unknown", gender='unknown'): self._gender = gender self._age = age self._name = name def setName(self, name): self._name = name def getName(self): return self._name def getGender(self): ret...
e9c69e5f79021648611b72493749e80cdd385778
Ahmedtronic/AItronic
/Advanced Implementation ( from scratch )/Machine Learning/Other/Thompson Sampling/Thompson Sampling.py
1,400
3.6875
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random dataset = pd.read_csv("Ads_CTR_Optimisation.csv") n_items = 10 n_trials = 10000 n_ones = [0] * n_items # Number of rewards of each item n_zeros = [0] * n_items # Number of punishments of each item total_rewards = 0 # Total gained rew...
e2d5c91e22940d1f07cca108bf9200fa56f97736
moschettoiago/github_class
/Fibonacci.py
366
4.125
4
def fibonacci(): a = int(input("How many fibonacci numbers do you want? ")) i = 1 fib = [] if a == 0: fib = [] elif a == 1: fib = [1] elif a == 2: fib = [1, 1] elif a > 2: fib = [1, 1] while i < (a-1): fib.append(fib[i] + fib[i-1]) ...
cc962a87b116053d6be869e2398a3ac877891683
Bhavikpatel576/Leet_Code
/Data_Structures/Binary_Search_Tree/098_Validate_Binary_Tree.py
1,952
4.03125
4
# **************************************************************************** # # # # ::: :::::::: # # 098_Validate_Binary_Tree.py :+: :+: :+: ...
64e31f3aca7176a5d0524876b4aaee107dd1d8b6
noite-m/nlp2020
/chart1/practice06.py
902
4.125
4
""" “paraparaparadise”と”paragraph”に含まれる文字bi-gramの集合を, それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,’se’というbi-gramがXおよびYに含まれるかどうかを調べよ. """ def nGramWord(text, num): #スライス result = [text[index : index+num ] for index in range(len(text)-num+1)] return result #n_Gramに入れる X = nGramWord("paraparaparadise", 2) Y...
7e1bc725d724a3f51d88fb043880995d1764b833
chowdhurynawaf/URI-SOLVE
/1114.py
138
3.859375
4
x = int(input()) s = 2002 while(x != s): print("Senha Invalida") x = int(input()) if (x == s): print("Acesso Permitido")
c193dcc39431563f4b6b716320983a6388715900
ankiwoong/Check_Io
/Home/SplitList.py
1,866
4.25
4
''' Split List You have to split a given array into two arrays. If it has an odd amount of elements, then the first array should have more elements. If it has no elements, then two empty arrays should be returned. example Input: Array. Output: Array or two arrays. Example: split_list([1, 2, 3, 4, 5, 6]) == [[1, 2,...
9217f32ef67c6f4c6b0c1e8b310ab98292f049e7
enjey00/Chapter-4
/task2.py
881
3.953125
4
class Airplane: def __init__(self, make, model, year, max_speed): self.make = make self.model = model self.year = year self.max_speed = max_speed self.odometer = 0 self.is_flying = False print(make, model, year, max_speed) def take_off(self): ...
77a5f6c22fa5f86b9a55427fb15d146487adc8c2
mdinacci/rtw
/game/src/utils.py
579
3.796875
4
# -*- coding: utf-8-*- """ Author: Marco Dinacci <dev@dinointeractive.com> Copyright © 2008-2009 """ def tenthsToStrTime(time): tens = time % 10 seconds = (time / 10) % 60 minutes = (time / 10) / 60 if tens == 0: tens = "0" if seconds == 0: seconds = "0" return "%d:%s....
b416483f1a28da193c8a0188ab09534485c0bd77
Puthiaraj1/ExceptionHandling
/except_examples.py
332
4.125
4
def factorial(n): # n! cak also be defines as n * (n-1) """ Calculate n! recursively""" if n <= 1: return 1 else: return n * factorial(n - 1) try: print(factorial(900)) except (RecursionError, ZeroDivisionError): print(" This program calculate factorial that large") print("Pro...
80ef4106ab61798ced52bb1258d45bfa4918a0cf
IvanFekete/fatic-dialogue
/dialog.py
2,499
3.53125
4
import random #download information will be used from files commonQuestions = [] commonAnswers = [] questionsWithPattern = [] answersWithPattern = [] invitePhrases = [] byePhrases = [] words = [] isQuestion = lambda sentence: sentence.find("?") != -1 containsPattern = lambda sentence: sentence.find("*") != -1 def d...
54fea13a3cfe69595b14bac79f46b054344a9823
ho-kyle/python_portfolio
/088.py
515
4
4
def validTriangle(a, b, c): Max = max(a, b, c) if Max < a + b + c - Max: isValidTriangle = True return(isValidTriangle) else: isValidTriangle = False return(isValidTriangle) def main(): a, b, c = eval(input('Please enter 3 lengths: ')) if a > 0 and b > 0 and...
e73b61674fd1955364d0b6cfe8df58d3b3e82c20
chenxy3791/leetcode
/No0213-house-robber-ii-medium-dp.py
3,023
3.75
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 15 07:24:23 2021 @author: chenxy 213. 打家劫舍 II 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 , 这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻 的房屋在同一晚上被小偷闯入,系统会自动报警 。 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。 示例 1: 输入:nums = [2,3,2] 输出:3 解释:你不能先偷窃 1 号房屋(金额...
a0936ea8473419b0ae8c597c2bbb0ea1af246d70
explodes/euler-python
/euler/problems/euler20.py
814
3.9375
4
#!/usr/bin/env python from euler.lib.maths import factorial, sum_of_digits from euler.problems.registry import register VALUE = 100 def sum_of_factorial_digits(n): return sum_of_digits(factorial(n)) @register class Euler: """ n! means n * (n - 1) * ... * 3 * 2 * 1 For example, 10! = 10 * 9 * ... *...
6376410463e3d1b069541122349eadc01a34dc9f
geekvinay/practice-your-basics
/python/quesn43.py
166
3.96875
4
# Solved question 43 # Remove duplicates from a string. d = {} s=input() res=[] for c in s: if c not in d: res.append(c) d[c]=1 print ("".join(res))
962c268a1595890cf928acbadbc9f4e7a1b0de65
soumya-mishra/Python
/Decorator_Generator.py
729
3.78125
4
from functools import wraps def get_ready(gen): """ Decorator: gets a generator gen ready by advancing to first yield statement """ @wraps(gen) def generator(*args,**kwargs): g = gen(*args,**kwargs) next(g) return g return generator @get_ready def infi...
28bf638236f9576aa8b0ba76148621bad64c9477
Dave-Perkins/Fall-2020-CS-101
/project code/project 2/character.py
1,767
3.921875
4
from nltk import* from nltk.corpus import* from matplotlib import pyplot as plt #takes a character name and a text(in the form of a string not a file) and returns #a list of numbers which each unumber is the Nth word in the text def character_word(character, words): wordPlaces = [] for wordNum in range(len(wo...
38ac5b980de97d78679d06903d9e07d2fb3892c6
GaikwadHarshad/ML-FellowShip-Program
/WEEK 1/program11.py
318
4.03125
4
""" Write a Python program to check whether a file exists. """ from os import path # it will return boolean value True if file exist and False if does not exist print("File Exist : "+str(path.exists('abc.txt'))) print("File Exist : "+str(path.exists('raw.txt'))) print("File Exist : "+str(path.exists('text.txt')))
c479f662b21dc3ebab5d0d617ed72b70db1e32fa
rohankumar997/Magic_calculator
/main.py
6,249
4.0625
4
import tkinter as tk import os #TKINTER_PROGRAMME_STARTS temp = "" def main(): root = tk.Tk() root.geometry("500x200") root.title("Magic Calculator") #this function is used to get the data from the button and insert into the Entry_input text def get_data(a): global temp te...
9827bf8bf5457c02ea2d48d7c110edb29039a621
johnnickell24/python-152
/HW6/HW6v3.py
2,804
4.28125
4
""" Description: """ _author_="John Nickell" _date_="10/30/14" #functions """ pre-condition: None Description: This is the menu where the user will pick what function is used to count parts of the sentence inputed. """ def printMenu(): print("1) Number of Vowels") print("2) Number of Consonants") ...
cadeeabe7f824aca1e7fa2d0718dbbdfe1c0d9d0
gustavscholin/advent_of_code_2020
/task_22/task_22_2.py
1,212
3.640625
4
def read_input(path): with open(path, 'r') as f: player_1, player_2 = f.read().split('\n\n') player_1 = [int(i) for i in player_1.splitlines()[1:]] player_2 = [int(i) for i in player_2.splitlines()[1:]] return player_1, player_2 def recursive_game(player_1, player_2): player_de...
90145d70ba9fa06c96211cf2b7ed4f004f4de8a8
rojcewiczj/Javascript-Python-practice
/Python-Practice/graphTraversal.py
581
3.796875
4
graph = [[1,2],[3],[3],[4],[]] all_path = [] def traverse(starting_node, ending_node): all_path = [] stack = [[starting_node]] while(len(stack) > 0): current_path = stack.pop(-1) current_node = current_path[-1] if current_node == ending_node: all_path.append(current_pa...
590fad3ee55aa362c056e2f306ec934f2db63ba6
calaphos/discord-chess-bot
/coordinates.py
1,552
4.03125
4
class Coordinate(): """This is a class for handling chess coordinates. It does bounds checking, defines movement operations and is used to translate between the internal (0,0) based coordintes system to the common (a,1) based chess system""" def __init__(self, *args :int): self.x, self.y = args ...
c51288eb7a84ecd015f84538414f2e3b432e6e19
Dynortice/Project-Euler
/problems/0039/compute.py
427
3.5625
4
from math import isqrt, sqrt def compute(n: int) -> int: perimeters = {} for a in range(3, n // 3): for b in range(a, n // 2): k = a * a + b * b if sqrt(k) % 1 == 0: p = a + b + isqrt(k) if p in perimeters: perimeters[p] += 1 ...
6d08454da7f8c3b15ec404505a6b77b9192e570e
breschdleng/Pracs
/fair_unfair_coin.py
1,307
4.28125
4
import random """ Given an unfair coin, where probability of HEADS coming up is P and TAILS is (1-P), implement a fair coin from the given unfair coin Approach: assume an unfair coin that gives HEADS with prob 0.3 and TAILS with 0.7. The objective is to convert this to a fair set of probabilities of 0.5 each Solution...
df3dbbe2f82adff6f850b186856eb231f2a12fbb
DmitryVlaznev/leetcode
/1473-paint-house-iii.py
3,135
3.734375
4
# 1473. Paint House III # Hard # There is a row of m houses in a small city, each house must be painted # with one of the n colors (labeled from 1 to n), some houses that have # been painted last summer should not be painted again. # A neighborhood is a maximal group of continuous houses that are # painted with the ...
29f7246dc6a7c71d990d55384de6d3403f5e4264
Aasthaengg/IBMdataset
/Python_codes/p02724/s897691778.py
101
3.515625
4
X=int(input()) a=X//500 if X%500==0: print(a*1000) else: b=(X-500*a)//5 print(a*1000+b*5)
56eab87d5cf5d8b73875bbdb56aee633e89a2eaf
RajeevPrakashAD1/python_projects
/ping pong game/scoreboard.py
463
3.609375
4
from turtle import Turtle class Scoreboard(Turtle): def __init__(self,x,y): super().__init__() self.penup() self.color("red") self.hideturtle() self.goto(x,y) self.lscore = 0 self.write(f'{self.lscore}',align="center",font=("Areial",80,"normal")) def u...
6c9ec3306f0ed0abec63c356dbee57f0dbbee991
huilizhou/Leetcode-pyhton
/algorithms/101-200/119.pascals-triangle-ii.py
750
3.59375
4
# 杨辉三角II class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ # 我的解法 res = [] for i in range(34): res.append([1] * (i + 1)) for j in range(1, i): res[i][j] = res[i - 1][j - 1]...
578783038454cb17a490ca9cb4104e33531f8f5b
AlphaProgramador-Edutech/edutech-pr
/Urna_eletrônica.py
1,098
3.921875
4
print ('URNA ELETRONICA') print("1 - João") print("2 - José") print("3 - Jaco") print("4 - Jobe") print("5 - Nulo") print("6 - Branco") print("Digite 0 para encerrar as eleições!") Joao = 0 Jose = 0 Jaco = 0 Jobe = 0 Nulo = 0 Branco = 0 Voto = -1 # Quando o usuário digitar 0, a votação irá parar e se...
b9d6d28dbc58d7b4901440aa9b234283fe90cfa4
manu9812/programming-oriented-objets
/operar/Calcular.py
1,955
4.40625
4
"""en este programa se pretende realizar algunas operaciones como lo son sumar, restar, relaizar el area de un circulo, realizar el teorema de pitagoras el rpograma es realizado por: Manuela Garcia Monsalve el dia 20 de abril del 2018""" import math # se importa la libreria math con el objetivo de reali...
96b045676303e0b557639b774139fe66e0b11fde
Guent4/pydisplay
/Drawables.py
13,900
4.125
4
import pygame from pydisplay import Colors from pydisplay import Events class Drawable(object): def __init__(self, x, y, width, height): """ This class is just the most basic level of anything that should be drawn on the screen. Lines, buttons, etc. are all children classes of ...
36c4d4001b93f82cb67c9207025e40a190734ca2
Aasthaengg/IBMdataset
/Python_codes/p03385/s730279749.py
123
3.53125
4
s=input() a=s.count('a') b=s.count('b') c=s.count('c') if (a==1 and b==1 and c==1): print("Yes") else: print("No")
6c801e4eb6043227a54df479b6382808f56b77b2
wrj27/willjames-python
/6BLab/6BLab.py
1,326
3.703125
4
monthsOfTheYear = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] weekends = {monthsOfTheYear[0]: [6,7,13,14,20,21,27,28], monthsOfTheYear[1]: [3,4,10,11,17,18,24,25], monthsOfTheYear[2]: [3,4,10,11,17,18,24,25,31], monthsOfTheYear[3]: [1,7,8,14,15,21,22,28,29], monthsOfTheYear[4]: ...
844620489692f14405f6486312d1b06e5bdaedb1
HelloiWorld/PythonPracticeDemo
/practice/test3_高级特性_迭代.py
619
4.03125
4
# -*- coding: utf-8 -*- # 高级特性->迭代 # 练习 # 请使用迭代查找一个list中最小和最大值,并返回一个tuple: def findMinAndMax(L): if len(L) > 0: min = L[0] max = L[0] for v in L: if v < min: min = v if v > max: max = v return min, max return (None, None) ...
b2b92889ff1c19758960f183c13e844e41d40205
dfyz/adventofcode
/2015/03/sln_hard.py
453
3.671875
4
import sys msg = sys.stdin.readline().strip() def visit_cities(program): visited = set([(0, 0)]) x = 0 y = 0 for ch in program: if ch == '^': y -= 1 elif ch == '<': x -= 1 elif ch == 'v': y += 1 else: assert ch == '>' x += 1 visited.add((x, y)) return visited santa_visited = visit_citie...
eebde52e90b09a7237e63f1d380da8207c2ecc81
sumonbis/TestDatagen
/test.py
1,469
3.96875
4
x = 1 print "This is Python 2 program" if x == 1: print("x is 1.") if x == 1 and 5 > 3: print("Print this.") myfloat = float(7) print(myfloat) hello = "hello" world = "world" helloworld = hello + " " + world print(helloworld) x = 5 + 6 + 2 - 9 / 6 * 3 a, b = 3, 4 print(a,b) mylist = [] mylist.append(1) ...
aefc03ca1d373db57f827923814d6f550a115291
thomascwilliams83/PhD_project
/Python/Python exercises/Day 2/Processing DNA in a file simple.py
473
3.671875
4
#Simpler alternative for processing DNA in a file #create file that contains data dna_sequence = open("E:\data files\input.txt") #don't need to create list of strings as Python does this automatically for files #Create new document Clean_sequence = open("Clean_dna_simple.txt","w") #trim out adaptor for string in d...
13507f79058722645580c27ffdd1598d0fb34694
kellyseeme/pythonexample
/219/for.py
318
3.84375
4
#!/usr/bin/env python """this is for test for to strip this is to strip the \n of the list first use the enumrate to get the index and value. second use the strip to cut the \n """ a = [["abc\n","kellyseeme\n"],["kel\n"]] for k,m in enumerate(a): for i,n in enumerate(m): print a[k][i].strip()
abd531df8fd0374f0245204731a2cc81a3edc5bc
LittleBlue418/CI_py_quizz
/quiz.py
2,827
4.4375
4
def show_menu(): # Showing options print("1. Ask questions") print("2. Add a question") print("3. Exit game") # Defining a variable and populating it with the user choice # Returning that choice variable option = input("Enter option: ") return option def ask_questions(): # Defining...
5351523b868b0100e1937832ad4c1714b4be5751
AdamZhouSE/pythonHomework
/Code/CodeRecords/2069/60616/265027.py
118
3.984375
4
def multiply(num1, num2): return str(eval(num1 + '*' + num2)) num1=input() num2=input() print(multiply(num1,num2))
712c6c2ffdd38251569baf2d5a79d306c58dcdca
ismailsinansahin/PythonAssignments
/Assignment_12/Question_57.py
543
4.5625
5
""" Given a square matrix, calculate the absolute difference between the sums of its diagonals. For example, the square matrix is shown below: 1 2 3 4 5 6 9 8 9 The left-to-right diagonal = 1+5+9 = 15. The right to left diagonal = 3+5+9 = 17. Their absolute difference is |15-17| = 2. """ matrix = [[1,2,3],[4,5,6],[9...
d8116f6033b7ae923e5475d8c3f7e627e65a6b4d
TexasAppz/Binary-Search-Tree-in-Python
/bst.py
23,407
4.0625
4
# Course: CS261 - Data Structures # Student Name: # Assignment: # Description: class Stack: """ Class implementing STACK ADT. Supported methods are: push, pop, top, is_empty DO NOT CHANGE THIS CLASS IN ANY WAY YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS CLASS IN YOUR SOLUTION """ de...
e1c0d2934c4520e9cd2f8288486e86827eed5c98
lainekendall/CS61A
/Lecture/Lec2:6.py
3,126
3.984375
4
Lec2/6.py 1 pimentel but check!! no lab on Tues!!! hog strategy contest concludes 2/18 11:59pm Abstraction: giving a name to something Fuctional Abstraction What does sum_squares need to know about square? needs to know that square takes one argument need to know its name do you need to know square's intrin...
4bd17fda3073952e3750e299857cdd3e485b6f35
nandakishore723/cspp-1
/cspp1-assignments/m22/assignment5/frequency_graph.py
576
4.15625
4
''' @author : nandakishore723 Write a function to print a dictionary with the keys in sorted order along with the frequency of each word. Display the frequency values using “#” as a text based graph ''' def freq_graph(dictionary): """frequency graph""" keys = sorted(dictionary.keys()) for key in keys: ...
2869e02289ba40b6d5e1180f31f124953006a19d
finnwilliams16/projects
/Machine Learning/K Means Clustering/Dog Classification/K Means Dog Classifier.py
2,791
3.71875
4
from matplotlib import pyplot as plt import random, math plt.title("Big Dogs and Small Dogs") plt.ylabel("Height (cm)") plt.xlabel("Weight (kg)") def euclideandis(x, y, a, b): # Formula for euclidean distance return math.sqrt((x-a)**2 + (y-b)**2) x = {5:31, 3.2:19, 4.6:32, # Data- key = weight...
14f6351c55babea3d04671b0cc5acf604e1decb5
t83955832/260201076
/lab5/ex4.py
295
3.859375
4
definePassword="abc123" while True: password=input("Please enter your password : ") if password==definePassword: print("Welcome") break else: if password=="help": print(definePassword[0]) else: print("Wrong")
2607a96a3b809081e81ce1658ebc52208cf1d0fd
Srinivas-Rao-au27/Accomplish_classes-
/coding-challenges/week12/day05/week12-day05-cc.py
3,424
4.125
4
""" Q-1 ) Convert Sorted Array to Binary Search Tree https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ (5 marks) (Easy) Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary t...
7142bc069072b2eada072996fdcf75851e28fa4f
rajagoah/Statistical_Thinking_in_python_1
/ExploratoryDataAnalysis/BernoullisTrial2.py
274
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 8 15:42:30 2020 @author: aakarsh.rajagopalan """ import matplotlib.pyplot as plt import numpy as np import seaborn as sns print(np.random.binomial(n = 3, p = 0.1, size = 10)) print(np.random.random())
bad9846c32901a656bd0bd0603001d34f0dc500f
samatbryan/ProgrammingContests
/binarysearch.com/WC38/1_TreeWIthDistinctParities.py
657
3.5
4
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def solve(self, root): res = 0 def f(node): if not node: return 0 nonlocal res le...
c2bebb5395dd4ea6cc4f7f1c87f2536be28359e7
MaoningGuan/LeetCode
/剑指 Offer(第 2 版)/movingCount.py
2,707
3.75
4
# -*- coding: utf-8 -*- """ 剑指 Offer 13. 机器人的运动范围 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外), 也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子? 示例 1: 输入:m = 2, n = 3, k = 1 输出:3 示例 2: 输入:m = 3, n = 1, k = ...
30b4bc8cb1307b01a3f3042a2d1943e734cfeb16
engelcituk/python-bases
/extras/types.py
553
3.921875
4
#las anotaciones son de caracter unicamente informativo #los tipos de datos con los que podemos trabajar son: str,int, float y bool #saludo recibe como parametro nombre de tipo string y que no regresa nada la funcion def saludo(nombre: str) -> None: #la flecha indica el tipo de dato que retorna la funcion print("...
ababf7b967d0cfad7cfaeec59cc88dab98cd723a
rohan47/iw-ques-soln
/snake_game.py
1,594
3.984375
4
#!/usr/bin/python3 import random players = {} initial_position = 0 win = 100 snakes = {12:4, 45:32, 67:5, 99:1} ladders = {3:43, 23:56, 38:78, 66:98} # Removes the player if he wins def remove_player(player): print("\n\n{} Won!\n\n".format(player)) players.pop(player) # Updates the position of the player de...
0a426461e0f7a11d13da5208c6294e974694ec61
chuck2kill/CoursPython
/chapitre_5/liste_propre.py
390
4
4
# programme 2 page 45 # permet d'afficher de manière "propre" # une liste composées de strings # déclaration de la liste et d'un compteur t1 = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'] i = 0 # boucle de traitement while i < len(t1)...
44036e07b09c83689e01fd10b8c52493f6f3794f
lidongze6/leetcode-
/练习05-旋转数组.py
1,169
3.6875
4
def rotation_matrix(matrix): """ 空间复杂度o(1) 实现顺时针旋转90° """ l = len(matrix) layer = len(matrix) // 2 for i in range(layer): for j in range(i, l - i - 1): tmp = matrix[i][j] # left-->top matrix[i][j] = matrix[l - j - 1][i] # top:行不变,列滑动,故行为i,列为j ...
6bad80305f664f587562117a1f6f849df25fca9b
ericqian1/poker_sim
/utils.py
6,493
3.625
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 4 13:54:27 2019 @author: eric.qian """ from collections import Counter from itertools import combinations # Numeric hand rankings, higher integer value is stronger hand HAND_RANKINGS = {0: 'High Card', 1: 'One Pair', 2: 'T...
805f031841399aad57b7dc6d3f6e2c4b8b47aa25
badwal/Self-Driving-Car
/lanes_video.py
3,716
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 25 03:28:07 2019 @author: TP """ import cv2 import numpy as np def make_coordinates(image, line_parameters): slope, intercept = line_parameters print(image.shape) y1 = int(image.shape[0]) """height, width, no. of channels = shape""" ...
be0b58aed03a0a4b8911032f1fcb71f209bfdc3d
zingpython/february2018
/day_six/selectionsort.py
414
3.921875
4
def selectionSort(starting_list): new_list = [] while len(starting_list) > 0: print(starting_list, new_list) lowest_index = 0 for index in range(0,len(starting_list)): if starting_list[index] < starting_list[lowest_index]: lowest_index = index removed_value = starting_list.pop(lowest_index) new...
d88d40cf93f086715d847bde44082432a1c597ce
hminaya/learnpythonex
/ex21.py
697
3.9375
4
def add(a, b): print "ADD %d + %d" % (a,b) return a + b def substract(a, b): print "SUBS %d - %d" % (a,b) return a - b def multiply(a, b): print "MULT %d * %d" % (a,b) return a * b def divide(a, b): print "DIV %d / %d" % (a, b) return a / b print "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" print "*Math.........
8127861df635f684d3403c2baf3deeba404d6966
feecarvalho/URI
/URI_1036.py
357
3.578125
4
import math valores = input().split(" ") A, B, C = valores try: if A != 0: delta = (pow(float(B), 2)) - 4 * float(A) * float(C) x1 = (-float(B) + math.sqrt(delta)) / (2 * float(A)) x2 = (-float(B) - math.sqrt(delta)) / (2 * float(A)) print('R1 = %0.5f\nR2 = %0.5f' % (x1, x2)) exce...
952272e95dca685fd1f4db88053fb9654880a706
KartikKannapur/Programming_Challenges
/HackerEarth/Little_Deepu_and_Array.py
303
3.546875
4
__author__ = "Kartik Kannapur" # N = Size of the array N = raw_input() # Elements in the array arr_input = raw_input() arr = [int(s) for s in arr_input.split(" ")] M = raw_input() for i in range(0, int(M)): X = raw_input() arr = [ele-1 if ele>int(X) else ele for ele in arr ] print " ".join(map(str, arr))
ac36f307a30675f9dba495f3de4c147e81faa299
purelind/fluent-python
/chapter2/Example2-12.py
307
4.125
4
# -*- coding: utf-8 -*- board = [['_'] * 3 for i in range(3)] print(board) board[1][2] = 'X' print(board) weird_board = [['_'] * 3] * 3 print(weird_board) #: Placing a mark in row1, column 2, #: reveals that all rows are aliases referring to the same object. weird_board[1][2] = '0' print(weird_board)
8e96fd4f505bdccc8d4f6f1cfe839cf7675458d5
daniel-reich/turbo-robot
/WY7r2XtarpupNDWE8_6.py
1,722
4.34375
4
""" Create a function (given the number of discs and the move number) that returns as a tuple the towers with their correct disks in order. ### What is Tower of Hanoi? Tower of Hanoi is a problem in occursion, where you have to move a certain amount of discs from one peg (or tower) to the final peg. The discs are ...
de93dbfa74bf362fa5d3528dcb9b210f0b641594
nobinson20/codingChallenges
/FloodFill_bfs.py
937
3.890625
4
class Solution: """ @param image: a 2-D array @param sr: an integer @param sc: an integer @param new_color: an integer @return: the modified image """ def floodFill(self, image, sr, sc, new_color): # Write your code here max_row, max_col, original_color = len(im...
6d48e4cc0b9c13b1e44259d4c4c742445cedc3bd
pvardanis/Deep-learning-with-neural-networks
/Codes/sentdex/RNN_examples/deep_set.py
3,608
3.890625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("tmp/data", one_hot=True) n_nodes_hidden_layer_1 = 500 n_nodes_hidden_layer_2 = 500 n_nodes_hidden_layer_3 = 500 n_classes = 10 # feed data in form of batches batch_size = 100 # matrix = height*wid...
e20ce289ad078a86627bc4f76c624f5b35e8ceb9
Wisdom-Miley/PythonChallenge
/Pybank/main.py
2,607
4.0625
4
import os, csv from pathlib import Path # input the csv file input_file = Path("PythonChallenge","Pybank","budget_data.csv") # Create the variable at the list months = [] total_revenue = [] monthly_revenue_change = [] # Open csv with context manager with open(input_file,newline="", encoding="utf-8") as ...
34d35b73ea04c8032919991c2beb903d96297e25
Roo4data/Tea_supervisedML
/arg_examples.py
1,155
3.890625
4
""" argmax(a, axis=None, out=None): Returns the indices of the maximum values along an axis. Parameters ---------- a : array_like Input array. axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis. out : array, optio...
3f518b255739eaec49c1f841ee3cf75c1ac8eeb6
Hamng/hamnguyen-sources
/python/decorator_example.py
2,129
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 20:28:39 2019 @author: Ham HackerRanch Challenge: Standardize Mobile Number Using Decorators Let's dive into decorators! You are given N mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx T...
0288ed894da0482378bdb3cf79ca8bfb2da0cb52
lithces/tpps
/neuralTPPs/tpp/utils/sequence.py
2,818
3.5
4
""" Adapted from torch.nn.utils.rnn.pad_sequence """ def pad_sequence(sequences, batch_first=False, padding_value=0, pad_len=None): r"""Pad a list of variable length Tensors with ``padding_value`` ``pad_sequence`` stacks a list of Tensors along a new dimension, and pads them to equal length. For example,...
7787c83262790af959b6669bfec38c585c2d837d
syurskyi/Python_Topics
/110_concurrency_parallelism/_exercises/templates/Python Parallel Programming Solutions/Section3/using_queue.py
1,087
3.625
4
# ##Using Queue with multiprocessing – Section 3: Process Based Parallelism # # ______ m.. # ______ ra__ # ______ t__ # # c_ producer ?.P.. # ___ - queue # ?.P.. . - # ? ? # # ___ run # ___ i __ ra.. 10 # item _ ra__.r_i.. 0, 256 # q__.p.. ? # print (...
6d982fc168135000ba7e2a83bc547d22a88e876a
luoshao23/Data_Structure_and_Algorithm_in_Python
/ch01_basic/generator_factor.py
284
3.828125
4
def factors(n): k = 1 while k * k < n: if n % k == 0: yield k yield n // k k += 1 if k * k == n: yield k if __name__ == '__main__': n = int(input('Enter an positive integer:')) for k in factors(n): print(k)
87fc75d68eb0f765917595f5e2fd91337f9a141a
MalteMagnussen/PythonProjects
/week3/plotting/classExercise01.py
878
4
4
import matplotlib.pyplot as plt # Class exercise # with the following dataset: student_attendance = {'day1': 33, 'day2': 34, 'day3': 29, 'day4': 31, 'day5': 28, 'day6': 26, 'day7': 30} # create a line graph showing attendance over time. hint: use keys() and values() method of the dictionary. # ...
15035e4458a9ee71c016c92fb9b59011954f5da5
btflyfish/AppiumDemo
/1-Python基础实例/ListComprehensions.py
569
3.625
4
L1=list(range(1,11)) #循环从1到10 L2=[x*x for x in range(1,11)] #还可以加if判断 L3=[x*x for x in range(1,11) if x%2==0] #还可以使用双层循环 L4=[m+n for m in 'ABC' for n in 'XYZ'] L5=['Hello','Python',19,'Apple',None] #isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。 L6=[str.lower(x) for x in L5 if isinstance(x,str)] print('输出List生成式的值:',L1)...
a7b46e1710e0af667fc5932c3b7b84926855b520
aspittles/pi-rfid-py-post
/led-bi-colour.py
792
3.953125
4
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library from time import sleep # Import the sleep function from the time module #GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering GPIO.setup(29, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set in...
403a429c9574c03b09e6edefb0a40db17bf4c427
Vichu7190/Python
/checkDBConn.py
3,470
4.0625
4
""" Created on Sun Oct 31 15:01:50 2020 @author: Viswanathan A @Descirpion : Database Manager Class with Class Methods. This Code lets you connect to the Game Database. """ import sqlite3 class DatabaseManager: ''' This is the Database Manager class''' def __init__(self, db_name): self.db_name = db...
6059094d94263a90a030efdcc463322121bca732
samwar/python-class
/lab10_string_formatting.py
2,092
4.15625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ :mod:`lab10_string_formatting` --- String formatting ==================================================== Find some documentation on string formatting operations using the "%" operator Print 6.2399 using a format specifier that keeps 3 decimal places Print 0x31 u...
08dba60eaf990e7ed49bf88b7c2c74920bfc41b0
nicklambson/pcap
/class/instance_method.py
272
4.125
4
class A: def __init__(self, v=2): self.v = v def set(self, v=1): self.v += v return self.v a = A() b = a b.set() print(a.v) # instances of objects are pointers, just like lists. # When b is set to a, it just points to the same object
ba0c335e585849a0f8e823e08f6425c4634d6e0f
AnjaliCAbraham/S1-A-Anjali-C-Abraham
/programing lab/27-01-2021/17.py
331
3.53125
4
import operator d = {0:1,2:3,4:0,3:4,1:2} print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(1)) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True)) print('Dictionary in descending order by value : '...
43913baf21c6a72737ebe13a73ec90763fd68bcf
VeroAzanza/AgendaFinal
/vistaContacto.py
839
3.65625
4
class vista: def menu(self): m = "MENU" print("1. Añadir contacto") print("2. Buscar contacto") print("3. Editar contacto") print("4. Salir de contactos") return int(input("Ingrese opción: ")) def datos(self): print("Ingrese datos del contacto: nombre, t...
ba16f16476c3adee38600dc75cd9e6700ac742eb
pray-lee/learn_python
/list/切片.py
722
4.21875
4
# 切片 (还是返回列表) players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3])# charles martina michale print(players[1:4])# martina michael florence # 如果没有指定,默认从第一个读取 print(players[:4]) # charles martina michael florence # 如果末尾没有指定,到结尾处结束 print(players[1:]) # martina michael florence eli # 负数 pri...
a271fa3ed759f6a78268e00ba461dd618df9a9d4
kwoo99/CPSC223P
/HW1_studentRecords.py
3,118
4.03125
4
print("Welcome to CPSC 223P's Student Records Program!") numOfRecords = input("Please enter how many records you have: ") columns = ["CWID", "FirstName", "LastName", "Gender", "BirthDate", "ClassID", "Grade"] # Variable (lists and dictionary) delceration classIds = {} # Empty dictionary for class Ids sortedClassIds ...
839d37741fa48e9e5fdb69c05003eafbe35505eb
Jimut123/code-backup
/python/python_backup/wisp_old/archives/test3.py
1,020
3.546875
4
import tkinter as tk def populate(frame): '''Put in some fake data''' for row in range(100): tk.Label(frame, text="%s" % row, width=3, borderwidth="1", relief="solid").grid(row=row, column=0) t="this is the second column for row %s" %row tk.Label(frame, text=t).grid(ro...
a3e682f9b6db699c77bffee42549c879ba568c76
thearod5/kaggle-product-matching
/src/preprocessing/image_pair_creator.py
5,538
3.53125
4
""" The following module is responsible for creating training image pairs. For more information about the methodology and reasoning of why and how this is done see notebook `1. Create Training Data` """ import numpy as np import pandas as pd from text.title_similarity import calculate_title_similarities MIN_SIMILARI...
f3c18cac89bb0c898db9f8d63fb990bb6c77f0e9
quatroka/urionlinejudge
/strings/1168.py
546
3.6875
4
# -*- coding: utf-8 -*- casos = int(input()) for i in range(0, casos): num = str(input()) leds = 0 for j in range(0, len(num)): if num[j] == '1': leds += 2 elif num[j] == '2' or num[j] == '3' or num[j] == '5': leds += 5 elif num[j] == '4': leds +...
e409ee23de203c0d90b9bd8ac96144b35916c835
pharick/python-coursera
/week1/2-pinguins.py
484
3.640625
4
def pinguin(number): lines = number // 10 last_line = number % 10 for _ in range(lines): print(" _~_ " * 10) print(" (o o) " * 10) print(" / V \\ " * 10) print("/( _ )\\ " * 10) print(" ^^ ^^ " * 10) if last_line > 0: print(" _~_ " * last_line) print(" (o o) ...
542a09ca1f0f7497dba82881a3abcd5a0464f1e8
JessicaCarrillo/Taller2
/Ejercicio_estrella_ladosimpares.py
234
3.828125
4
import turtle a = int(input("ingrese un numero impar de puntas para una estrella : ")) t = turtle.Pen() t.reset() for x in range(1,a+1): t.forward(100) an = 180/a ang = 180 - an t.left(ang) turtle.getscreen()._root.mainloop()
52b6edd687cbb01e07a401f80eb3e51029402bbd
Abhisd/Mathscode
/socket.py
613
3.71875
4
import socket print("\n\n DNS lookup") print("1. Url to IP address") print("2. IP address to URL" ) print("3. Get the host name") print("Enter your choice") ch=int(input()) if ch==1: urlname=raw_input("Enter the Url") IPadder=socket.gethostbyname(urlname) print(urlname) print(IPadder) elif ch==2: ipadd=raw_in...
47e0e75e2aaad88d9796b19a320d12c4adb342e6
COW-edu/Study-21-1-codingTest
/dojinyou/code_1week/03_1920.py
834
3.5625
4
# https://www.acmicpc.net/problem/1920 from sys import stdin input = stdin.readline # solution 1 def in_number(sorted_array, number): left_index = 0 right_index = len(sorted_array)-1 while left_index <= right_index : m = (left_index+right_index)//2 if sorted_array[m] == number : return True if sorted_arra...
63a447fcb4783dc9d4f4badc1d2e1be01980e6f5
ayushgoel/Python-blog
/15.py
597
3.5
4
#Using try-except block def dic(words): a = {} for i in words: try: a[i] += 1 except KeyError: ## the famous pythonic way: a[i] = 1 ## Halt and catch fire return a # >>> a='1,3,2,4,5,3,2,1,4,3,2'.split(',') # >>> a # ['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2'] # >>> dic(a) # {'1': 2, ...
13b254203761b6264e79ac317697516f6f93da8f
jriall/leetcode
/medium/all_elements_in_two_binary_trees.py
1,666
4.125
4
# All Elements in Two Binary Search Trees # Given two binary search trees root1 and root2. # Return a list containing all the integers from both trees sorted in ascending order. # Example 1: # Input: root1 = [2,1,4], root2 = [1,0,3] # Output: [0,1,1,2,3,4] # Example 2: # Input: root1 = [0,-10,10], root2 = [5,1,7,0...
1a9be0ae020fc6e1c99d81ca8f4a508f0d07ffc7
anlemora/knowledge_cornucopia
/FacebookPrep/DS Learning/graphs.py
1,941
3.890625
4
class Graph: graph_dict = {} def __init__(self): pass def addNode(self, name, neighbours): if name not in self.graph_dict: self.graph_dict[name] = neighbours def add_edge(self, node, neighbour): if node not in self.graph_dict: self.graph_dict[nod...
811b9d32401de6b259f2cc534aed8f84f84c2eec
carlosberrio/holbertonschool-higher_level_programming-1
/0x07-python-test_driven_development/3-say_my_name.py
681
4.375
4
#!/usr/bin/python3 """Module for say_my_name method""" def say_my_name(first_name, last_name=""): """Prints My name is <first name> <last name> Args: (str) first_name: first string (str) last_name: second string, default str = empty Raises: TypeError: if arguments are not string ty...
3a091df6f4d84d81a16c680c17315b9b89c41e79
paliwalamol/AmolPaliwal_0827CT191009
/ASSIGNMENT/44.py
145
3.65625
4
s = input("enter string:") y="" for i in range(len(s)): if(s[i]==" "):y=y+" " y = y + s.replace(" ","") # y=y + s print(y) #Copyright @Amol Paliwal
dddc636c825ec5751b2afca6954dda4dc48539e4
AV272/Python
/Tasks/_18_Alphabet_Ragnoli.py
1,013
4
4
''' Задача: Нарисовать индийский рисунок рагноли из букв. ''' import string def print_rangoli(size): # your code goes here let = string.ascii_lowercase # записываем все буквы нижнего регистра l = n*4-3 # ширина рисунка L=[] for i in range(1,n+1): s = '-'.join(l...