blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6c7017961787cfad52e209540622285e06ac2722
dashboardijo/TechWrap
/Interviews/Problems/LeetCode/1001-1100/1122_RelativeSortArray.py
1,439
4.1875
4
""" Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. Example 1:...
ee6f33dc2e675c8e56e4a986f5c4672e7ea30ead
kstseng/dsa-ml-tool-note
/DSA/ProblemSolvingWithAlgorithmsAndDataStructures/CODE/BasicDataStructure/stack_postfix.py
4,693
3.703125
4
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def isEmpty(self): return self.items == [] def size(self): ...
c5652c63b77025cbe3633a72da4ca1c635a44485
prasadmule25/Group_B
/setterANDgetter_method.py
3,156
4.0625
4
# class Student: # def __init__(self,name,marks): # self.name=name # self.marks=marks # def display(self): # print("hi",self.name) # print("your markd is",self.marks) # s=Student('swastik',100) # print(s.name) # s.display() class Student: def setname(self,name): # used ...
311125e60526c545d6c73813a75b8420500126df
KeithPallo/independent_coursework
/1 - MOOC - Intro to CS & Programming/Final Exam/f_problem_6.py
4,047
3.9375
4
# Initial class Container is given from the problem. It represents a simple container that can # hold hashable objects of any type class Container(object): """ Holds hashable objects. Objects may occur 0 or more times """ def __init__(self): """ Creates a new container with no objects in it. I.e., any...
ec2bd5cd698aa39dd86716f2d2de207669122484
Jackyzzk/Algorithms
/字符串-07-0647. 回文子串-优化dp.py
1,216
3.5625
4
class Solution(object): """ 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。 输入: "abc" 输出: 3 解释: 三个回文子串: "a", "b", "c". 输入: "aaa" 输出: 6 说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa". 输入的字符串长度不会超过1000。 链接:https://leetcode-cn.com/problems/palindromic-substrings """ def countSubstrings(s...
e38a57a23ea7a4fff2542b18f8b978b02be92550
UncleBob2/MyPythonCookBook
/Intro to Python book/random 3D walk/random walk sin cos.py
1,857
4.625
5
from random import random import math import matplotlib.pyplot as plt # Define the main function as function call begins from here. def main(): path = [] printintro() n = getinput() steps, path = walkRandomly(n) printSummary(steps, n) # print(path) x_val = [x[0] for x in path] y_val = [...
479c5beca1ca747a2f30fa0f23050bff33010412
GHDDI-AILab/Targeting2019-nCoV
/util/csv2md.py
2,246
3.734375
4
# coding:utf-8 """ Convert a csv file to markdown format. Syntax: python csv2md.py -csv <csv file> -md <markdown file> in which <csv file> is the csv file to be converted; <markdown file> is the output path for the generated markdown file, optional; <encoding> is the encoding of the csv file, optional, the default ...
096b88a35550dd914a3c044d62b1ae093d9652d0
gselva28/100_days_of_code
/DAY 17/class_def.py
611
4.0625
4
# class User: # def __init__(self): # print("new user being created..") # # # user_1 = User() # user_1.id = "001" # user_1.username = "Selva" # # print(f"The id is {user_1.id} and the name is {user_1.username}") # # user_2 = User() # user_2.id = "002" # user_2.username = "Ganesh" # # print(f"The id is {user...
ebaf1a3b8d691b0712f450da76b3726ccd345d9b
Jelle12345/Python-3
/oefeningen.py
2,238
3.875
4
contacten = {} def main(): menu() keuze = input("Maak een keuze") while keuze != 's': if keuze == 'm': nieuw_contact() elif keuze == 't': toon_contacten() elif keuze == 'v': verwijder_contact() elif keuze == 'a': contact_aanpas...
7163d57eca4f67dd6e9db8e7eba410c071435127
sonalipatil1729/SSW-540
/guessingNumberGame.py
2,948
4.375
4
"""Name: Sonali Patil This program will generate a random number and will ask user to guess the number in 6 guesses. The program is coded to handle all the below use cases: - if user provides incorrect input(alphabet): program will give message to user that input is not correct and will ask again to input correct va...
03fc03590cbafe6aae800756944009acb7128623
TheOneAndOnlyAbe/astar
/helperFiles/nodeFunctions.py
6,775
4.0625
4
import math # The Node class is in here because these functions require the node class and so do the other classes. # I would remake this so that the Map class hold all of these functions, but that would take more time than I have. # If I were to leave this class in the classes.py file, I would get an error because th...
0b4d1ebfcffae7e0c0f7003d552472ec458c669d
emamula/SoftDesSp15
/toolbox/word_frequency_analysis/frequency.py
1,747
4.5625
5
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string def get_word_list(file_name): """ Reads the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. A...
49112217b892b9edbffb49dfc8f2450dc0ee4c3e
iansedano/codingame_solutions
/Skynet_revolution/dijkstra.py
1,792
3.8125
4
nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] links = [[2, 6], [9, 7], [0, 7], [9, 8], [8, 2], [7, 1], [9, 2], [3, 1], [2, 5], [0, 8], [4, 1], [9, 1], [0, 9], [2, 1]] def dijkstra(n1, n2, nodes, links): '''Get shortest distance between two nodes Assumes unweighted linkes (i.e. each link's value is 1) ''' no...
b9bff2a8e344dabb03de95bfd95e9f2ac59f1cc5
WillLuong97/MultiThreading-Module
/openWeatherAPI.py
4,137
3.75
4
''' OpenWeatherMap API, https://openweathermap.org/api by city name --> api.openweathermap.org/data/2.5/weather?q={city name},{country code} JSON parameters https://openweathermap.org/current#current_JSON weather.description Weather condition within the group main.temp Temperature. Unit Default: Kelvin, Metric...
99a6a8f58c3b31a201aaef43cf7b7d74598fcfa5
unouno1224/workspace
/learning/src/excercise/train4.py
288
3.640625
4
def func(li): li[0]= 'i am your father!' #1 if __name__=="__main__": li = [1,2,3,4] func(li) print(li) def func1(li): li= ['i am your father!', 2,3,4] print(li) if __name__=="__main__": li = [1,2,3,4] func1(li) li.sort(reverse=True) print(li)
3f97901da34c0283c0fb6f0f41c2fa9dda264345
yonggqiii/kattis
/cs1010e/2048/2048_template.py
671
4.03125
4
def solve_2048(puzzle: [[int]], move: int) -> [[int]]: ''' https://open.kattis.com/problems/2048 Define the solve_2048 function which solves the problem given the puzzle as a list of lists containing ints, and the move. Your function should return the new puzzle after the move. The input puzzle...
454274a954a6173f98d91b42244d873550204af2
salmonteASC/AllStarCode
/ListLab.py
659
3.546875
4
from random import * def randomMovies(): lst1 = ["The Adventure of ","The tales of ","The Odyssey of ","The life of ","The hunting of ","The stories of ","The trials of ","The return of ", ] lst2 = ["David","Sam","Shorlock Homes","Hulk","","Charlie","Joshua","Christina","Shinjini"] lst3 = [" the killer"," t...
40cafc20345aa969a088b103961af6b8b8cd0d13
RahulLooserR/python-pygames
/Archery/Arrow.py
1,799
3.703125
4
from Globals import * class Arrow: # 1/2 length of the arrow LENGTH = 50 # constructor with parameters, starting point(anchorPoint), angle of projectile and velocity def __init__(self, anchorPoint, angle, velocity): self.x, self.y = anchorPoint self.xoffset, self.yoffset = anchorPoint # angle fixed for th...
16fdf9cba56f918df91b08d729eabda5eb248ffc
CallmeChenChen/leetCodePractice
/1_twoSum.py
474
3.5625
4
''' 1. two sum ''' class Solution(object): def twoSum(self, nums, target): tmp = {} for i in nums: if target - i in tmp: first_index = tmp.get(target - i) second_index = len(tmp) return first_index, second_index tmp[i] = len...
1aecee7cc5007bce58d846d4325ea7108af3cde3
vitorvicente/LearningPython
/Basics/DataTypes.py
1,528
3.640625
4
# Data Types print("Data Types:") x = "Hello World" print(x, type(x)) x = 20 print(x, type(x)) x = 20.5 print(x, type(x)) x = 1j print(x, type(x)) x = ["apple", "banana", "cherry"] print(x, type(x)) x = ("apple", "banana", "cherry") print(x, type(x)) x = range(6) print(x, type(x)) x = {"name" : "John", "age" :...
880b9c506880351a87bc24dc4a62a10f0d9cb5a9
elainedo/python_practice
/Array/NextPermuation.py
598
3.515625
4
def next_permutation(nums): # find the non increasing part at the end last_index = len(nums)-2 while (last_index >= 0): if nums[last_index] < nums[last_index+1]: break last_index -= 1 if last_index == -1: nums[:] = reversed(nums) return nums for i in rev...
75b820e4dd9e58513765cbebec227e8d4b059f31
TrickFF/helloworld
/random_ex.py
550
3.828125
4
from random import randint, choice, sample, shuffle # 1 загадать случайное число от 0 до 100 print(randint(0, 100)) # 2 выбрать победителя лотереи из списка players players = ['Max', 'Leo', 'Kate', 'Ron', 'Bill'] print(choice(players)) # 3 Выбрать 3х победителей лотереи print(sample(players, 3)) # 4 перемешать карты ...
46900163ce8a1f4f482adf1865a3ef2115cb5757
futeen/playboy
/usual_code/pandas_sort.py
1,605
3.78125
4
import pandas as pd import numpy as np def pandas_sort(): df = pd.DataFrame({'col1': ['A', 'A', 'B', np.nan, 'D', 'C'], 'col2': [2, 1, 9, 8, 7, 7], 'col3': [0, 1, 9, 4, 2, 8] }) # 依据第一列排序,并将该列空值放在首位 one = df.sort_values(by=['col1'], na_...
7442fabe19959a3c9f056c4e5d6da9f5b8c1b5a9
agnewfarms/adventofcode
/Day2/Day2.py
4,574
3.59375
4
<<<<<<< HEAD from operator import itemgetter def read_input(): rules_with_data = [] with open('Inputday2.txt') as reader: lines = reader.readlines() for line in lines: elements = line.split(' ') iterations_of_char = elements[0] char = elements[1][0] ...
3d984868de8bfeeccb21535df0723d389683da15
Reginald-Lee/biji-ben
/uoft/CSC148H1F Intro to Comp Sci/@week1_object_oriented/@@Lab1/console.py
1,386
4.15625
4
# Lab 1 - Python (Re-)Introduction # # CSC148 Fall 2014, University of Toronto # Instructor: David Liu # --------------------------------------------- """Lab 1: interactive console. This module contains a script to run an interactive console, in which the user types in commands and sees results. Your task is ...
2af62fb3d3e8a39e5b4f248ff907632b5ab9036b
teslastine08/py_nielit
/programs/tot_avg.py
195
3.8125
4
a=int(input("enter no-1")) b=int(input("enter no-2")) c=int(input("enter no-3")) d=int(input("enter no-4")) e=int(input("enter no-5")) x=(a+b+c+d+e) y=(x/5) print("total:",x) print("average:",y)
b255fdf34e22a4165490cdca3b6a1c6e64f12f1d
Jeremy277/exercise
/pytnon-month01/month01-shibw-notes/day08-shibw/demo02-函数实参传递方式.py
1,069
3.9375
4
''' 函数传参 实参传递方式 ''' def fun01(a,b,c):#形参 a b c print(a) print(b) print(c) #位置实参 实参是根据位置与形参对应的 #如果实参位置发生改变 会影响函数结果 # fun01(10,20,30) # fun01(30,10,20) #序列实参 用*将序列中的元素拆开然后与形参依次对应 #序列 字符串 列表 元组 list01 = [10,20,30] fun01(*list01) # str01 = 'abcd' # fun01(*str01)#报错 #关键字实参 #实参的值与形参的名称对应 # fun01(a=10,b=20,c=...
2d7a66e54b79c527d2203b57a0e5b1b9ef0a67da
apollokit/snippets
/python/algs/dfs.py
1,178
3.859375
4
from Graph import Graph from Queue import MyQueue from Stack import MyStack def get_children_vertices(graph, vertex): children = [] edge_list = graph.array[vertex] if not edge_list.is_empty(): node = edge_list.head_node while node is not None: children.append(node.data) ...
5cfa6cf0ac7fb2fa986a7b0416ba7420fe2aa76c
celsopa/CeV-Python
/mundo02/ex037.py
704
4.1875
4
# Exercício Python 037: Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. n = int(input("Digite um número inteiro qualquer: ")) print(f"""--- MENO DE CONVERSÃO --- [1] Binário [2] OCTAL [3] ...
ebe53a51ca70f7bb410a1f79089c6edfd282e581
SaiSharanyaY/HackerRank
/Finding the percentage.py
988
4.15625
4
" " " The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal. Output Format Print one line: The average of the marks obtained by the particular student co...
fd64560e5a34c634cb2e49dd6089271c44a2fb56
krisnadiputra/100knock
/ch1/2.py
180
3.796875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- a = u"パトカー" b = u"タクシー" for i in range(len(a)+len(b)): if i%2: print b[i/2] else : print a[i/2]
c478079708e8d4b50e046e7f1a2ce0776374bbc6
PariaSabet/PythonAlgorithms
/Sum.py
524
4
4
# this program adds the digits of an integer repeatedly # until the sum is a single digit number = int(input("please enter a number")) def sumOfDigits(x): summary = 0 while x > 0: add = x%10 summary = add + summary x = int(x/10) if summary > 9: final = summary sum...
6812e1de0e1f7e36851db5ac4c1bc2ec5642778d
wenjie-lu/AOC2020
/day3.py
605
3.640625
4
from pathlib import Path def read_file_by_line(input_path): with open(input_path, 'r') as f: string = f.read().splitlines() return string def slide(map, dy, dx): x = y = 0 trees = 0 while x < len(map) - 1: y = (y + dy) % len(map[x]) x = x + dx if map...
a3373551419399b982f41e3bb8c36bb282eb6b93
Erihon78/python_start
/children_py/arrays.py
196
4
4
# Generates a list of numbers # print(list(range(10, 20))) for x in range(0, 5): print('You number is %s' % (x + 1)) x = 45 y = 80 while x < 50 and y < 100: x = x + 1 y = y + 1 print(x, y)
61d5ca05a684ce20e43dfb935701f9cb1498e2c6
kitoriaaa/AtCoder
/Problems/abc065_b.py
231
3.75
4
N = int(input()) a_li = [int(input()) for _ in range(N)] now_i = 1 step = 0 for i in range(1*10**5+10): step += 1 button = a_li[now_i-1] now_i = button if button == 2: print(step) exit() print(-1)
6a1c7725575f904ddbf73315fa6211946528529e
Swati213/pythonbasic
/stu.py
1,683
4.03125
4
class student: """class variable""" roll=23 age=23 def __init__(self): """global variable""" self.tot_marks=0 self.percent=0 """instance variable""" self.name="Ajay gupta" self.d_o_b="7/8/1996" self.age=student.age self.parent_n...
e6642965bb3b9eedb196459fdc0b3e1e675b679a
le-n-qui/sentimental-analysis
/rmp_scraper.py
11,747
3.546875
4
import bs4 import requests import json import csv import selenium.webdriver as webdriver # ---------------------------------------------------------- # Turn webpage into a parseable BeautifulSoup object # which represents the document as a nested data structure # -------------------------------------------------------...
39345774aa9079a34313b4b34e38d1099b8e515c
cnovacyu/python_practice
/automate_the_boring_stuff/Chapter9_FillGaps.py
991
3.578125
4
#! python3 # Find all files with a given prefix such as spam001.txt, spam002.txt, etc # in a single folder and locate any gaps in the numbering. Rename all later # files to close the numbering gap. import os, argparse, shutil # create args for selecting folder to check numbering of files parser = argparse.ArgumentPar...
32448cfb69a4251b203344f94fc162d13a173d86
hyun-soo-park/Algorithm
/18장/65.py
642
3.84375
4
#https://leetcode.com/problems/binary-search/ class Solution: def search(self, nums: List[int], target: int) -> int: def binary_search(bin_list, start, end, target): if start > end: return -1 mid = (start + end) // 2 if bin_list[mid] == target: ...
ecebef5015ddfebbc897d7411b42d7658d11ea99
Dadajon/100-days-of-code
/competitive-programming/hackerrank/algorithms/implementation/039-find-digits/find-digits.py
603
4.28125
4
def find_digits(n): """ The function should return an integer representing the number of digits of d that are divisors of d. :param n: an integer to analyze :return: for every test case, count the number of digits in n that are divisors of n """ cnt = 0 tmp = n while tmp > 0: dig...
3e8f777a01f2a65cb19972bd24a79168710489f8
Charlie-Toro/automate-Python
/isPhone.py
749
4.21875
4
# isPhone # Caleb Bell # Provided a string of numbers, determines if the format is correct for phone number def isPhoneNumber(text): """Checks validity of phone number provided""" if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False ...
3fbb6548abdd5e5f2b3dd7d5bb48af84a40d3a8a
amiraHag/hackerrank-30-days-of-code
/day7.py
301
3.75
4
#!/bin/python3 import math import os import random import re import sys def printArray(array): for i in range (len(array)): print(array[len(array) - i -1], end =" ") if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) printArray(arr)
7afeb35493bc4d86c898eb568d2a35c8bd8d9634
BenjiFuse/aoc-2020
/Day2/Part2.py
509
3.796875
4
import re from itertools import accumulate pattern = r'(\d+)-(\d+) (.): (.+)' regex = re.compile(pattern) def is_valid(s): m = regex.fullmatch(s) min = int(m.group(1)) max = int(m.group(2)) char = m.group(3) password = m.group(4) return (password[min-1] == char) ^ (password[max-1] == char) wi...
a01c14496ada76b54b9dfd68daf7ca1d0b2dcc0d
oraocp/pystu
/primitive/base/statical.py
2,679
3.953125
4
""" 文档目的:演示Python中的统计模块的用法 创建日期:2017/11/16 演示内容包括: 1. 平均数 2. 中位数 3. 高低中位数 4. 总体方差 = 总体标准差^2 5. 样本方差 = 样本标准差^2 """ import math from fractions import Fraction as F from statistics import mean, median, median_low, median_high, pvariance, pstdev # ======定义测试数据======== # data = [i for i in range(1, 5)] data2 = [i for i ...
60fbdacb1cc6560ff23567360f0dcf86cfecca80
mikerojaswa/PythonSnippets
/Graphs/Graph_DFS_Iterative.py
375
3.796875
4
graph = {'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']} def dfs(graph, start): visited = set() stack = [start] while stack: s = stack.pop() if s not in visited: visited.add(s) for node in graph[s]: if node not in visited: ...
7c6a1ef4d4e2b1d5ba69931dede8cedb762e1454
hofernandes/python3-mundo-1
/ex004.py
530
4.09375
4
# Dissecando uma Variável n=input('Escreva algo: ') print ('O tipo primitivo é: {}'.format(type(n))) print('Esta string é número? : {}'.format(n.isnumeric())) print('Esta string são caracteres? :{}'.format(n.isalpha())) print('Esta string são números ou caracteres? {}'.format(n.isalnum())) print('Esra string são maicus...
ce05b7a544d6d3ea6836f8c249fa6497941da91b
Darpan28/PythonWallet
/untitled1/venv/HomeView.py
10,038
3.53125
4
import mysql.connector from tkinter import * import datetime as dt phone = "" transferPhone = "" def dateTime(): global today today = dt.datetime.today() class customer: def __init__(self,name,phone,balance): self.name = name self.phone = phone self.balance = balance class dbHelp...
05654cc27295a6bbfbecaaf428be6da29f10127d
kimbumsoo0820/codeup
/20200714_codeup_3/codeup3_16junsoo.py
79
3.578125
4
a = input() b = int(a,16) for i in range(1,16): print("%s*%X=%X"%(a,i,b*i))
73d55a37f22bea206ed607cdc3ecc6e896634860
roden011/sample-code-portfolio
/imgProc.py
4,835
3.65625
4
from ezgraphics import * from imgProcTools import * ''' This program requires that the image files be formatted as bitmap (or raster) images. Each pixel has a distinct location in a 2 dimensional matrix (x,y plot or grid) as well as a r(red), g(green),b(blue) color value of 0-255. https://en.wikipedia.org/wiki/...
a96a42887616c1883c08bd5436a40824bc99eb4a
athletejuan/notebook
/Python Daily/calc.py
249
3.5625
4
# Calc.py def add(a,b): return a+b def substract(a,b): return a-b def multiply(a,b): return a*b def divide(a,b): return a/b #print (add(4,2)) #print (substract(4,2)) #print (multiply(4,2)) #print (divide(4,2))
77a286927296c9821afdf47cd7eda8291a904ad4
ssthurai/fullerene-predictor
/fullerene_curvature/sphere.py
1,163
3.71875
4
'''@package sphere helper routines related to spheres. ''' import numpy import numpy.linalg def compute_sphere(point_a, point_b, point_c, point_d): ''' compute_sphere Given four points, this computes the radius on a sphere containing them. point_a: point_b: point_c: point_d: return: r...
68fb900a4a94a3a04acb48d1b1146011416339a0
TestowanieAutomatyczneUG/laboratorium-11-maciej-witkowski
/src/zad3/friendships.py
1,055
3.921875
4
class FriendShips: def __init__(self): self.friends = {} def addFriend(self, person, friend): if not (isinstance(person, str) and isinstance(friend, str)): raise TypeError("Inputs must be of string type!") if not person or not friend or person.isspace() or friend.isspace():...
46fd6508edb30bc2e2d7818c8b73f9e087720d88
mizanurrahman13/PythonAbc
/FreeCodeCamp.org/TakingInputFromUser.py
475
4.09375
4
name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + " ! Your are " + age + " Years old now.") num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = num1 + num2 print(result) # We need int casting number num1 and num2 result = int(num1) + int(num2) print(...
de24c1bc42c6224300cb190615d304126f75f26a
AJohnston29/Instrumental-Project
/conversion.py
4,931
3.625
4
#!/usr/bin/python #Script created by Anthony Johnston import os import sys import argparse from scipy import misc import numpy as np from PIL import Image #RGB to Grayscale Conversion Function def GrayScale(filename): #Defines the weighted average formula for luminosity def LuminosityMethod(pixel): return 0.21*(p...
1c6339fadc505d07a9245714a8b94ef8fa043afb
MastersAcademy/Programming-Basics
/homeworks/olena.kucheruk_elena6kucheruk/Homework-1/homework1.py
392
3.875
4
print ("Please write about your favorite books \n") name = input("What is your name?\n ") age = int(input("What is your age?\n ")) book = input("What is your favorite book?\n ") #results result = ("Your name is %s, You are %i years old, your favorite book is %s. Thank you." % ( name, age, book )) print (...
d64585d2d0eed2004db9d55445afcc7ffb64df5b
zuxinlin/leetcode
/leetcode/editor/cn/[98]验证二叉搜索树-validate-binary-search-tree.py
2,046
3.703125
4
#! /usr/bin/env python # coding: utf-8 # 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 # # 假设一个二叉搜索树具有如下特征: # # # 节点的左子树只包含小于当前节点的数。 # 节点的右子树只包含大于当前节点的数。 # 所有左子树和右子树自身必须也是二叉搜索树。 # # # 示例 1: # # 输入: # 2 # / \ # 1 3 # 输出: true # # # 示例 2: # # 输入: # 5 # / \ # 1 4 #   / \ #   3 6 # 输出: ...
dd0079a1c05d9e5e33d8bc26f227f2daf7bc87f3
LudwinGarcia/Examples_Python
/ex36.py
8,702
3.859375
4
# -*- coding: utf-8 -*- from sys import exit def matematica(): print"\n" print "*" * 76 print "\n++++++ HAS LLEGADO A LA ULTIMA PRUEBA!!!!++++++" print "\nEn una jaula hay conejos y palomas, pueden contarse 35 cabezas y 94 patas." print "Cuntos animales hay de cada clase? " print "\t 1) 14 conejos y 21 palomas" ...
4d736eabf7068a532e2aa40472818c1225f605bf
bamonson/brm677
/02_problem4.py
1,034
4.75
5
#Code to determine if the Year is a leap year or not. Year=2020 #Year is the variable. The value is 2020. if Year%4==0: #This determines if the Year value is divisible by 4. If it is, it goes to the next line's prompt. If it is not, it goes down to the "else" inline with it below that will print it isn't a leap yea...
bd6775968ee8454fc9b0b0a86bb86acbe92e98b8
DanyZy/Python-Labs
/Practice04/VigenereCipher.py
3,413
3.5625
4
import unittest def add_spaces(text_w_space, text_wo_space, alphabet='abcdefghijklmnopqrstuvwxyz'): for i, el in enumerate(text_w_space): if not alphabet.__contains__(el): text_wo_space.insert(i, el) return text_wo_space def del_surplus_symbols_in_text(text, alphabet='abcdefghi...
2a4becc098cd2d6a072cc3e0b12f6eab0c597973
dlgweeduh/movie_trailer_website
/media.py
719
3.546875
4
# allows use of Web Browser functionality import webbrowser class Movie(): """" This class provides a way to store movie-related info. """ VALID_RATINGS = ["G", "PG", "PG-13", "R"] def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): """ Initializes Movie ob...
f00dbf3879e0a237bed44271ad460489294938d3
varnitsaini/python-dynamic-programming
/KnapsackProblem.py
1,388
3.84375
4
""" Implementing 0-1 knapsack problem Two ways of representation has been depicted here """ """ Naive recursive approach Time complexity : 2^n This approach has exponential time complexity as each subproblem has to be evaluated twice. Although time complexity can be reduced if we use memoisation for evaluate each recu...
fc16cc20845cfa49345594c077dc1886bbc2d04b
YusefQuinlan/PythonTutorial
/Basics/1.12.1_Basics_Sets.py
1,831
4.46875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 7 15:40:46 2019 @author: Yusef Quinlan """ Set1 = {1,7,"Hello"} #Set creation i.e. put items in '{}' those squiggly brackets print(Set1) Set1.add(8) #Adding items to the set, notice if you use the command several times the number # 8 will still only appear in the s...
edf16a7a8783d8b1175f4d48b43625ba8ae1096a
lishuchen/Algorithms
/leecode/337_House_Robber_III.py
689
3.609375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ if not root: ...
5ec4ef9ba1c4077e26e41eb6765f2ebe26eec7ee
uzzal5954/Weather_Application
/weather_api.py
1,201
3.5625
4
# Weather API import requests def format_response(weather_data): try: city_name = weather_data['name'] country_name= weather_data['sys']['country'] # *** condition = weather_data['weather'][0]['description'] temperature = weather_data["main"]["temp"] icon_na...
c4decdb01fe6a5e1fffa5f53056a5fdf9355a2ae
jmt-transloc/python_learning
/magic_methods/person_example.py
302
3.78125
4
class Person: def __init__(self, title, forename, surname): self.title = title self.forename = forename self.surname = surname def __str__(self): return ' '.join([self.title, self.forename, self.surname]) person = Person('Mr', 'John', 'Smith') print(person)
83f48889c76b8ce2dbb6de080aafc066b9f6826e
datadiskpfv/basics1
/functions1.py
869
4.03125
4
def python_food(): width = 80 text = "spam and eggs" left_margin = (width - len(text)) // 2 print(" " * left_margin, text) def center_text(width, text): text = str(text) # make sure parameter is a str left_margin = (width - len(text)) // 2 print(" " * left_margin, text) # there ar...
0333a1c91c7846bbb94dd626cbeee17fad839e86
aldrinpscastro/PythonExercicios
/EstruturaDeRepeticao/ex021.py
263
4
4
numero = int(input('Digite um número: ')) eprimo = True for i in range(numero - 1, 1, -1): if numero % i == 0: eprimo = False break if eprimo: print('O digitado é primo.') else: print('O número digitado não é primo.')
ad874c9fcdfa6e474950def668961bb93677534f
IuriiD/PythonBasics
/practicepython.org/old/23.py
1,402
3.640625
4
# let's create a dictionary {'Name': count} '''namescount = {} with open('nameslist.txt','r') as open_file: line = open_file.readline() while line: line = line.strip() # check if this key is in dictionary if line in namescount: # if it is, corresp. value+=1 namescount[line]+=1 # if it doesn't exist, add...
c0ea96b2eb61f8d9121562e9e7c6ecdff73aff42
CheffOfGames/Diemen-Academy
/blankScreen.py
1,689
3.546875
4
from tkinter import * top_bar_color = "Red" logo_background = "White" button_background = "Blue" class Screen: def __init__(self, root:Tk, frame:Frame, screens:dict, database): self.root = root self.frame = frame self.screens = screens self.frame_objects = [] se...
df9a44571d3f08a39d51d87afce49a2f50ce4598
yi-guo/coding-interview
/leetcode/python/015-threeSum.py
1,382
3.59375
4
#!/usr/bin/python # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets # in the array which gives the sum of zero. # Note: # 1. Elements in a triplet (a, b, c) must be in non-descending order, i.e., a <= b <= c. # 2. The solution set must not contain ...
6314bf28225deb4912d84a760b1967daa07831dd
Gangamagadum98/Python-Programs
/PythonClass/reverseStr.py
1,431
4.0625
4
#reverse string s1="hi hello" def reverse(s): s2 = "" # empty string since string is immutable for i in s: print(i) # we are iterating over characters in a string s2=i+s2 return s2 # palindrome string # if("NAN" == reverse("NAN")): # print("Is a palindrome") result = reverse(...
ef2e1caf2a26aeb4f3bb9f455e5f22447fd5eca9
kburts/python-HearthStoneUtils
/HSCardnames.py
509
3.828125
4
import csv import json ''' Program to search through a .csv file and retrieve all of the contents of one row, and save them to a json file. can be modified to get other information about the cards. File format: ["1","2","3"..."mystuff"]. ''' cardnames = [] with open('Hearthstone_cards.csv', 'r') as csvcards: ...
9ea6102dd25de4c840d338cd886a3cce2e3e34de
howobe/scan-scraping
/utils.py
185
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 29 22:48:21 2020 @author: bj """ def xor(lst): if not lst: return return lst[0] != xor(lst[1:])
694ac2f1609017d8443a5d0e78031820712101b3
N1kken/PythonProjects
/PythonPodstawy/delta.py
603
3.71875
4
import time import math print("LICZ DELTE") time.sleep(1) print("Witaj, podaj wspolczynniki rownania kwadratowego: ax^2+bx+c=0!") print("Podaj a:") a=int(input()) print("Podaj b:") b=int(input()) print("Podaj c:") c=int(input()) delta=math.pow(b,2)-4*a*c if delta == 0: m1 = -b/(2*a) print("F...
f0228b236d6bd3d15959552ca64bf9b0e603cd81
makhsudov/csv-reader-python
/Csv.py
603
3.984375
4
import csv array = [] path = '' i = 0 with open(path, encoding='utf-8') as r_file: # Separator character "," csvReader = csv.DictReader(r_file, delimiter = ",") # Reading data from a CSV file for row in csvReader: if i == 0: # Displays the first line that contains the he...
20be62521318fc7b29236872cecbc49fc87ee0a0
hellion86/pythontutor-lessons
/8. Функции и рекурсия/Числа Фибоначчи.py
682
4.0625
4
''' Условие Напишите функцию fib(n), которая по данному целому неотрицательному n возвращает n-e число Фибоначчи. В этой задаче нельзя использовать циклы — используйте рекурсию. ''' # Мое решение n = int(input()) def fibo(n): if n == 0: return 0 if n == 1: return 1 if n > 1: return...
ec0a6abb1351fa144f079218821e14ed60f72a50
christiandleonr/Machine-Learning-A-Z-Course
/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py
1,904
4.40625
4
# Simple Linear Regression # Importing the libraries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # Importing the data-set data = pd.read_csv('Salary_Data.csv') """We take all columns except the last one, th...
c81edc2c96c521858f2335cc471ef642c5b17cf1
kaztoyoshi/algorithm
/divisor/divisor.py
795
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math N = 36 # 整数 N print("1.") out = "{" for i in range(1, N+1): if N % i == 0: out += (str(i)) + "," out += "}" print(out) print("2.") arr = [] max = math.ceil(math.sqrt(N+1)) + 1 for i in range(1, max): if N % i == 0: arr.append(i) ...
b9f502ee35630d30fe2a9287c2ee45f3ee4d7330
JackelyneTriana/AprendaPython
/Tablas.py
508
3.78125
4
#Tablas.py #Autor: Mirna Jackelyne Triana Sanchez #Fecha: 18/09/2019 for j in range(1,11): #para cada elemento del rango 1 al 11 imprimir lo siguiente: encabezado = "Tabla del {}" print(encabezado.format(j)) for i in range(1,11): #para cada elemento del rango 1 al 11 imprimir lo siguiente: ...
6383f374b80644b18be38bd9578800a344b90f5e
acharyasant7/Bioinformatics-Algorithms-Coding-Solutions
/Chapter -2/2A_MotifEnumeration.py
1,473
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 10 09:02:17 2020 @author: sandesh """ def Neighbors(Pattern, d): assert(d <= len(Pattern)) if d == 0: return [Pattern] SuffixNeigh = Neighbors(Pattern[1:], d-1) Neighborhood = [] Neighborhood.append(Pat...
95d86665b106facfc38e4e57c7e4f04159d0392d
falabretti/uri-online-judge
/python3/beginner/1164.py
324
3.625
4
testes = int(input()) for caso in range(testes): entrada = int(input()) soma = 0 for index in range(1, entrada): if(entrada % index == 0): soma += index if(soma == entrada): print("{} eh perfeito".format(entrada)) else: print("{} nao eh perfeito".format(entrad...
f42a0060b4a2635a0fa89f94493aa3cbc30b1f8d
ErickMwazonga/sifu
/oop/playlist.py
1,397
3.703125
4
class Song: def __init__(self, title, artist, album, track_number): self.title = title self.artist = artist self.album = album self.track_number = track_number artist.add_song(self) class Album: def __init__(self, title, artist, year): self.title = title ...
229b171160322badbe876e007dfad43cc25e252c
Ressull250/code_practice
/part4/110.py
1,133
3.75
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if abs(self.maxDepth(root...
dcae6505d8b0af3069e022944bc804756de10b90
Puneetdots/Python
/snake_water_gun.py
548
3.765625
4
import random obj = ["Snake","Water","Gun"] input1 = print(input("Please choose the charater S for Snake,W for Water,G for Gun\n")) ch = random.choice(obj) #print(ch) if ch=="Snake" and input1 =="W": print("Snake Win") elif ch=="Snake" and input1 =="G": print("Gun Win") elif ch=="Water" and input1 =="S": pr...
631a93b8edc4edd2b65b8d5b5e02f5436c745127
lilaboc/leetcode
/5.py
438
3.5625
4
# https://leetcode.com/problems/longest-palindromic-substring/ class Solution: def longestPalindrome(self, s: str) -> str: window = len(s) while True: for i in range(len(s) - window + 1): st = s[i : i + window] if st[:] == st[::-1]: ret...
9aee8cee3ad47a9da7e76f83551a2d5430088ee4
Uncastellum/Hashcode
/2022/main2.py
818
3.515625
4
def main(): print(f"Reading from {input}") print(f"Writing to {output_file}") # Sort projects radixSort(projects, lambda x: x.best_before) print([x.best_before for x in projects]) indiceWhile = 0 activeProjects = [] output = [] while(len(projects) != 0): for project in acti...
e36aa5959ad66a03ad6d910e09ae49fa00c196c2
Xillow/CL-Stanley-Parable
/insane.py
7,069
3.90625
4
import door import time def insane(): print("(You enter a room with a car parked. A door shuts behind you.)") print("But Stanley just couldn't do it.") time.sleep(1) print("He considered the possibility of facing his boss, admitting he had left his post during work hours, he might be fired for that. An...
06936194f459028b65d4dee13db6c3787a9ff989
DaVinci42/LeetCode
/110.BalancedBinaryTree.py
1,085
3.75
4
from typing import Dict # 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 class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return True...
df70575c0a6beeed16c299b9301ce2bd17550ba1
H-Shen/Collection_of_my_coding_practice
/Hackerrank/Mathematics/Eulers_Criterion.py3
305
3.65625
4
import fractions for i in range(int(input())): A, M = list(map(int,input().split())) if A ** 0.5 % 1 == 0: print('YES') elif (M > 2 and fractions.gcd(A, M) == 1 and pow(A, (M - 1) // 2, M)== 1): print('YES') elif M == 2: print('YES') else: print('NO')
b875f497344c9f951b5c862aa92b01f0dfaffef1
KimbaWLion/RedditBotPractice
/RedditBotWait.py
425
3.75
4
#!/usr/bin/python import time import sys def wait_2_seconds(): wait_seconds(2) def wait_2_seconds_no_display(): wait_seconds(2,False) def wait_seconds(waittime, display=True): if display: print 'Wait {0} seconds because you cannot make a call more than once every 2 seconds'.format(waittime) t...
88708a7801b8c4b771ea2711463d43e8632da154
Reynouts/AoC19
/AoC19/day20.py
5,548
3.78125
4
import copy import os import aocutils as util from collections import defaultdict WIDTH = 0 HEIGHT = 0 def draw(tiles): result = "" for j in range(HEIGHT): for i in range(WIDTH): if (i, j) in tiles: result += tiles[i, j] else: result += " " ...
bbd0344172d7543573c568b9c832bbc6f8b4e8c7
kimsungho97/Algorithms
/baekjoon/두 동전.py
3,479
3.6875
4
import copy row, col= list(map(int,input().split())) origin_board=[] for i in range(row): line=list(input()) origin_board.append(line) token={'coin': 'o', 'empty':'.', 'wall':'#'} moving=['up','down','left','right'] count=11 def coin_move(before,direction): global row, col, token drop_count=0 ...
bb62834bfa72d4f6daa038655c47b04f97b4da52
vronikp/PrestamosIngSw
/prestamo.py
1,010
3.625
4
class Prestamo(): def valor_total(self,prestamo,tiempo): if( prestamo <5000 && tiempo <=3): comision=(prestamo *2)/100 capital_total=float(prestamo+comision) interes=float(((capital_total*1)/100)*tiempo) return float(capital_total+interes) ...
4d08b61f6b54ad55a723599450e7f0beab8cf466
evalDev/ud-fullstack
/programing-fondations/02-use-functions/secret-message.py
563
4.03125
4
import os def rename_files(): files_dir = "/home/mute/repos/udacity/programing-fondations//02-use-functions/prank" saved_path = os.getcwd() os.chdir(files_dir) #1. Get the name of each file in folder file_list = os.listdir(files_dir) for file_name in file_list: #2. remove numbers from e...
3c7b172b44d143a43e7da5915fb0880adad5db59
mateuskienzle/training-python
/ex-078-maior-e-menor-valores-na-lista.py
544
3.78125
4
valores = [] for c in range (0, 5): valores.append(int(input(f'Digite um valor para a Posição {c}: '))) valor_max = max(valores) valor_min = min(valores) print('=-' *30) print(f'Você digitou os valores {valores}') print(f'O maior valor digitado foi {valor_max} nas posições ', end='') for i, v in enumerate(valores):...
80595a0b47554fe2c8cdab1ccd9d280033b43c80
Evelyn9276/Practice
/main.py
455
3.890625
4
import turtle as trtl # set turtle pencolor to teal trtl.pencolor("teal") trtl.speed(10) # draw six hexagons for i in range(6): trtl.circle(50, 360, 6) trtl.penup() trtl.forward(10) trtl.pendown() # move turtle to (0, -100) trtl.penup() trtl.goto(0, -100) trtl.pendown() # make turtle pencolor green trtl.pe...
ba46c6c939aeb6e5d5e5c660bbd0735a59d9c634
wahyuagungs/NotFreeCell
/core/foundation.py
2,195
3.953125
4
from core.stack import Stack from core.color import Color class Foundation(Stack): """ This class is sometimes called as winner deck, because it will hold stack of cards that will be moved from either Tableau or Cells. All cards must be placed according to its suit and number sequentially. The number...
9a6ab5479ba578aea057ea4b357234f410522e14
kalmuzaki/Card-Classes
/Card.py
1,090
3.78125
4
from enum import Enum class Card: def __init__(self, suit, value): self.suit = suit self.value = value def __str__(self): return "{0} of {1}".format(self.value.name,self.suit.name) def __gt__(self, other): if self.suit.value >= other.suit.value: if ...
e099799375308a2b43a1d482b75759fd7a9f79fa
anoru/Intro-to-machine-learning
/naive_bayes/nb_author_id.py
2,096
3.828125
4
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from em...
48cef7ec37fa45ed3a1c5d7bafe63d43f7baa0f6
Roykssop/pytraining
/11-Ejercicios/ejercicio1.py
832
4.03125
4
# Fn recorre lista def recorreListaSimple( nombre, lista ): print(f"============= {nombre} ===========") for item in lista: print(item) print("===============================\n") def devuelveElemento( indice, lista ): if( indice < len(lista) ): print(lista.index(indice)) else: print("No existe el...