blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1dae77273c6bce5a786e08ff7f79a8f8dea57771 | JiangFengJason/LeetCodePractice | /SolutionsPY/JumpGame.py | 531 | 3.546875 | 4 | class Jump:
def canJump(self, nums) -> bool:
if not nums:
return False
c = len(nums)
pos = [0] * c
pos[0] = 1
temp = nums[0]
pos[1:1+nums[0]] = [1]*nums[0]
for i in range(1, c-1):
if pos[i] != 0 and i+1+nums[i]>temp:
pos... |
68b1c7bfd28d3074932dc2eda69c0e77cb00efe5 | Aadhya-Solution/PythonExample | /for_examples/for_add_numbers.py | 405 | 3.515625 | 4 | import pdb
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename='add_num/add_num.log',
filemode='w')
n=input("Enter N:")
if n==0:
logging.warning("Given Number is 0")
logging.info("N:{}".format(n))
c=0
for i in range(n):
c=c+i
lo... |
ea43ef8caf69949ece0b5c34d602b84284cbda4e | Kaushaldevy/sort | /Bubble.py | 453 | 3.921875 | 4 | import time
import random
start = time.time()
def bubbleSort(arr):
for j in range(len(arr)-1):
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
arr = random.sample(range(100,100000),500)
#arr = []
#arr = [1]
#arr = [1,2]
#arr = [4,4,4,4,4,4,4]
#arr =... |
3b9748738cc95b44f3027be51fcd904811f49ab8 | kambiz-kalhor/python--euler-project | /problem 45/problem 45 - 30 seconds.py | 369 | 3.671875 | 4 | import time
startTime = time.time()
listh=[]
n=0
for i in range (1,100000):
p = ((i*((3*i)-1))/2)
h = (i*((2*i)-1))
listh.append(h)
if p in listh:
print (p)
n=n+1
if n ==3:
break
print ("finish")
executionTime = (time.time() - startTime)
print('Ex... |
195a58e9df2ca54cbb82c57c50875af8ed393231 | MarioMartReq/coding-interview | /arrays/rotate-matrix.py | 788 | 4.5625 | 5 | '''You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly.
DO NOT allocate another 2D matrix and do the rotation.
'''
# Explanation: to rotate a matrix, you can reverse it ... |
3fc16fab61213e98c81bc9637c96697f2fc0bf10 | daniel-reich/ubiquitous-fiesta | /q5jCspdCvmSjKE9HZ_16.py | 168 | 3.703125 | 4 |
def lcm_of_list(numbers):
n = 1
for i in numbers:
n = (n*i)//gcd(n,i)
return n
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
|
1585fcf0b62b9e9acb267aaaafac1433765a15e8 | khelwood/advent-of-code | /2018/03_slice.py | 952 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import re
import itertools
from collections import Counter, namedtuple
Claim = namedtuple('Claim', 'id left top width height')
Claim.__iter__ = lambda self : itertools.product(
range(self.left, self.left + self.width),
range(self.top, self.top + self.height)
... |
a3c1aec2682bbcb62a4590c044b863bb56ce1a5b | limapedro2002/PEOO_Python | /Lista_04/Guilherme Ferreira/q1Clista4.py | 118 | 3.5625 | 4 | def conc(*strings):
x = ""
for str in strings:
x += "" + str
return x
print(conc('o','lho'))
|
8242e7dab080fbae6c6b68abd901376661146bd0 | lil-mars/pythonProblems | /algorithms/Linear search/lsearch.py | 679 | 3.859375 | 4 | def binary_search(item_list, item):
first = 0
last = len(item_list) - 1
found = False
mid = 0
while first <= last and not found:
mid = (first + last) // 2
if item_list[mid] == item:
found = True
else:
if item < item_list[mid]:
last = mi... |
50caaaef3b60643ae0dc74b3fd3d8cc1e8784e40 | aziza-calm/python_course_1_faki | /turtle_1/post_code.py | 4,335 | 3.9375 | 4 | import turtle
import math
# Constants
STEP_SIZE = 30
DIAGONAL_STEP_SIZE = math.sqrt(2) * STEP_SIZE
def draw_symbol(symbol, coords):
"""
:param symbol: symbol to draw
:param coords: left upper corner coords
"""
turtle.penup()
if symbol == '0':
turtle.goto(coords[0], coords[1])
... |
7dc74a301f7e7875aac134d3d6eee700c7b01a82 | avhirupc/LeetCode | /problems/Pattern : Untagged/Implement Stack using Queues.py | 980 | 4.125 | 4 | from collections import deque
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q=deque([])
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.q.append(x)
def pop(self) -> int:... |
40e05bad49e93a3794914977f3e522d301757d22 | nhat117/Pythonproject | /car.py | 405 | 3.6875 | 4 | class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.000
def description(self):
return "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
car1 = Vehicle()
car1.name = "Merc"
car1.color = "Red"
car1.value = 100000
car2 = Vehicle()
car2.name = "BMW"
car2.co... |
01670b536bd487a44d02d9a1f89f18d208b4f884 | TaichiSky/python_like | /src/day09_funcAdvance1.py | 2,029 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'advanced features of the function'
__author__ = 'dogsky'
import os
###generate list formula
list_a = range(11)
print('list = ',list(list_a))
#compute the square of each number(List or tuple)
print()
list_aa = [x * x for x in list_a]
print('x*x of list = ',list_aa)
... |
6884890d17ad71278f330b43c8d3afe17bceb032 | veronicarose27/playerset2 | /index03.py | 148 | 3.5 | 4 | m=input()
l=list(m)
p=len(m)
k=[]
o=(p)//3
if(p<=3):
k.append(l[0])
else:
for i in range(0,o+1):
k.append(l[i*3])
print("".join(k))
|
b96dd7321e1e718535019efb21456944af269878 | LauroJr/Python_projeto01 | /Exercícios_Lógica_python/AC_7_lógica_2º_exercício.py | 318 | 3.875 | 4 | si = 0
m = 0
i = 1
while i != 0:
i = int(input("Digite sua idade: "))
si = si+i
if i > 0:
m = m+1
if si > 0:
mi = si/m
print("A média das idades somadas é: ",mi,". A soma é: ",si," anos")
else:
print("Não é possível resumir a conta pois não há entradas coerentes")
|
0075ed1eb20964cca065d6d37370e3b10496ebbf | Jeremy277/exercise | /资料data/pyth自学预习7.11-7.30/demo13随机生成验证码程序for语句改进.py | 362 | 3.9375 | 4 | #1.实现随机生成n位验证码(字母 数字 下划线)
import random
import string
all_chars = string.ascii_letters + string.digits + '_'
i = 1
n = int(input('请输入验证码位数:'))
#定义一个空字符串变量
pwd = ''
#控制循环次数
for i in range(n):
char = random.choice(all_chars)
pwd = pwd + char
print(pwd)
|
c22c90e86a477d8f608cf113795c669c30d06030 | NathanLaing/word-chain | /word_chain.py | 7,361 | 4.03125 | 4 | """
word_chain.py
@autor Nathan Laing and Sam Fleury
"""
import sys
from collections import deque
word_to_index = {}
index_to_word = {}
class Node:
"""
A class for the nodes of the graph.
"""
def __init__(self, word, parent, cost):
"""
Initialises the Node class objects
:par... |
56c433173caccab62794d09ae8102d62c53c68b4 | koiic/python_mastery | /myrange.py | 470 | 3.609375 | 4 | #Implementing my version of the ramge function
def myrange(first, second=None, step=1):
if second is None:
current = 0
maxnum = first
else:
current = first
maxnun = second
if step > 0:
while current < maxnum:
yield current
c... |
d6e0884b603aeb9d3e521c5c9c16b86a3e8373d8 | akimi-yano/algorithm-practice | /lc/1722.MinimizeHammingDistanceAfter.py | 5,871 | 4.125 | 4 | # 1722. Minimize Hamming Distance After Swap Operations
# Medium
# 66
# 2
# Add to List
# Share
# You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and ... |
cffb81271ba9f100472901d7c10b19880cd8191c | nitishkrishna/my_stuff | /python/algos/well_known_algos/BreadthFirstSearch.py | 1,034 | 4.0625 | 4 | """
graph represented as an adjacency list
"""
from Queue import Queue
g = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
class BFS():
def __init__(self):
pass
def brea... |
8e0840b08dea4e4ec6519a70fa771ac9be1e4e69 | licht5/TEST | /qunar/database.py | 793 | 3.578125 | 4 | #!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost", "root", "0801", "RUNOOB")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT sname FROM STUDENT WHERE ssex='FE'")
cursor.execute("CREATE TABLE COURSE (CNO CHAR (4) PRIMARY KEY ,CNAME C... |
4732805df8782ff3763a23e07e692ae328f28afb | ewelkaw/tic_tac_toe | /minimax_alg.py | 1,676 | 3.59375 | 4 | from math import inf as infinity
from collections import namedtuple
from const import Player
from game import Game
def evaluate(game: Game) -> bool:
if game.finished and game.winner == "o":
return 1
elif game.finished and game.winner == "x":
return -1
else:
return 0
def choose_be... |
33c2113d91c16223af2bea7896bb3a86c73756ba | ivan-yosifov88/python_basics | /More While Loop Excercise/01. Dishwasher.py | 867 | 3.9375 | 4 | detergent = int(input())
total_detergent = detergent * 750
command = input()
dishwasher_counter = 0
detergent_over = False
sum_plates = 0
sum_pots = 0
while not command == "End":
number_of_dishes = int(command)
dishwasher_counter += 1
if dishwasher_counter < 3:
sum_plates += number_of_dishes
... |
2af0d783f9c5cb2a1ea8b99414021b33cd0007f9 | RaniaMahmoud/SW_D_Python | /Sheet4/S4/P18.py | 132 | 3.515625 | 4 | from functools import reduce as r
def simulateReduce(L1):
return r(lambda x,y:x+y,L1)
l1=[5,8,6,1,3,4]
print(simulateReduce(l1)) |
65b349711cc37ff28e8e5123d09745218062f160 | suitendaal/RailNL | /PythonFunctions/DijkstraAlgorithm.py | 1,417 | 4.21875 | 4 | def algorithmDijkstraFunction(graph, start, end):
"""algorithm get the best route between two stations"""
bestPath = None
score = 0
for path in graph.allRoutes:
# If the path has the given begin- and endstation, calculate the score.
if (path[0][0] == start and path[0][-1] == end) or (p... |
5425a4a118866201859c2d0983014796e69859b6 | emmas0507/lintcode | /lowest_common_ancestor.py | 1,602 | 3.953125 | 4 | class Node(object):
def __init__(self, value, parent=None, left=None, right=None):
self.value = value
self.parent = parent
self.left = left
self.right = right
def print_node_list(node_list):
for n in node_list:
print(n.value)
def get_path(root, target):
curr_list = ... |
243ae5a9d9538322a362c7cf5f53c515b005e13b | lukeolson/cs450-f20-demos | /demos/upload/toshow2/Relative cost of matrix factorizations.py | 992 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Relative cost of matrix factorizations
# In[1]:
import numpy as np
import numpy.linalg as npla
import scipy.linalg as spla
import matplotlib.pyplot as pt
from time import time
# In[2]:
n_values = (10**np.linspace(1, 3.25, 15)).astype(np.int32)
n_values
# In[9]:
fo... |
2fd0342e9038a5a67fc2ed79e704e9fa3ebe5c7d | ben-spiller/pysys-sample | /test/correctness/MyApp_cor_001/Input/test.py | 78 | 3.625 | 4 | print('Hello world')
x = 1235
if 123 == x:
print ('Nay')
else:
print ('Yey') |
8e549033f4eb67ba0b88d4704037e5186c1cf7d9 | cry999/AtCoder | /beginner/003/B.py | 418 | 3.765625 | 4 | def trump(S: str, T: str)->bool:
for s, t in zip(S, T):
if s == t:
continue
elif s == '@' and t in 'atcoder':
continue
elif t == '@' and s in 'atcoder':
continue
else:
return False
return True
if __name__ == "__main__":
S = in... |
28971ac19be7dff6c8e826f3b5b27c2526147ce3 | shlok57/CodeDatabase | /Random/Subsets.py | 449 | 4.03125 | 4 | '''
generate subsets and sort alphabetically
'''
def give_subset(string):
subsets = []
actual = []
helper(string, subsets, 0, actual)
return actual
def helper(string, subsets, i, actual):
# print subsets, " ", i
if i == len(string):
actual.append(subsets)
else:
helper(string, subsets, i+1, act... |
6342eeb82b24787349998a60011a036951ef8cff | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_84/264.py | 2,051 | 3.625 | 4 | #!/usr/bin/python
blue = []
red = []
#white = []
def ispossible(x,y):
global blue,red
# try:
# print '>',(x>=0) and (y>=0)
# print (y+1 <len(blue))
# print (len(blue[y])>x+1)
# print (blue[y][x]=='#' or blue[y][x+1]=='#' or blue[y+1][x]=='#' or blue[y+1][x+1]=='#')
# print '<',(red[y][x]==' ' and red[y][x+1]... |
b295f5d307f6e64e52923f463f33575ea77c59cf | harshitbhat/Data-Structures-and-Algorithms | /GeeksForGeeks/DS-Course/000-Mathematics/016.digits-in-factorial.py | 872 | 3.671875 | 4 | # Naive - TLE
# class Solution:
# def digitsInFactorial(self,N):
# def factIt(n):
# res = 1
# for i in range(1,n+1):
# res *= i
# return res
# def countDigits(n):
# temp = n
# ans = 0
# while temp:
... |
fbc464fbed152ecda8fcb8885f9a01613796dcae | HanchengZhao/Leetcode-exercise | /398. Random Pick Index/reservor_sampling.py | 1,156 | 4 | 4 | import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
result = -1
count = ... |
a9cf8d768725fcd80bdaacc3e97acf7ed275c0f8 | DigBaseball/python-challenge | /PyPoll/main.py | 3,123 | 4.03125 | 4 | # ___________________________________ #
# ~ ~ ~ IMPORT SOME MODULES ~ ~ ~ #
# Import the os module so we can can create a path to the data file
import os
# Import the csv module so we can read the data file
import csv
# _____________________________________ #
# ~ ~ ~ CREATE SOME VARIABLES ~ ~ ~ #
# Create ... |
599e3e4758166c2b1f93e67c5eed268f6fd61638 | Kevinxu99/NYU-Coursework | /CS-UY 1114/Homework/HW5/sx670_hw5_q4.py | 243 | 3.703125 | 4 | w=input("Enter a word:")
w1=w.lower()
count=0
for i in range(0,len(w1)):
if(w1[i]=='a' or w1[i]=='e' or w1[i]=='o' or w1[i]=='u' or w1[i]=='i'):
count+=1
print(w,"has",count,"vowels and",(len(w)-count),"consonants")
|
351ffdf70e3303e85c1dc113ec1997aa6cc8ce75 | ashwani8958/Python | /PyQT and SQLite/M3 - Basics of Programming in Python/program/function/3_verdict.py | 433 | 3.625 | 4 | #Do i have the enough money to splurge on the latest iphone?
def verdict(m1,m2,m3):
total = m1 + m2 + m3
if total >= 15000:
print("Yes! you can get a new smartphone!")
else:
print("Sorry, you can buy the smartphone!")
return
gift = int(input("Gift money from family: Rs. "))
saving = in... |
89b97983bcc43231cc7e0e4aea20aeb227d5de14 | mohdsohail-Bestpeers/Python-Projects | /inheritance/hybride_inheri_with_super.py | 524 | 3.828125 | 4 | #Hybride inheritance with super()
class rahul():
def __init__(self):
print("rahul is a principle of school ")
class sanjay(rahul):
def __init__(self):
super().__init__()
print("sanjay teach English subject")
class salman(rahul):
def __init__(self):
super().__init__()
... |
8163d6c4079b3d73eb69e2fecc726abc14560911 | victordomene/ram-paxos | /paxos/receivers/receiver.py | 2,002 | 3.640625 | 4 | """
This module defines the abstract class of a receiver. It provides all of
the functionality that is implemented by a specific type of receiver. In
Paxos, we will allow some different types of communication, but all of them
must present this interface.
Notice that a single machine may need to use all of the function... |
163cd2003b814999419d11e19b683fa12c6208d6 | songseonghun/kagglestruggle | /python3/001-050/008-len.py | 287 | 3.71875 | 4 | # the 'len ' bulit-in function
list_var = [1,2,3,4,5]
str_var = 'Hello, wolrd'
dict_var = {"a":100, "b":200}
print(len(list_var))
#5 - 리스트 안의 변수 수
print(len(str_var))
#12 = 글자 수 띄어쓰기 포함
print(len(dict_var))
#2 = 딕셔너리변수 갯수
|
81d1fcf1b53c8aafbb894f1ba1c7efa59d223a28 | Jonathan-aguilar/DAS_Sistemas | /Ago-Dic-2019/Ricardo_Romero_Medina/Practica1/Practica_6-9.py | 256 | 3.671875 | 4 | lugar_favorito={
'Friki Plaza':'Ricardo',
'Cine':'Jose',
'Biblioteca':'Juan'
}
lugar=lugar_favorito.keys()
nombre=lugar_favorito.values()
val=lugar_favorito.items()
for lugar,nombre in val:
print(lugar,'Es el lugar favorito de ',nombre) |
53ffd293531d1ca6bfe39539d3cf830fbe2fa735 | SimasRug/Learning_Python | /Chapter 1/P5.py | 153 | 3.96875 | 4 | import math
cities = int(input('How many cities? '))
num = math.factorial(cities)
print('For ', cities, ' cities there are ', num, ' possible routes')
|
4a0adbd60248443f71c1c6f8ed45fc10129ee9f2 | arghadeep25/Neural-Network-Activation-Functions | /relu.py | 406 | 3.53125 | 4 | import numpy as np
class ReLU():
def __init__(self):
self.val = np.arange(-20, 20, .1)
def function(self):
zero = np.zeros(len(self.val))
y = np.max([zero, self.val], axis=0)
return y, self.val
def derivative(self):
val_func, _ = self.function()
val_func[va... |
69c0582b8c78585d961a69e798717939c64d3bb0 | basfl/yt_dynamic_programing_python_js | /invert_tree/python_impl/tree/node.py | 273 | 3.546875 | 4 | class NewNode:
"""
A Node containing data , left and right pointers
"""
def __init__(self, data):
self.data = data
self.right = self.left = None
def __str__(self):
return f'data={self.data} left={self.left} right={self.right}' |
b4c03f24705768c77640c5223327b60bc8300d95 | rafaelperazzo/programacao-web | /moodledata/vpl_data/3/usersdata/104/424/submittedfiles/ex1.py | 370 | 3.828125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=input('Digite o primeiro termo:')
b=input('Digite o segundo termo:')
c=input('Digite o terceiro termo:')
delta=(b**2)-(4*a*c)
if delta<0:
print('A equação não possui raízes reais')
if delta>=0:
x=((-b)+(delta**0.5))/(2*a)
y=((-b)-(delta**0.5))/(2*a)... |
edb1f6b6665f1afb000afde8f180bc742c17cb9d | ShyZhou/LeetCode-Python | /343.py | 2,288 | 4.03125 | 4 | # Integer Break
"""
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 ... |
f7145134ce878d5fce0c0d05960bfba9868d28c4 | Foknetics/AoC_2018 | /day11/day11-2.py | 1,492 | 3.5625 | 4 | SERIAL_NUMBER = 5034
GRID_SIZE = 300
GRID_SIZE += 1
def power_level(x, y):
rack_id = x+10
power_level = rack_id*y
power_level += SERIAL_NUMBER
power_level = power_level * rack_id
try:
power_level = int(str(power_level)[-3])
except IndexError:
power_level = 0
return power_lev... |
63dade1b2b593eb6cef59c7d431f84506a55f946 | CaptainSherry49/Python-Project-Beginner-to-Advance | /57 Coroutines In Python.py | 977 | 3.625 | 4 | def searcher():
import time
# Some 5 sec time consuming code executed
book = 'Sherry This is a book in which there are lots of stuff'
time.sleep(5)
while True:
text = (yield)
if text in book:
print('Your Text is in book')
else:
print('I cannot found y... |
54b87482e295b759eb23ec9e3717c961de463f68 | Pjoter-B/spyder | /1_Simple_Linear_Regression.py | 1,103 | 3.9375 | 4 | # Simple Linear Regression - data years of experience vs salary and relationship
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1]
# Train test split
from sklearn.model_selection import t... |
36d463b47b9587991c54fdd539f5ba6203a15fc5 | ranierelm/Python_exercise | /ex029.py | 204 | 3.71875 | 4 | vel = int(input('A qual velocidade você passou no radar? '))
valor = (vel - 80) * 7
if vel > 80:
print(f'Você foi multado! \nValor da multa: R${valor}')
else:
print('Velocidade permitida!') |
fe87f45df5f4939468c40dd7a18df44e0cf129b5 | vinnicius-martins/Treinamento-Python | /ex040.py | 216 | 3.90625 | 4 | n1 = float(input("Digite a primeira nota: "))
n2 = float(input("Digite a segunda nota: "))
m = (n1 + n2)/2
if m < 5:
print("REPROVADO")
elif m >=5 and m < 7:
print("RECUPERAÇÃO")
else:
print("APROVADO") |
525776a784c9e311a06d5f67480761164c61bb24 | 3ntropia/pythonDojo | /list/list7/testSortList.py | 542 | 3.578125 | 4 | import unittest
from list.list7 import sortList
class MyTestCase(unittest.TestCase):
def test_not_sorted(self):
self.assertEqual(sortList.is_sorted([2, 9, 3, 8]), False)
def test_not_sorted_letters(self):
self.assertEqual(sortList.is_sorted(['d', 'a', 'h']), False)
def test_is_sorted(sel... |
9d51b5eb35f38cf0d59621e392deb349b623e70c | Dummy-Bug/Love-Babbar-DSA-Cracker-Sheet | /Binary Trees/26.2 LCA of a Binary Tree Recursive.py | 982 | 3.578125 | 4 | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ans = None
self.find_lca(root,p,q)
return self.ans
def find_lca(self,root,p,q): # mainain three flag variables ,mid for root and left,right f... |
20e41786bca24aec0e4b4d582385564653bce1dc | toyijiu/300_python_questions | /300_questions_python/11_arithmetic_progression.py | 72 | 3.609375 | 4 | #用公式产生一个11的等差数列
print([x*11 for x in range(10)]) |
4f554404afe9d4406c18e7ef7ed1ded7de0cc9ce | englishta/python | /machine learning/analysis/ana1.py | 413 | 3.953125 | 4 | # %%
#zipの使い方
seq1 = ['foo', 'bar', 'baz']
seq2 = ['one', 'two', 'three']
#for x, y in zip(seq1, seq2):
# print(x, y)
for i, (a, b) in enumerate(zip(seq1, seq2)):
print(i, a, b)
zipped = zip(seq1, seq2)
a, b = zip(*zipped)#分解する
print(a)
print(b)
# %%
#set
a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
wa = a.uni... |
1c0661b98621a2795e923cc3133b928a5f336905 | amitkayal/Deep_learning_CNN | /ConvolutionalNeuralNetworks.py | 9,030 | 3.859375 | 4 | # Build Convolutional Neural Networks
#Import Keras package.
# Sequential pakage is used to initilize our neural network
from keras.models import Sequential
from keras.layers import Dropout
'''
# Conv2D is used to make first step in CNN that is adding convolutional layers.
# Since we are working on image, an... |
8571e01b97dffe8b2438c0ad009c7569b55b58eb | jfharney/ornl-poller | /practice/pet.py | 461 | 3.671875 | 4 | class Pet(object):
def __init__(self,name,species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
... |
8085ad7b719b62c3f255b6c586ffcdb80327de50 | Aftabkhan2055/Machine_Learning | /python1/quadratic.py | 382 | 3.9375 | 4 | import math
a=int(input("enter the no"))
b=int(input("enter the no"))
c=int(input("enter the no"))
d=b**2-4*a*c
if d<0:
print(" root are imaginary",d)
elif d==0:
root=math.sqrt(d)/2*a
print("root are equal",root)
else:
root1=-b+math.sqrt(d)/2*a
root2=-b-math.sqrt(d)/2*a
print("sepr... |
2c2303fad210e9542808b282f1385b6b76255b63 | sebito91/challenges | /exercism/python/archive/space-age/space_age.py | 1,643 | 3.78125 | 4 | """ Module to return the 'earth' time on different planets """
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SpaceAge(object):
""" structure to handle our time conversion """
def __init__(self, seconds=0):
""" Instantiate our space_age calculator """
self._seconds = fl... |
bce631569f3e2d95d0b176179c8c137006c7ce95 | zzinsane/algos | /countRangeSum.py | 2,916 | 3.578125 | 4 | """
Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.
Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.
Example:
Given nums = [-2, 5, -1... |
2abdfaedcef487323adf8c1eb73c20b37210035a | DreamOfTheRedChamber/leetcode | /Python/SweepLine/MyCalendarIII.py | 1,150 | 3.625 | 4 | # Definition for a binary tree node.
import heapq
import unittest
# Read about enumerate in python
from collections import defaultdict
from typing import List
from sortedcontainers import SortedSet, SortedList
class MyCalendarThree:
def __init__(self):
self.sortedBoundaries = SortedList(key=lambda x: (x[... |
e18dceced9cd2309f1ea7972e6f41a22392e5977 | lucasayres/python-tools | /tools/reverse.py | 241 | 4.1875 | 4 | # -*- coding: utf-8 -*-
def reverse(input):
"""Reverse the order of a list or string.
Args:
input (str/list): List or String.
Returns:
str/list: Return a reversed list or string.
"""
return input[::-1]
|
44d88e151517c747ef5d8e590a8f4569d224c5a2 | egjallo/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/4-print_square.py | 634 | 3.984375 | 4 | #!/usr/bin/python3
"""
This is the "4-print_square" module
for the Holberton School Higher Level Programming track.
The 4-print_square module supplies one function, matrix_divided().
For example,
>>> print_square(4)
####
####
####
####
"""
def print_square(size):
""" Prints a square made with the char `#`. """... |
52f0e54bcc1ed76f6bdbde46ebf83da745676b28 | priyanshkedia04/Codeforces-Solutions | /Part A/A and B and Chess.py | 337 | 3.65625 | 4 | lower = dict(zip(list('qrbnp'), [9,5,3,3,1]))
upper = dict(zip(list('QRBNP'), [9,5,3,3,1]))
white = 0
black = 0
for i in range(8):
for j in input():
if j in lower:
black += lower[j]
elif j in upper:
white += upper[j]
if black > white:
print('Black')
elif black < white:
print('White')
else:
... |
34ad8ab18fa3253fd1469bae2366d4d2548380db | BABIN2D/Employee-Eligiblity- | /Employee.py | 4,987 | 3.859375 | 4 | # ask user to provide input for age gender and physical disability.
# if anyone is above the age of 45 the work in urban areas, all female workers
# work in urban areas, any disabled person work in urban areas rest
# will work any location
# ask for qualification, the following are the criteria and accordingly
# the ... |
e54b209801aa23895bbff5cc96547e58a4aea656 | Constadine/Misc | /other/time.py | 351 | 3.8125 | 4 | hours = int(input("Δώσε ώρες: "))
minutes = int(input("...λεπτά: "))
seconds = int(input("...και δευτερόλεπτα: "))
if hours < 10:
hours = "0" + str(hours)
if minutes < 10:
minutes = "0" + str(minutes)
if seconds < 10:
seconds = "0" + str(seconds)
print(str(hours) + ":" + str(minutes) + ":" + str(seconds... |
fd0b1700bb7f1edf956cab204426826a53e6e66f | brucehzhai/Python-JiangHong | /源码/Pythonpa/ch12/listbox.py | 497 | 3.84375 | 4 | from tkinter import * #导入tkinter模块所有内容
root = Tk(); root.title("Listbox") #窗口标题
v = StringVar()
v.set(('linux','windows','unix'))
lb = Listbox(root, selectmode=EXTENDED, listvariable = v)
lb.pack()
for item in ['python','tkinter','widget']: lb.insert(END,item) #列表框
lb.curselection() #... |
586eb9438e244f912e9c086789ea3f6481ac4a25 | tagler/MIT_Computer_Science_Python | /exam_midterm.py | 4,004 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
PROBLEM 1
Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b.
For example, if x = 16 and b = 2, then the result is 4 - because 2^4=16. If x = 15 and b = 3, then the
result is 2 - because 3^2 is the largest power of 3 less than 15.
In oth... |
7c7ce615831c6ccef1d0bdeea4a03b44567cc779 | taha717/python | /cheeking py3_file.py | 1,475 | 4.21875 | 4 | import os
# Setting variables
one = 1
comment_char = "#"
space = " "
comment = "comment"
code_line = "line"
total_line = "line"
plural = "s"
# Initialising line counters
comment_counter = 0
code_counter = 0
line_counter = 0
# Getting file name from user
file_name = input("Please enter the name of fi... |
3f49f9750d7211b8f0e4a391af5b3cd2531c108d | Bara-Ga/SmartninjaCourse | /python_00100_datatypes_calculator/example_00130_show_types_quiz.py | 368 | 3.734375 | 4 | print type(str(1))
print str(1)
eingabe_1 = "1"
eingabe_2 = "2"
print 3+4
print eingabe_1 + eingabe_2 # concat
print int(eingabe_1) + int(eingabe_2)
print float(eingabe_1) + float(eingabe_2)
resultat_1 = int(eingabe_1) + int(eingabe_2)
resultat_2 = float(eingabe_1) + float(eingabe_2)
print resultat_1 == resulta... |
954bfeb1f35c90f1ad4b3b3b25d4d49f43302d7e | Pratyaksh7/Dynamic-Programming | /Longest Common Subsequence/Problem2.py | 698 | 3.71875 | 4 | # 2. Longest Common Substring -> means continuous sequence
def longestSubstring(X,Y, n,m):
# Initialization of first row and first column of the t matrix
for i in range(n+1):
for j in range(m+1):
if i==0 or j==0:
t[i][j] = 0
for i in range(1, n+1):
for j in rang... |
dc1fa99bcb723fc22f603d40ddbb9ce89fa1321c | ishanlal/data-structures-and-algorithms | /Data Structures/problem_3.py | 8,836 | 3.609375 | 4 | import sys
from queue import PriorityQueue
from functools import total_ordering
dic_ = {}
class Tree:
def __init__(self, data=None):
self.root = Node(data, None, None, None)
def get_root(self):
return self.root
def set_root(self, node):
self.root = node
@total_ordering
class Node:
... |
03c9a3f9cd906088b50a2397b9ce3c4b049c0c31 | dm36/interview-practice | /interview_cake/permutations.py | 3,204 | 4.15625 | 4 | # All permutations of a string with the same length as the original string
# Take a string "abc":
# Take away a character- say a- so that we now have the string "bc"
# Form all permutations of bc ["bc", "cb"] (recursively)
# For each permutation of bc, concatenate a at every possible spot in the string, so for bc:
# [... |
e91bfa8a9d596db19b6bbdb024135193577c3a4b | BenGeissel/Movie_Industry_Insights_Module_1_Project | /Module_1_Project/tmdb_clean.py | 5,965 | 3.53125 | 4 | # Import libraries with proper aliases
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import csv
# Create function to fix numerical data; Budget and Gross have '$' and ','; Change to integer
def budget_gross_number_fix(dataframe, column):
'''
Function to fix the fo... |
2f081d12548518050ed4e70fd4fd3d57f57a2159 | aherzfeld/udacity_cs101 | /Unit5/problem_set_optional/shift_n_letters.py | 701 | 3.796875 | 4 | # Write a procedure, shift_n_letters which takes as its input a lowercase
# letter, a-z, and an integer n, and returns the letter n steps in the
# alphabet after it. Note that 'a' follows 'z', and that n can be positive,
#negative or zero.
def make_alphabet():
p = []
i = 0
while len(p) < 26:
p.append(chr(ord('a')... |
18e393e221345ad06e17c5f9f8a0c07b120a683f | AndriiLatysh/ml_course | /python_4/point.py | 946 | 3.828125 | 4 | import math
class Point:
def __init__(self, x, y):
self.x_coordinate = x
self.y_coordinate = y
def calculate_distance_to_origin(self):
distance = math.sqrt(self.x_coordinate ** 2 + self.y_coordinate ** 2)
return distance
def move(self, x_shift, y_shift):
self.x_c... |
c7183bf73a4bec8aeaa1e04463e0649ea0699982 | Halverson-Jason/cs241 | /week2/check02b.py | 609 | 3.71875 | 4 | def prompt_file():
return input("Enter file: ")
def open_file(file_name):
return open(file_name, "r")
def get_lines(user_file):
line_counter = 0
word_counter = 0
for line in user_file:
word_counter += len(line.split())
line_counter += 1
word_line_count = [line_counter,word_... |
0c823eee30a2b5d26e28ac04b61ff205c1eedb35 | hashtagallison/Python | /Practice_STP/Examples_Notes/Ch6.2_STP.py | 4,747 | 4.40625 | 4 | # https://www.theselftaughtprogrammer.io
# Cory Althoff - The Self-taught Programmer
# Chapter 6.2 pg 92 - More String Manipulation
# hashtagallison - Practice 2019-04-08
#-------------------------------------------
#-------------------------------------------
# EXAMPLE: pg 92-93
#-----------------------------------... |
0057cb293f457c6234f188c18a34e4a25ea6f9b7 | guruv22/Test_Scripts | /test.py | 3,055 | 3.796875 | 4 | # a = "abc"
# b = "abc"
# print(a)
# print(b)
# print(id(a))
# print(id(b))
# print("----------------")
# # print(id(a+"x"))
# # print(id(b+"x"))
#
# print(a+"x")
# print(b+"x")
# print(id(a+"x"))
# print(id(b+"x"))
# print(id(a+"x"))
# print(id(b+"x"))
# a = "abc"
# b = "abc"
#
# # print(a+"x")
# # print(b+"x")
# #... |
5bcf1fe446ef2c12036549395deff411683e5c9b | QingfengTang/Algorithms-and-Data-Structures | /剑指offer/sort.py | 6,435 | 3.984375 | 4 | '''
将一组数按照大小排序
!!!note:当列表作为参数在函数间传递时,对列表的修改要注意深浅拷贝
例如 对于列表array 在函数中进行array[i]=value 这种修改时为深拷贝,会对原来的array进行修改
而对于array=[value]时为浅拷贝,这是array的变化不会影响原来的array
'''
class Sort():
# array一维列表
def BubbleSort(self, array):
'''
冒泡排序 时间复杂度O(n^2)
1.将a[j]和a[j+1]比较大的放后面,依次遍历一遍,大的数就在尾端冒泡
... |
6aef77ed808d0014c4ebdd52aacdb2fda8595b40 | eduardonery1/Coding-Interview | /4. Trees and Graphs/4.4-Check_Balanced.py | 1,437 | 3.8125 | 4 | from graph import Node
def findHeight(node, height=0) -> int:
if node:
height += 1
left_height = findHeight(node.left, height=height)
right_height = findHeight(node.right, height=height)
return max(left_height, right_height)
return height
def isBalanced(node, balanced... |
7407046760510cc60cd8d0683abaf4881bc04957 | CarlosDNieto/python-snipps | /Data Science From Scratch/Chapter 1/01_FriendSuggester.py | 6,276 | 3.59375 | 4 | from __future__ import division # integer division is lame
from collections import Counter
from collections import defaultdict
# * Book: Data Science From Scratch by Joel Grus
# * This intro in from the page 22 (pdf page)
# * Title: Data Scientist You May Know Suggester
# Teorical Objectiv... |
c094cf8704df88dc7d7b5770fc88424a02a41c39 | I-will-miss-you/CodePython | /Curso em Video/Duvidas/d013.py | 416 | 3.6875 | 4 |
#Importando biblioteca:
from tkinter import *
#Definindo função:
def onClick():
print('Você clicou no botão OK!')
#Código da gui:
janela = Tk()
#Cria botão com texto = "OK" e comando associado: aoClicarOk()
bt_ok = Button(janela, text='OK', command=onClick)
#Usa-se pack() como gerenciador de layout
bt_ok.pa... |
93af342cace874760c40e024616f66967d7a86fe | adannogueira/Curso-Python | /Exercícios/ex096.py | 354 | 4.0625 | 4 | # Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno
# retangular (largura e comprimento) e mostre a área do terreno.
def área(l, c):
print(f'Área: {l * c}m²')
if __name__ == '__main__':
print('Para cálculo da área do terreno, informe:')
área(int(input('Largura: ')), int(in... |
76955c53a7338aed39142e1ab160eafc47a7b171 | jupmarsat/codewars_kata_python3 | /What is between.py | 1,205 | 4.21875 | 4 | #!/usr/bin/python3
#CODEWARS Kata exercise: What is between?
#https://www.codewars.com/kata/55ecd718f46fba02e5000029/train/python
#Tests Passed: 54
#Tests Failed: 0
#Instructions: Complete the function that takes two integers (a, b, where a < b)
#and return an array of all integers between the input parameters, i... |
86b2a025483f0c697bc1facb1da689d27a8a06ba | LucasAraujoBR/Python-Language | /pythonProject/Python Basic/aula9.py | 515 | 4.3125 | 4 | """
Aula 9 - Entrada de dados (input)
"""
name = input('Whats your name? ') #input sempre retorna string!
print(f'your name is {name}, and your type is ' f'{type(name)}.')
age = input("Whats your age? ")
print(f"{name} have {age} years old.")
yearsOfBirth = 2021 - int(age)
print(f'{name} he was born in {years... |
b3b678f5c4fd0df65368905728e95f5ef9b75530 | atozzini/CursoPythonPentest | /PycharmProjects/ExerciciosGrupo/exercicio084.py | 517 | 4.03125 | 4 | pizza = ["mussarela", "tomate", "calabresa", "oregano", "farinha", "molho"]
if "mussarela" in pizza:
print("mussarela adicionada")
if "tomate" in pizza:
print("tomate adicionado")
if "calabresa" in pizza:
print("calabresa adicionada")
if "oregano" in pizza:
print("oregano adicionado")
if "farinha" in p... |
ff262b7961eccb0a355b3a0a5c19218500e56c76 | zhouli01/python_test01 | /sum_a_b.py | 203 | 4.15625 | 4 | #!/usr/bin/python3
# coding:utf-8
a = int(input('请输入a的值:'))
b = int(input('请输入b的值:'))
'''
a = a^b
b = a^b
a = b^a
'''
a,b=b,a
print("交换后的值:" ,a , b )
|
c5c48cfe17ae7da95d9d391fb50e7df89230650a | MateusCohuzer/Exercicios-do-Curso-em-Video | /Curso_em_Video_Exercicios/ex009.py | 490 | 3.75 | 4 | n = int(input('Qual número você quer ver a tabuada? '))
print('=' * 10)
print('{} X {} = {}'.format(n, 1, n*1))
print('{} X {} = {}'.format(n, 1, n*2))
print('{} X {} = {}'.format(n, 1, n*3))
print('{} X {} = {}'.format(n, 1, n*4))
print('{} X {} = {}'.format(n, 1, n*5))
print('{} X {} = {}'.format(n, 1, n*6))
print('{... |
cfffdcab48b26afdb68cbfd0d757583caa2ad526 | KarashDariga/week1 | /45.py | 94 | 3.578125 | 4 | for x in range(2, 6): # [2...6)
print(x)
# for x in range(a, b+1) [a...b]
# print(x) |
ccf4ccea0b71fc80a6bdfd345bba0c40ea1e5f1f | freelikeff/my_leetcode_answer | /leet/309answer.py | 826 | 3.65625 | 4 | #!D:\my_venv\Scripts python
# -*- coding: utf-8 -*-
# @Time : 2019/10/3 8:55
# @Author : frelikeff
# @Site :
# @File : 309answer.py
# @Software: PyCharm
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 因为交易次数限制为正无穷,所以k的情况等于k-1
thedaybeforeyester =... |
b0a6884ef31e7bd6dcdf7d312d44dff60247676c | CuiFengming/Call_center_data_Analysis | /daily_call_count_forecast/preprocessing.py | 3,295 | 3.625 | 4 | import pandas
from pandas import Series, DataFrame, read_csv
from sklearn.preprocessing import LabelEncoder
def preprocessing(target_column):
# Load dataset(csv) & 지역은 서울에 한정
dataset = pandas.read_csv('./dataset_final.csv')
dataset = dataset[:][(dataset['Area_code'] == '002-')]
# Classify y values to ... |
691d2ee31ec543bcfbf88089f06140691a3235c7 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 4/Exercise4-2.py | 945 | 4.1875 | 4 | import polygon
import turtle
def draw_a_petal(turt,arc):
"""It draws one petal of the flower
turt:The turtle instance
arc:The angle of the arcs.
"""
for i in range(2):
polygon.arc(turt,100,arc)
turt.lt(180-arc)
def paint_flower(turt,petals):
"""It draws a flower of n petals
... |
3b553604f43a79c29da5770975c3cf69b5b2f453 | yuanrunsen/Sword-to-offer | /src/sort_and_search/004.py | 3,929 | 4.03125 | 4 | # 归并排序
def merge_sort(array, start, end):
if not array or start is None or end is None:
return
# 当递归到最后只剩1个或两个元素时 排序
if end-start <= 1:
if array[start] > array[end]:
array[end], array[start] = array[start], array[end]
return start
else:
# 拆分递归
mid = (s... |
690e8c100adc3b07cdc5177bab13277d2e467db2 | balintdorner/exam-basics | /oddavg/odd_avg_test.py | 638 | 3.546875 | 4 | import unittest
from odd_avg import *
class TestOddAvg(unittest.TestCase):
def test_odd_average_empt_list(self, integer = []):
odd_avg = OddAvg()
integer = []
self.assertEqual(odd_avg.odd_average(integer), 0)
def test_odd_average_only_odd(self, integer = []):
odd_avg = OddAvg()... |
9d021767cf4ab8be787c2a83273be893a45336a5 | anti401/python1 | /python1-lesson7/loto.py | 2,733 | 3.625 | 4 | # coding : utf-8
# детали задания в task.txt
import random
class Ticket:
def __init__(self):
# генерируем 15 случайных чисел
numbers = set()
while len(numbers) < 15:
numbers.add(random.randint(1, 90))
# сохраняем в отсортированном виде как список и кортеж
self.... |
f1230981091c81e811888dde0220a9055dec1c03 | niefy/LeetCodeExam | /explore_easy/dynamic_programming/MaxProfit.py | 1,246 | 3.90625 | 4 | """
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/23/dynamic-programming/55/
题目:买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
@au... |
70becfda5c39f6de278654fb9a5e5b8d35c40f3f | ikramulkayes/University_Practice | /practice69.py | 240 | 3.6875 | 4 | def convert_to_list(square_matrix_dict):
lst = []
for k,v in square_matrix_dict.items():
lst.append(v)
return lst
square_matrix_dict = {1 : [1,2,3] , 2 : [4,5,6] , 3 : [7,8,9] }
print(convert_to_list(square_matrix_dict)) |
6b7f19ab22fa5c4665550582e71698e2827e3bdf | anyone27/Automate-the-Boring-Stuff | /diceRoller.py | 283 | 3.875 | 4 | import random
dice1 = 0
dice2 = 0
def roll():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print("First dice rolled was a " + str(dice1))
print("Second dice rolled was a " + str(dice2))
print("Together these total " + str(dice1 + dice2))
roll()
|
1704a78c28588f21bea3175e9169b9a5b938deb4 | rvkeerthana/myprogram2 | /B10.py | 126 | 3.734375 | 4 | import math
def countDigit(n):
return math.floor(math.log(n,10)+1)
n=34567890
print("number of digits: %d %(countDigit(n)))
|
4301a9f6a244a660ea5dda8004711adb8a0fe08b | ramonvaleriano/python- | /Cursos/Curso Em Video - Gustavo Guanabara/Curso em Vídeo - Curso Python/Exercícios/desafio_067.py | 301 | 3.90625 | 4 | # Program: desafio_067.py
# Author: Ramon R. Valeriano
# Description:
# Updated: 29/09/2020 - 17:52
while True:
number = int(input('Digite um número: '))
if number<0:
break
n = 0
print('='*30)
for i in range(1, 11):
n = i * number
print(f'{i:2} * {number:2} = {n:3}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.