blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
115e777efb051ba28d7f2919e7e506f04e052ad5
francisco-igor/ifpi-ads-algoritmos2020
/Fabio01_Parte01/f1_q14_media_ponderada.py
551
3.921875
4
# ENTRADA nota1 = int(input('Valor da 1ª nota: ')) peso1 = int(input('Peso da 1ª nota: ')) nota2 = int(input('Valor da 2ª nota: ')) peso2 = int(input('Peso da 2ª nota: ')) nota3 = int(input('Valor da 3ª nota: ')) peso3 = int(input('Peso da 3ª nota: ')) # PROCESSAMENTO soma_das_notas = (nota1 * peso1) + (n...
da61efbacb5a2b35338e444a00b18f2bbc118bfc
francisco-igor/ifpi-ads-algoritmos2020
/repeticoes_e_strings/uri_1150_ultrapassando_z.py
247
3.71875
4
def main(): x = int(input()) z = 0 while z <= x: z = int(input()) cont = 1 soma = x while x <= z: x = x + soma + 1 soma = soma + 1 cont = cont + 1 print(cont) main()
f1391f8b78a1f97dcb5bc2dde4b4e9a19ba997bc
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2b - Condicionais/G_Fabio_2b_q12_inteiro_decimal.py
332
3.96875
4
'''Leia um número e escreva se o número é inteiro ou decimal.''' # ENTRADA def main(): num = float(input('Número a ser verificado: ')) itdc(num) # PROCESSAMENTO def itdc(num): if num % 1 == 0: print('O número é inteiro.') else: print('O número é decimal.') # SAÍDA main(...
c6ade138941c4795b7a69cacc3c80868705585ff
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2b - Condicionais/G_Fabio_2b_q16_tabajara_.py
3,363
4.28125
4
'''O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira: Até 5 Kg Acima de 5 Kg Filé R$ 4,90 por Kg R$ 5,80 por Kg Alcatra R$ 5,90 por Kg R$ 6,80 por Kg Picanha R$ 6,90 por Kg R$ 7,80 por Kg Para atender a todos os clientes, cada cliente poderá leva...
6322535ab2953a7a315c671329a018b60f5e4da7
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q24_coeficiente.py
639
4.03125
4
'''Leia os coeficientes (A, B e C) de uma equações de 2° grau e escreva suas raízes. Vale lembrar que o coeficiente A deve ser diferente de 0 (zero).''' # ENTRADA def main(): a = int(input('Valor do coeficiente A: ')) b = int(input('Valor do coeficiente B: ')) c = int(input('Valor do coeficiente C: ...
1c98ab786491e08eaf137e08025b7fad1caab516
francisco-igor/ifpi-ads-algoritmos2020
/repeticoes_e_strings/uri_1131_grenais.py
875
3.609375
4
def main(): grenais = 0 vit_inter = 0 vit_gremio = 0 empates = 0 while True: grenais += 1 vi, vg = input().split() vi = int(vi) vg = int(vg) if vi > vg: vit_inter += 1 elif vi < vg: vit_gremio += 1 else...
194839227386322a84746edd795bd098c33e00d8
francisco-igor/ifpi-ads-algoritmos2020
/Fabio01_Parte01/f1_q18_circunferência.py
184
3.609375
4
# ENTRADA raio = int(input('Valor do raio: ')) # PROCESSAMENTO comprimento = 2 * 3.14 * raio # SAÍDA print(f'O valor do comprimento da circunferência é de {comprimento} m')
c393fc5d6020cc51b7dffee8ea8f727834f443ad
francisco-igor/ifpi-ads-algoritmos2020
/Fabio01_Parte01/f1_q12_salário.py
243
3.59375
4
# ENTRADA salário = int(input('Salário do trabalhador: R$ ')) # PROCESSAMENTO aumento = (salário * 25) / 100 novo_salário = salário + aumento # SAÍDA print('O novo salário do trabalhor é de R$ {:.2f}'.format(novo_salário))
3fca3c935ac7315821f6cf7a641bb8cc947f99cf
francisco-igor/ifpi-ads-algoritmos2020
/Fabio01_Parte01/f1_q16_quadrado.py
168
3.671875
4
#ENTRADA lado = int(input('Valor do lado de um quadrado: ')) #PROCESSAMENTO área = lado ** 2 # SAÍDA print(f'O valor da área do quadrado é de {área} m')
e0f104cd802d9f0697ac0c8ca7cb0d8d82061d70
francisco-igor/ifpi-ads-algoritmos2020
/semanas_3_4_funcoes_operadores/uri_1011_esfera.py
181
3.921875
4
def main(): R = float(input()) esfera(R) def esfera(R): pi = 3.14159 esfera = (4/3) * pi * (R**3) print('VOLUME = {:.3f}'.format(esfera)) main()
ae876fd71ac1d82e14c3c37f4be4058a82aece0f
francisco-igor/ifpi-ads-algoritmos2020
/Fabio01_Parte02/f1_p2_q13_idade_anos.py
344
3.6875
4
# Leia a idade de uma pessoa expressa em anos, meses e dias e escreva-a expressa apenas em dias. # ENTRADA anos = int(input('Leia uma idade em anos: ')) meses = int(input('Meses: ')) dias = int(input('Dias: ')) # PROCESSAMENTO dias_total = anos * 365 + meses * 30 + dias # SAÍDA print(f'A idade total em di...
8594a9a864bcf64953d418b4220eb6f98c5a1070
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q18_operações.py
1,190
4.21875
4
'''Leia dois valores e uma das seguintes operações a serem executadas (codificadas da seguinte forma: 1 – Adição, 2 – Subtração, 3 – Multiplicação e 4 – Divisão). Calcule e escreva o resultado dessa operação sobre os dois valores lidos.''' # ENTRADA def main(): valor1 = int(input('Digite um valor: ')) v...
d5a77ffc05b686cfe9bd978a10a133c11f7d109f
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q12_par_impar.py
363
3.78125
4
'''Leia 1 (um) número inteiro e escreva se este número é par ou impar.''' # ENTRADA def main(): numero = int(input('Digite um número: ')) par_ou_impar(numero) # PROCESSAMENTO def par_ou_impar(num): if num % 2 == 0: print(f'O número {num} é par.') else: print(f'O número {num...
f8cf1b25f2f1d6d6567057734546c79fc2b7bf94
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q29_quadrado_perfeito.py
823
4.15625
4
'''Um número é um quadrado perfeito quando a raiz quadrada do número é igual à soma das dezenas formadas pelos seus dois primeiros e dois últimos dígitos. Exemplo: √9801 = 99 = 98 + 01. O número 9801 é um quadrado perfeito. Escreva um algoritmo que leia um número de 4 dígitos e verifique se ele é um quadrado perfeit...
e44fadb5c06b8ffd8469759532f2a2c2d8f184d9
francisco-igor/ifpi-ads-algoritmos2020
/Fabio01_Parte02/f1_p2_q14_idade_dias.py
339
3.734375
4
# Leia a idade de uma pessoa expressa em dias e escreva-a expressa em anos, meses e dias. # ENTRADA dias = int(input('Leia uma idade em dias: ')) # PROCESSAMENTO anos = dias // 365 meses = (dias % 365) // 30 dias = (dias % 365) % 30 # SAÍDA print(f'A idade total é de {anos} ano(s), {meses} mês(meses) e {d...
1d223d0f2a77c763bd99b58e5de56e908fdb70f3
BDouchet/SemanticSegmentation-Internship
/data processing/Visualization.py
656
3.59375
4
import cv2 import numpy as np import matplotlib.pyplot as plt ### allows to visualize the masks of the image. For instance : [2,3] for class 2 AND 3### def visualise(filename,filter): img = cv2.imread(filename)[:, :, 2] mask=np.zeros((np.shape(img))) for i in filter: mask[:,:][img[:,:]==i]=1 m...
a4985f8142330f118f574067798993987b23aa3e
Yousef497/Professional-Data-Analyst-Track
/BikeShare_Project/bikeshare_first_project.py
7,119
4.28125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
ced72946cb76dd23bef17fa807bf492cb90887a2
B-Manitas/Text-Editor
/main.py
16,381
4.15625
4
""" This script allow to create simple text editor application. This software was made in Python 3 on Windows 10. Package used: Tkinter Use: python main.py: ButtonFonctionality, MainApplication ButtonFonctionality (class): ButtonFonctionality is a class containing functionality for buttons. ...
e91cd63e217f3120d7f88d3bece570f01d557114
ray530/prueba
/DiazRay_Ejercicio1.py
438
3.53125
4
#Funcion de angulo def angulo_sol(Hora_militar): horas, minutos = Hora_militar.split(':') #separar string en 2 ints Horas_=int(horas) + int(minutos)/60 #Cantidad de horas if Horas_<= 6.00 or Horas_>=18.00: print("No hay sol", "A las ", Hora_militar) if Horas_>6.00 and Horas_<=18.00: print("Ángulo del sol ...
53c8628862bd98bf1ae2dda071e33b41cf65ad35
sky7ark/Simulation-Project
/SimulationProject.py
2,237
3.59375
4
import random print("LAB PROJECT SIMULATION\n\n") len=int(input("Enter Arrival time: ")) vet = [random.randint(10,80) for _ in range(len-1)] vet1 = [random.randint(10,80) for _ in range(len)] arrRandom=[0]+vet arrivalTime =[0]+ [random.randint(1,10) for _ in range(len-1)] print("Random number of TBA") for i...
bf68585eca35565383742bbf54e144417be91fe9
ryanlee95618/puzzles
/3inarow.py
4,652
3.53125
4
from puzzleClass import Puzzle, Cell #initiate selenium from selenium import webdriver browser = webdriver.Chrome() #open 'root' webpage browser.set_window_position(650, 0) url = 'https://www.brainbashers.com/show3inarow.asp?date=0126&diff=2&size=18' browser.get(url) browser.execute_script("return arguments[0].scrol...
2ee1e894c44cd7a08dd757d0fb786a52aa25fd4c
ysluckly/Hello-Linux
/python/Day1/test1.py
4,334
3.875
4
#!/usr/bin/python #coding:utf-8 ''' python 概述 ''' #from __future__ import division #除法方法 print "hello python" #输出hello #第一种执行:python+文件 #第二种执行: #chmod +x 文件名 #./文件名 #python是动态强类型 #解释时检查类型,不支持隐士类型转换 #变量与赋值 #直接赋值 a=1 b=0.5 #链式赋值 a=b=c=1 #增量赋值 a= 10*2 a=208*b #多元赋值 x,y = 1,2 #给同一变量赋值,最后一次为准 a=0.5 a=2 a="123" #######...
29007b1abbfe1a0b6204c8693ee5fbdaf90486d1
jhand2/ml-classifiers
/models/nbclassifier.py
2,034
3.75
4
""" Jordan Hand, Josh Malters, and Kevin Fong CSE 415 Spring 2016 Professor: S. Tanimoto Final Project Naive Bayes classifier. Uses naive bayes method to classifiy records. """ import math class nbclassifier(object): def __init__(self, trainer): super(nbclassifier, self).__init__() self.data = t...
300596f7cc439f968ffe1bb985d4de29368c3800
mathi98/madhu
/swap/swap.py
98
3.53125
4
a,b=input().split() a=int(a) b=int(b) temp=a a=b b=temp print(" ",format(a)) print(" ",format(b))
f4a0084220f4dfd91ddf79b14c1e166d67d4e9cc
mathi98/madhu
/rmodified.py
133
3.703125
4
k=input() a=0 for i in k: if i=='a'and i=='b': a+=1 else: a=0 if a>1: print("yes") else: print("no")
bde1c171208db7eb41eda2f49c936e721ac154a0
mathi98/madhu
/between.py
115
3.578125
4
k=int(input()) a,b=input().split() a=int(a) b=int(b) if(k in range(a+1,b)): print("yes") else: print("no")
7824163a3def5b0466be9205b895bc4987bee80d
mathi98/madhu
/during.py
294
3.671875
4
k=str(input()) m=len(k) a=m//2 if(m%2!=0): for i in range(0,1): if(i==a): print("*",end="") else: print(k[i],end="") else: for i in range(0,1): if i==a-1 or i==a: print("*",end="") else: print(k[i],end="")
c8d583db90939476c5a02e41b49f0d086400f4c7
vivia618/Code-practice
/Reverse words.py
593
4.3125
4
# Write a function that reverses all the words in a sentence that start with a particular letter. sentence = input("Which sentence you want to reverse? : ").lower() letter = input("Which letter you want to reverse? : ").lower() word_in_sentence = sentence.split(" ") new_sentence = [] def special_reverse(x, y): x...
b1b6cc0e046df3dff0af5f55358a521e8dd82eb1
GordonQuach/Engineering-Programming-Projects
/Bio.py
1,660
4
4
print("Welcome to GQ's first Bioinformatics program!") # Setting empty variable to store values. G = 0 C = 0 A = 0 T = 0 # Set variable to true to continue while loop. still_Count = True while(still_Count): # Opens and reads in inputted file. file_Name = raw_input("Enter the file storing genetic data: \t") pri...
3c77c02d8465f0da8977a161943ca4de62271502
hatamirais/Using-Pyhton-to-Access-Web-Data
/Week 2/assigmnet.py
390
3.671875
4
import re name = input('Enter file:') handle = open(name) #create empty list of number number = [] total = 0 for line in handle: line = line.rstrip() #find number start from 0-9 y = re.findall( '[0-9]+', line) #add found number to the empty list number = number + y #adding total number found f...
eae73a83d575a53ac72302d59a1ff7c08d35a5b8
harrtedwin/Projects
/classes/classTwo.py
455
3.5625
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 4 03:09:24 2022 @author: Phoenix """ class Team: def __init__(self, Name ="Name", Origin="Origin"): self.teamName = Name self.teamOrigin = Origin teamOne = Team('Arusha', 'Tanzania') teamTwo = Team('Kigali', 'Rwanda') teamThree=Team() ...
e747416cd343e9ca0f7e68091ec02d93b947cdfa
MohamedFawzy/Data-Structures-And-Algorithms-Specialization
/course1/week2/fibonacci.py
843
3.9375
4
# Uses python2 import random def naive_calc_fib(n): if (n <= 1): return n return naive_calc_fib(n - 1) + naive_calc_fib(n - 2) def calc_fib(n): if n==0 or n==1: return n f = range(0,n+1) f[0]=0 f[1]=1 for i in range(2, n+1): f[i] = f[i -1] + f[i - 2] return f...
e200d0a74379d1115d10173f0999dc1287b63c16
Harsh2790/Positive-numbers
/ABC.py
133
3.546875
4
l = [12,13,-35,-14,6] p1 = [] n1 = [] for i in l: if i>0: p1.append(i) else : n1.append(i) print(p1) print(n1)
c759b9b0b77b38d773482210b6b86685f67b224d
TejshreeLavatre/CrackingTheCodingInterview
/Data Structures/Chpt1- Arrays and Strings/3-URLify.py
871
4.3125
4
""" Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation i...
bc6efeabe016700f3f1ca1f8597d3aa2cae6ae30
Wangdaoshuai/python_learning
/python入门/08面向对象/hm_12_摆放家具_02_房子类.py
1,093
3.890625
4
class HouseItem: def __init__(self,name,area): self.name = name self.area = area def __str__(self): return "[%s] 占地%.2f"%(self.name,self.area) class House: def __init__(self,house_type,area): self.house_type = house_type self.area = area #剩...
857bdf4d392caf5e2dcb1cc5ceec2f43234b1532
Wangdaoshuai/python_learning
/python入门/05高级变量类型/hm_11_字典的其他操作.py
389
3.625
4
xiaoming_dict = {"name": "小明", "age": 18} #1、统计键值对数量 print(len(xiaoming_dict)) #2、合并字典 temp_dict = {"height": 175, "age":20} #注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对 xiaoming_dict.update(temp_dict) #3、清空字典 xiaoming_dict.clear() print(xiaoming_dict)
9b15553096bc04bc117774810b128fdaeffa8e26
Wangdaoshuai/python_learning
/python入门/03循环/hm_03_偶数求和.py
266
3.65625
4
# 0. 最终结果 result = 0 # 1. 计数器 i = 0 # 2. 开始循环 while i <= 100: # 判断偶数 if i % 2 == 0: print(i) result += i # 处理计数器 i += 1 print("0~100之间偶数求和结果 = %d" % result)
93d5403bbe0bbe8db0dc1ccd36593323c2917c1b
Wangdaoshuai/python_learning
/python入门/05高级变量类型/hm_13_字典的应用场景.py
432
3.53125
4
# 使用 多个键值对,存储 描述一个 物体 的相关信息 —— 描述更复杂的数据信息 # 将 多个字典 放在 一个列表 中,再进行遍历,在循环体内部针对每一个字典进行 相同的处理 card_list = [ {"name": "小明", "age": 18, "phone":"1212"}, {"name": "李四", "age": 18, "phone": "121442"} ] for card_info in card_list: print(card_info)
111874672c5451e9c5159da88710253da4e8092d
thedudetechnologies/hangman
/hangmanbyme.py
4,260
4.09375
4
import random import string import more_itertools as mit import pdb WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loa...
84804b724600060beedf1fa598b53f238940594b
365sec/texam
/lsm/20190329/exam_1_7.py
820
3.71875
4
# 7.水果出售记录 # ### Description # 某水果店简单地把每天销售的水果记录在一个列表中,你能帮忙店老板统计出每个水果卖出了多少,并从多到少排个序吗? # ### Specification # 输入为一个字符串列表,每项为一个水果的名字。 # 输出为一个列表,每一项为一个二元组表示水果和卖出数量,列表需要按照水果的卖出数量从多到少排序,如果数量相同就按照水果名称 # 在列表中的先后顺序排列。 # ### Sample Input # ``` # ['apple','banana','cherry','pineapple','banana'] # ``` # ### Sample Output # ``` # [...
2bd79c65fff75f90931dc7102dd4ee853c53d68a
365sec/texam
/llh329/20190329/2-判断素数.py
335
3.609375
4
import sys from itertools import count def isPrime(n): if n <= 1: return False for i in count(2): if i * i > n: return True if n % i == 0: return False try: for line in sys.stdin: a=int(line) print(isPrime(a)) except EOFEr...
5f7f108a2d20f7f342fa95a3769e46c345bdf282
cjoverbay/cracking-the-code-interview-solutions
/python/solution/chapter_01_arrays_and_strings/problem_1_2_check_permutation.py
799
3.859375
4
""" Problem: 1.2 Given two strings, write a method to decide if one is a permutation of the other """ # Time complexity: O(len(s1) + len(s2)) # Space complexity: O(len(s1) + len(s2)) or O(1) if fixed char set def is_permutation(s1, s2): """ Returns a boolean which is True if each element in ...
d56969b05ab1673ebae52b003332e6f53e4003dd
CaosMx/100-Python-Exercises
/011.py
606
4.28125
4
""" Create a script that generates and prints a list of numbers from 1 to 20. Please do not create the list manually. """ x = range(1,21) print(list(x)) # Create a script that generates and prints a list of numbers from 1 to 20. Please do not create the list manually. # 1 Punto # El truco es castear el resultado co...
058da8ba584bd1510b197f919c615e6923e9dc05
CaosMx/100-Python-Exercises
/010.py
706
3.96875
4
""" Exercise 10 - Sequence Item Picking Question: Complete the script so that it prints out a list slice containing letters a, c, e, g, and i. letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] Expected output: ['a', 'c', 'e', 'g', 'i'] """ letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i",...
bee12643fb9c7979b52d053d7c3ac2946c26d765
NiraliSupe/Sample-Python-Programs
/Sqlite3/Database.py
1,660
4.8125
5
''' Program created to learn sqlite3 ''' import sqlite3 class Database: def __init__(self): self.conn = sqlite3.connect('UserInfo.db') self.cur = self.conn.cursor() print("success") def createTable(self): table_exists = 'SELECT name FROM sqlite_master WHERE type="table" AND name="USERS"' sql = 'CREAT...
d0493185c1c5605bf508122a4b602b73660aa8fb
hold-n/stego
/utils.py
1,989
3.59375
4
from Crypto.Hash import SHA256 as sha from Crypto.Cipher import AES as aes # can be any valid aes key size: 16, 24, 32 _AES_KEY_SIZE = 16 def bits_to_str(bits): result = bytearray() for byte_num in range(len(bits)/8): byte_digits = bits[byte_num*8:(byte_num+1)*8] result.append(int(''.join(st...
f08145581e1b931b91255434c0d05aaeca711323
abruceme/MNISTNeuralNetworkDemo
/NeuralNetwork3.py
10,133
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 18 09:31:40 2020 @author: queek """ # ============================================================================= # 1. Split the dataset into batches # 2. Initialize weights and bias # 3. Select one batch of data​ ​and calculate forward pass​ - # f...
bfb4c23e85d31db4cb1235a46f33114cb7f497d7
ferdinandb/PSS_Learntools
/learntools/python1/pandas1.py
8,784
3.75
4
from learntools.core import * import pandas as pd import numpy as np investments = pd.DataFrame(0, index=['Anna', 'Tim', 'Kim', 'Jordan'], columns=['AAPL', 'MSFT', 'GOOGL']) investments2 = investments.copy() investments2['GOOGL'] = 4 investments3 = investments2.copy() investments3.loc['Kim'] = 8 investments4 = invest...
07f2be3230a3ff4ecfcda0a4de209d913e5c38b3
cheungis/simple-tic-tac-toe
/simpleTTT.py
3,760
3.96875
4
class TicTacToe: def __init__(self): # "board" is a list of 10 strings representing the board (ignore index 0) self.board = [" "]*10 self.board[0]="#" def drawBoard(self): # This method prints out the board with current plays adjacent to a board with index. ...
f8dbd9bd397ce93b6b3787d70c40229587b03d15
liulehui/LintcodeSolution
/lintcode algo ladder/159. Find Minimum in Rotated Sorted Array.py
519
3.78125
4
# coding:utf-8 def findMin(nums): # write your code here start = 0 end = len(nums) - 1 target = nums[end] while start + 1 < end: mid = start + (end - start) // 2 if nums[mid] < target: end = mid el...
a0a93f0d8a4bb9a1b32fc75a75f71f95e32117a9
liulehui/LintcodeSolution
/lintcode algo ladder/577. Merge K Sorted Interval Lists.py
1,307
3.90625
4
# coding:utf-8 """ Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ # Solution 1 min heap from heapq import heappush,heappop class Solution: """ @param intervals: the given k sorted interval lists @return: the new sort...
744233c670fabebfd8029776e279ff63d42e72df
liulehui/LintcodeSolution
/leetcode/Tree/230. Kth Smallest Element in a BST.py
924
3.703125
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 kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int ...
2d356e31e44c72b6c98610caad47c0753f4b0dfd
liulehui/LintcodeSolution
/lintcode algo ladder/34. N-Queens II.py
902
3.65625
4
class Solution: """ @param n: The number of queens. @return: The total number of distinct solutions. """ def totalNQueens(self, n): # write your code here if n <= 0: return 0 self.result = 0 cols = {} self.search(0,cols,n) ...
cacc2f38e13b6a38c2972783c5d5bc39f321d6ef
liulehui/LintcodeSolution
/lintcode algo ladder/130. Heapify.py
447
3.59375
4
# coding:utf-8 class Solution: """ @param: A: Given an integer array @return: nothing """ def heapify(self, A): # write your code here for i in range(len(A)): self.siftup(A,i) def siftup(self,A,k): while k!=0: father = int((k-1)/2) ...
7a3cd0d036ef24eb1d7bf37be06300b35bb5550b
liulehui/LintcodeSolution
/lintcode algo ladder/480. Binary Tree Paths.py
1,353
3.921875
4
class Solution: """ @param root: the root of the binary tree @return: all root-to-leaf paths """ def binaryTreePaths(self, root): # write your code here result = [] if not root: return result path = [] self.helper(root,...
62d297a72bdfcd3e88de8095c42b6990ed28d7e7
liulehui/LintcodeSolution
/leetcode/DFS/44. Wildcard Matching.py
1,026
3.609375
4
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ dp = {} # [[False for _ in range(len(s)) for _ in range(len(p))] return self.helper(s,0,p,0,dp) # search if s start from i and p start from j match...
3148fd91ae46b92488aaed60bb205d43d3bf346c
liulehui/LintcodeSolution
/lintcode algo ladder/68. Binary Tree Postorder Traversal.py
1,734
3.84375
4
# coding:utf-8 """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ # 这题有点绕,看答案有人说可以用morris算法 # 这里用的是用一个prev记录上一次访问过的点,然后看栈顶的node,如果有左儿子,就push进栈 # 这样一路push可以找到最左边的那个node,只要满足当前这个点prev是自己,且上个访问过的节点不是自己的 # 左儿子,那就可以append到result里,如果是...
f275518b834b7527ec57e1ee8adf2cedc85fce3f
liulehui/LintcodeSolution
/leetcode/Tree/1008. Construct Binary Search Tree from Preorder Traversal.py
751
3.5
4
class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if not preorder or len(preorder) == 0: return None self.preorder = preorder self.index = 0 self.n = len(preorder) return...
1f6b0cca54bdca75ad184f9d159427e0d1797504
liulehui/LintcodeSolution
/leetcode/Tree/897. Increasing Order Search Tree.py
914
3.859375
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 increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ if n...
7f79ce296f926526d25fb20b262432f660288858
liulehui/LintcodeSolution
/leetcode/Tree/124. Binary Tree Maximum Path Sum.py
2,004
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Result Type的思想,返回两个值 # 以root为节点的maxSum 和 从这个root出发的最长pathSum # maxSum 有两种,一种是不经过root的左子树的maxSum或右子树的maxSum # 另一种是经过root, 左边最大 + root + 右边最大。 # rec...
e54b29af4b636fa822a4915dbe5180cffb6dc12b
aabeshov/PP2
/String3.py
305
4.28125
4
b = "Hello, World!" print(b[2:5]) # show symbold on the 2th 3th 4th positions a = "Hello, World!" print(b[:5]) # show symbols til the 5th position b = "Hello, World!" print(b[2:]) # show symbold from 2th position til the end b = "Hello, World!" # Its the same but it starts from the ending print(b[-5:-2])
f4f7f3c6a38dfa054dc61982a46b5a15c4e9952d
aabeshov/PP2
/Syntax.py
172
4
4
a = input("Put number in a:") b = input("Put number in b:") if a > b: print("A is more than b and equals " + a) if b > a: print("B is more than a and equals " + b)
5cf489efa78e85955f10655cb85b2c8a6eb63b93
logashin0403/Russian--game_Viselica
/Виселица.py
2,535
3.625
4
import random vocabulary = ["поезд","машина","самолет","корабль","вертолет", "кактус","хризантема","дерево","тюльпан","смородина", "телефон","компьютер","телевизор","микроволновка","клавиатура",] word = random.choice(vocabulary) len_w = len(word) len_w = len_w - 1 HP = 10 s = word...
b3ff39263be9bfd4912ee5da8009f5be306418ee
joseph704/study-code-test
/정렬/baekjoon2750.py
109
3.609375
4
a = int(input()) list = [] for i in range(a): list.append(int(input())) list.sort() for j in list: print(j)
283b5e71cb7592434d122d9c68c849991a1facaa
muzuoan/demo
/task1/task1.py
2,193
3.671875
4
#!/usr/bin/env python #_*_coding:utf-8_*_ #authory:luca import getpass exit_flag = False have_flag = False while exit_flag is not True: file = open('userinfo.txt', 'r+') db_info = file.readlines() db_dic = dict() username = input("Please input your account: ") # passwd=getpass.getpass("Please in...
c3b8228b0894f054f5153931fa943fd65845906d
DimitarYordanov17/Chess
/Rook.py
427
3.5625
4
from Figure import Figure class Rook(Figure): def __init__(self, y, x): super().__init__(y, x) self.y = y self.x = x horizontal_coordinates = [(self.y, x) for x in range(8) if x != self.x] vertical_coordinates = [(y, self.x) for y in range(8) if y != self.y] self.co...
ef8947ca8c92178a85dc64a0abd92618af979428
Taisiamouse/PyGameStart
/lesson2/loops.py
453
3.859375
4
for index in range(10): print(index) #indexes 0 1 2 3 symbols = ['a', 'b', 'c', 'd' ] print(symbols[0]) # a print(symbols[3]) # d # for index in symbols: # print(index) number = 20 # while number > 0: # print(number) # number -= 1 while True: age = int(input('Enter your age: ')) prin...
869fcd4951ae7337167bb37ad04104b701ad4a7e
sulenn/leetcode_python
/BFS/cousinsInBinaryTree/Solution.py
2,179
3.828125
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): # official answer def isCousins(self, root, x, y): """ :type root: TreeNode :type x: int ...
8757b2b574cb78785d804f2b2834e75ea70fc458
sulenn/leetcode_python
/DFS/binaryTreePaths/Solution.py
590
3.53125
4
class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ if not root: return [] if not root.left and not root.right: return [str(root.val)] allPathList = [] if root.left: ...
34941f8d19374a9dc5ed573448795ddc6e6c39cb
sulenn/leetcode_python
/BFS/binaryTreeLevelOrderTraversal2/Solution.py
939
3.75
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 levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
90a6917da0d09dc6a2f3aac1b9181dae3bacf45f
mobishift2011/My-100-Days-Of-ML
/2/code.py
866
3.875
4
# 1: 数据预处理 from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import numpy as np """简单线性回归""" import pandas as pd import matplotlib.pyplot as plt import os file_path = os.path.join(os.path.dirname(__file__), 'studentscores.csv') dataset = pd.read_csv(file_path) x = d...
ce81f083a5ad7911810caf4ac51c87ae527e162b
battyone/python-opencv2
/Vortrag/circle.py
268
3.765625
4
import numpy as np import cv2 # Create a black image img = np.zeros((512,512,3), np.uint8) # Draw a red closed circle cv2.circle(img,(200,200), 40, (0,0,255), -1) cv2.circle(img,(300,300), 40, (255,0,255), 1) #Display the image cv2.imshow("img",img) cv2.waitKey(0)
96e85918759d34a2d815f7adc4f90a44b68ca4ec
rojcewiczj/Javascript-Python-practice
/Python-Practice/graph_demo.py
1,003
3.625
4
array = [] for x in range(21): array.append([0] * 20) print(array) connections = {} for x in range(len(array)): for y in range(len(array[x])+ 1): connections[f"{x},{y}"] = [] if x + 1 < 21: connections[f"{x},{y}"].append([x + 1, y]) if x - 1 > 0: ...
f64282aa00334a0bb823efe766c6cbb7fe8b7f3c
rojcewiczj/Javascript-Python-practice
/Python-Practice/AlgoExpert3/AlgoExpert3/15second.py
247
3.9375
4
def binarySearch(array, target): left = 0 right = len(array) -1 while (left <= right): mid = (left + right) // 2 if array[mid] == target: return mid if target > array[mid]: left = mid + 1 else: right = mid -1 return -1
a2d04e3e6daf1ee1168380928a28e18a94ffbc0b
rojcewiczj/Javascript-Python-practice
/Python-Practice/Teams.py
374
3.6875
4
def tournamentWinner(competitions, results): teams = {} res = {0: 1, 1: 0} winning_score = 0 winner = "" for i in range(0, len( results)): team = competitions[i][res[results[i]]] if team not in teams: teams[team] = 3 else: teams[team] += 3 if teams[team] > winning_score: winning_sc...
6201b1311be874a7dd0fa5c41d9b5722d0d14e49
rojcewiczj/Javascript-Python-practice
/Python-Practice/minimum_swaps.py
500
3.546875
4
def minimumSwaps(arr): inc = 0 count = 0 while inc < len(arr): if arr[inc] > inc + 1: first_place = arr[inc] second_place = arr[first_place - 1] print(first_place, second_place) arr[inc] = second_place arr[first_place - 1] = first_place ...
64c2a87d7e11c7b5a097feb609cb293626690133
rojcewiczj/Javascript-Python-practice
/Python-Practice/acode_break.py
597
4.21875
4
code = "asoidjfiej;akfgnrgjwalkaslkdjhfaasdfj;asdkjf;gforwarddhjfajkhfthendfijaifgturndksoejkgorightsdfupsdfasdfgg" words= ["walk", "forward", "then", "turn", "right"] # function for finding a message consisting of given words hidden in a jumbled string def find_message(code, words): inc = 0 dictionary = {} ...
f575ad5f98a3d8df9aafd9df36a4865e94efe6be
rojcewiczj/Javascript-Python-practice
/Python-Practice/TwoStrings.py
496
3.75
4
def twoStrings(s1, s2): dictionary = {"total": 0} for element in s1: if element in dictionary: dictionary[element] +=1 else: dictionary[element] = 1 dictionary["total"] += 1 current = dictionary["total"] for element in s2: if element in ...
637aa68d0db1bd32ff3b1d4911f6bd6d7e55196d
rojcewiczj/Javascript-Python-practice
/Python-Practice/AlgoExpertThreeSum.py
453
4.09375
4
def threeNumberSum(array, targetSum): output_array = [] array.sort() for i in range(0, len(array)- 2): left = i + 1 right = len(array) -1 while left < right: if(array[i] + array[left] + array[right]) == targetSum: output_array.append([array[i], array[left], array[right]]) left += 1 right -...
9d4f6748021f39b27dda48bd77b10a956470fd07
rojcewiczj/Javascript-Python-practice
/frequency_dict.py
1,199
3.53125
4
import math # nums = [1,1,2,1] # def find_single(nums): # my_dict = {} # for num in nums: # if my_dict.__contains__(num): # my_dict[num] += 1 # else: # my_dict[num] = 1 # for num in my_dict: # if my_dict[num] == 1: # return num # r...
53d0b52dffe445ae7f6e74167d811ac9f91b1b8e
rojcewiczj/Javascript-Python-practice
/Python-Practice/AlgoExpertHard3/31.py
1,583
3.65625
4
# This is an input class. Do not edit. class BinaryTree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def findNodesDistanceK(tree, target, k): nodesToParents = {} populateNodesToParents(tree, nodesToParents) targetNode ...
c9139624f520c86349e1c02351193e7dc669c8cb
rojcewiczj/Javascript-Python-practice
/Python-Practice/frogs.py
586
3.6875
4
array = [7,5,9,2,9] def jump(arr): dictionary = {} for index, num in enumerate(array): dictionary[num] = index print(dictionary) sorted_arr = [] for num in array: sorted_arr.append(num) sorted_arr.sort() print(sorted_arr) j = dictionary[sorted_arr[0]] k = dictionary...
468bcee7bee757fc2298c584f2ee3fb1b79e2791
rojcewiczj/Javascript-Python-practice
/Python-Practice/test_func.py
708
3.703125
4
string="whereeasttrendssouth" def seperate(string): dictionary = {} indexes = [0] inc = 0 sec_inc = 1 new_string = [] while(sec_inc < len(string)): if string[inc] == string[sec_inc]: indexes.append(inc) inc += 1 sec_inc += 1 print(indexes) index...
8122af72edfabe1e746ceed2174bef892c1d8cbe
rojcewiczj/Javascript-Python-practice
/Python-Practice/Graphtraversal2.py
562
3.8125
4
connections = [[1,2],[2,3],[1,4],[1,2],[3,2]] def traverse(connections, start, end): queue = [[start]] visited = [] while queue: path = queue.pop(0) current_node = path[-1] visited.append(current_node) if current_node == end: return path for neighbor i...
5f3cba3eb2f4eb5a9a2a1e0b43da07ced05be26d
rojcewiczj/Javascript-Python-practice
/Python-Practice/daily_practice_7_28.py
1,752
3.65625
4
def freqQuery(queries): first_dict = {} sec_dict = {} def add(elem): if elem not in first_dict: first_dict[elem] = 1 sec_dict[first_dict[elem]] = 1 else: first_dict[elem] += 1 sec_dict[first_dict[elem]- 1] -= 1 if first_dict[elem...
803577a4cc1f133dc73c1bd1a88c8502bb7c00ae
rojcewiczj/Javascript-Python-practice
/Python-Practice/daily_practice_8_27.py
236
3.6875
4
array = [1,3,4,5,2,4,5,6,4] stack = [] towers = [] i = 0 while i < len(array): if len(stack) == 0: stack.append(i) else: while len(stack) > 0: check = stack[-1] if array[i] > stack[-1]
44c1a23e34148478664faa93edfa8779356ab096
rojcewiczj/Javascript-Python-practice
/Python-Practice/graphAndTaversal.py
712
3.75
4
class Graph: def __init__(self, adjList): self.adjList = adjList def Tarverse(self, start, end): queue = [[start]] visited = [] current = start while len(queue) and current != end: cur_path = queue.pop(0) current = cur_path[-1] ...
2d972b6d098c9e172a9f78bfffabc492ef6bfab8
cvhs-cs-2017/practice-exam-easy-as-pi
/MyEncrypt.py
848
3.578125
4
def removeChar(string, idx): return string[:idx] + string[idx+1:] def keyGen(): import random alphabet = 'abcdefghijklmnopqrstuvwxyz ' key = "" for i in range(len(alphabet)): ch = random.randint(0,26-i) key += alphabet[ch] alphabet = removeChar(alphabet,ch) return key Ci...
8ec3f21223372231a6ea99bf68525e05551e1f3d
simon-mo/booklist_app
/amazom_scrap_review.py
1,684
3.5625
4
from bs4 import BeautifulSoup import requests """This is not happening becuase amazon blocked srapping""" def search_page(name, n=0): """Input a search title, return a url""" name = ''.join([char if char != ' ' else '%20' for char in str(name)]) search_url ='https://www.amazon.com/s/ref=nb_sb_noss?url=se...
2623ed3e04574ac0b3038d270688278ec33b06bf
11kim/programming
/hw2/2.py
120
3.78125
4
print("variant:3") print("Input word") s = input() s = s[::-1] s = s.replace("з", "") s = s.replace("я", "") print(s)
c6c938a2cdf448061dfc58fd1bda129f35064d44
11kim/programming
/bonus/bonus-6.py
638
3.96875
4
height = float(input()) / 100 weight = float(input()) i = weight / (height * height) if i <= 16: mean = "Выраженный дефицит массы тела" elif i <= 18.5: mean = "Недостаточная (дефицит) масса тела" elif i <= 24.99: mean = "Норма" elif i <= 30: mean = "Избыточная масса тела (предожирение)" elif i <= 35: ...
c78c0093aa272df735ab1f9ca11e94ff8618ead5
drjordy66/LeetCode
/Algorithms/0016_3Sum_Closest.py
676
3.5625
4
class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ closest = nums[0] + nums[1] + nums[2] nums = sorted(nums) for i in range(len(nums)): l = i + 1 r = len(nums) - ...
da00fa93ac62b4e07c0d77e815051f1b8655cd6f
mgmikez/gmq450
/APP_Donnees_liees/FORMULAIRE/database_setup.py
327
4.09375
4
import sqlite3 # Open a connection to the database conn = sqlite3.connect('data.db') c = conn.cursor() # Execute a SELECT query to fetch all rows from the `parcs` table c.execute("SELECT * FROM parcs") rows = c.fetchall() # Print the rows for row in rows: print(row) # Close the connection conn.cl...
bba131fed1711edf4785e028be5adf9d9e59bea2
nedbat/adventofcode2017
/day19.py
1,430
3.625
4
""" http://adventofcode.com/2017/day/19 """ TEST_INPUT = """\ | | +--+ A | C F---|----E|--+ | | | D +B-+ +--+ """ def turns(posx, posy, dx, dy): if dx == 0: yield posx + 1, posy, 1, 0 yield posx - 1, posy, -1, 0 else: yield posx, po...
9530c1fe533bec823fc52e115ae9ffa17165d1f9
nedbat/adventofcode2017
/day08.py
1,470
3.609375
4
""" http://adventofcode.com/2017/day/8 """ import collections import operator import re TEST_DATA = """\ b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10 """ CONDITIONS = { '<': operator.__lt__, '<=': operator.__le__, '>': operator.__gt__, '>=': operator.__ge__, '==': o...
4e9c6a42579e4295977b7f37fc130565faba0b10
nedbat/adventofcode2017
/day07.py
4,442
3.59375
4
""" http://adventofcode.com/2017/day/7 """ import collections import re import pytest TEST = """\ pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57) """ de...
dd04361b3df2dd5d1380d8fdb1ed67e1bb898d6a
rolandoquiroz/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/5-filter_cities.py
1,175
3.5625
4
#!/usr/bin/python3 """ Script that takes in the name of a state as an argument and lists all cities of that state, using the database hbtn_0e_4_usa """ if __name__ == "__main__": """ This won't be run when imported """ from sys import argv import MySQLdb """ Making a Connection """ db = MySQLdb.co...
3664d30966db44495bf24bc707f34715795552b6
rolandoquiroz/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
491
4.46875
4
#!/usr/bin/python3 """ This module contains a function that appends a string at the end of a text file (UTF8) and returns the number of characters added. """ def append_write(filename="", text=""): """ append_write- Appends a string at the end of a text file (UTF8). Args: filename(str): filename...
2b781a636d192a4cd52fc0ecec2a722490d45373
rolandoquiroz/holbertonschool-higher_level_programming
/0x0A-python-inheritance/7-base_geometry.py
606
3.609375
4
#!/usr/bin/python3 """ This module contains a class with public instance and Raises exception when required """ class BaseGeometry: """ Class BaseGeometry """ def area(self): """ raises not implemented exception """ raise Exception("area() is not implemented") def integer_validator(self,...
c0ea0bfe2833840c17ff9ce853ab4e3a248a3a2a
rolandoquiroz/holbertonschool-higher_level_programming
/0x06-python-classes/1-square.py
275
3.828125
4
#!/usr/bin/python3 class Square: """Defines a class square """ def __init__(self, size): """Square object attributes initialization. Args: size: Square size. Returns: None. """ self.__size = size