blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7c8a42e7beaaaab63cb8804c296de890bc506e2f
kodomotachi/Python
/Bai_17_dot_2.py
322
3.578125
4
a = int(input('Nhap so thu nhat: ')) b = int(input('Nhap so thu hai: ')) m = a n = b while a != b: if a > b: a -= b else: b -= a if a == 1: print("{0} va {1} la hai so nguyen to cung nhau.".format(m, n)) else: print("{0} va {1} la hai so nguyen to khong cung nhau".format(m, n...
ca22de16db4235e68adfe57ab75f2a002c9b9a86
virensachdev786/my_python_codes
/OOPS4.py
829
3.96875
4
class Employee(object): def __init__(self,name,salary): self.name = name self.salary = salary def display(self): print("employe name is :{0}".format(self.name)) print("employee salary is :{0}".format(self.salary)) def main(): myobj = [] name = [] salary = list() ...
e1af2c04c92dfe762fe8e68c168b512c5d132791
SothothLL/LeetCode_Solution
/链表/206_Reverse Linked List .py
570
3.828125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: stack = [None] while head: stack.append(head) head = head.next re...
4727d20d7d031354d3241cb3a96fd63b34d593b6
Avtandil-hub/test
/generator (1).py
909
4.0625
4
# Генераторы позволяют значительно упростить работу по конструированию итераторов. # В предыдущих примерах, для построения итератора и работы с ним, # мы создавали отдельный класс. Генератор – это функция, # которая будучи вызванной в функции next() возвращает следующий объект согласно алгоритму ее работы. # Вместо ...
1b2147a1cf9c13208bb1310e4c6328e626cc855e
avinashranjan1/Cardinality-Estimation
/Data Cleaning for IMDb dataset/Removing duplicates and copyOutputofPythonInCSV.py
383
3.765625
4
import pandas as pd import os df = pd.read_csv("/home/hp/Desktop/Thesis/sortedData/aka_title2.csv") df.sort_values("keyword", inplace = True) # dropping ALL duplicte values df.drop_duplicates(subset ="keyword", keep = False, inplace = True) #keyword- Column name print(df.to_string(index...
5b6c99aa27f6d2c4c7466dff79492c41882f8fda
BeahMarques/Workspace-Python
/Seção 3/exercicio26/app.py
310
4.21875
4
Categoria = int(input("Qual sua categoria: ")) if Categoria == 1: print("Voce escolheu a categoria BOLSA!") elif Categoria == 2: print("Voce escolheu a categoria TENIS!") elif Categoria == 3: print("Voce escolheu a categoria MOCHILA!") else: print("Essa categoria não foi encontrada")
2aac9de74c6494c831c70cec63b903a4d857e0a5
xljixieqiu/cookbook
/demo8.4.py
2,067
3.9375
4
#创建大量对象时节省内存的方法 #问题 #你的程序要床架大量(可能有上百万)的对象,导致占用很大内存 #解决 #对于主要是用来当成简单的数据结构的类而言,你可以通过给类添加__slots__竖向来极大的减少实例所占的内存。比如: class Date: __slots__=['year','month','day'] def __init__(self,year,month,day): self.year =year self.month=month self.day =day #当你定义__slots__后,python就会为实例使用一种更加紧凑的内部表示。 #实例通过一个很小的固定大小的数组来构建,而不是为每个实...
76f77ef6b67100f786111b0556b2651f03622bd4
Tathagat12/assignment
/assignment4/root.py
320
4
4
import math print("The quadratic equation i.e ax2 + bx + c = 0 ") a = int(input("Enter value for a")) b = int(input("Enter value for b")) c = int(input("Enter value for c")) print("the roots are:-") d=math.pow(b,2)-4*a*c res1=(-b+math.sqrt(d))/(2*a) res2=(-b-math.sqrt(d))/(2*a) print(res1) print(res2)
c63051e983999dc6a8cc6d8837042bc7591697b2
thaliadelgado/Programacion4Tarea1
/main.py
2,982
3.625
4
import sqlite3 con = sqlite3.connect("slang.db") cur = con.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS slang (palabra text UNIQUE, definicion text)''') def compruebasiexiste(palabra): p = cur.execute("""SELECT EXISTS (SELECT 1 FROM slang ...
c43850e9f8496bceea73b9f6ff1e35d275e043bc
CodeInDna/CodePython
/Intermediate/relational_database_23.py
4,309
4.21875
4
# Relational Database # Based on relational model of data # First described by Edgar "Ted" Codd # Relational Database Management Systems # SQLite # Mysql # Postgres # Creating a database engine in Python # SQLite database: Fast and simple # SQLAlchemy: Works with many Relational Databse Management Systems # We'll cre...
620557ca584dc5c2dbf00523b9ff6d62a6221687
Aasthaengg/IBMdataset
/Python_codes/p03486/s186587678.py
158
3.65625
4
s = input() t = input() s = ''.join(sorted(s)) t = ''.join(sorted(t, reverse=True)) if s>=t: print('No' , flush=True) else: print('Yes' , flush=True)
6d741a75f7c40257481e7d376d28d9268c7d06b7
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/141_2.py
1,047
4.28125
4
Python | Remove duplicate tuples from list of tuples Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. **Examples:** **Input :** [(1, 2), (5, 7), (3, 6), (1, 2)] **Output :** [(1, 2), (5, 7), (3, 6)] **Input :** [('...
be01687d9a08630ba8ccbcc172f802fbc6135383
CosmicTomato/ProjectEuler
/eul58.py
1,887
4.4375
4
#Spiral primes #Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. #37 36 35 34 33 32 31 #38 17 16 15 14 13 30 #39 18 5 4 3 12 29 #40 19 6 1 2 11 28 #41 20 7 8 9 10 27 #42 21 22 23 24 25 26 #43 44 45 46 47 48 49 #It is interesting to note that the...
b7f3eda47f8fb2150469a96e1799c971871ecd88
raahim007/string-manipulation-AS
/RemovingChars/removingchars.py
266
3.984375
4
finalStr = "" myStr = input("Enter String: ") myChar = input("Enter character to remove: ") for index in range(len(myStr)): nextChar = myStr[index:index+1] if nextChar != myChar: finalStr = finalStr + nextChar print("Final String is =", finalStr)
b2c83bd0089e37970f411814ca7df593f467bf40
madhavGSU/Data_Programming
/Assignment_1/chapter2_21.py
456
3.796875
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 14 18:37:45 2020 @author: Administrator """ import math; principal=eval(input("Give the principal amount")); intRate=0.05/12; # interest=principal*((1+(0.05)/12))**6; interest=0; total=principal; for i in range(6): total=principal+interest; interest=total*(1+intRate);...
25195f94c942383332a056c82318ffe1c45077d9
salpoe/code-guild-labs
/credit2.py
697
3.625
4
cc_num = input('Enter 16-digit credit card number:\n') cc_num = list(cc_num) print(cc_num) check_digit = cc_num[-1] new_cc1 = cc_num[:-1] print(new_cc1) new_cc1.reverse() print(new_cc1) new_cc2 = [] for num in range(len(new_cc1)): if num % 2 == 0: new_cc2.append(int(new_cc1[num])*2) else: ne...
e00ec80b9d3d431028259cf2cc7bba0ec2a9b317
lazyKT/REST-API
/lib/vdo_helper.py
2,039
3.71875
4
import os import youtube_dl # url_helper function helps to validate the url and remove the playlist information from url # : for example, if a user request a song from youtube playlist, only the song requested will be processed, # : removing playlist id from url. This is being done because of Youtube-dl feature. # : ...
9b06db392f6b98bb0fc220b4978cb0345486b3ad
turtelneck/Python-Projects
/text-based-game/nice-mean-game.py
3,013
4.21875
4
# # Python: 3.9.0 # # Author: Rhodri def start(nice=0,mean=0,name=""): # get user's name name = describe_game(name) nice,mean,name = nice_mean(nice,mean,name) def describe_game(name): """ check if this is a new game or not. If it is new, get the user's name. If it is not a...
4f45e839b658102c44e7ca566efa62f8c76aee8d
wonjongah/JAVA_Python_Cplusplus
/Python/chapter03 타입/ordchr.py
115
3.75
4
print(ord('a')) print(ord('A')) print(chr(98)) for c in range(ord('A'), ord('Z') + 1): print(chr(c), end = '')
4391c670dec0503a06a622aa811976dead1cec6f
wgkdata/learningpython
/exerciciospythonbrasil/EstruturaSequencial/04_Media.py
234
3.84375
4
n1 = int(input("Digite um numero: ")) n2 = int(input("Digite outro numero: ")) n3 = int(input("Digite outro numero: ")) n4 = int(input("Digite outro numero: ")) media = (n1 + n2 + n3 + n4) / 4 print(f"A média das notas é {media}")
16bf184ba81dd864840952d2795174324e32212a
jorgepdsML/DIGITAL-IMAGE-PROCESSING-PYTHON
/CLASE5_PYTHON_UMAKER/codigo1.py
455
3.9375
4
""" primer codigo de python clase 5 """ class persona(): #método de instancia def hablar(self,x): print("YO PUEDO HABLAR",x) def caminar(self): print("yo puedo caminar") #---INSTANCIANDO NUEVOS OBJETOS--------- #primera instancia o1=persona() #segunda instancia o2=persona() #...
359390b60bc41859d2c5a0de9e5d554f666835ae
jessica-lemes/exercicios-python
/Ex. 07 EstruturaDeRepeticao.py
280
3.984375
4
def maior_numero(): lista = [] contagem = 0 while contagem < 5: num = int(input("Informe um numero: ")) lista.append(num) contagem += 1 lista lista_ordenada = sorted(lista) return lista_ordenada[-1] print(maior_numero())
dd0d20f08ce4f40cca261c805552b2ace8aa71d6
Athi101/codeforces_sol
/133A.py
384
3.5625
4
a = str(input()) count = 0 m = 0 for i in range (len(a)): if a[i] == 'H' or a[i] == 'Q' or a[i] == '9': count += 1 m = 1 else: count = 0 if count > 1 or m == 1: print ("YES") else : print ("NO") # for loop can be avoided a = input() count = a.count("H") + a.count("Q") + a.cou...
6df89d550eb3a85acd1afbad541938e513726ccd
deepaksng29/computer-science-a2
/Worsheet Task/fishTask1.py
299
3.765625
4
def feed(state, size): size += 1 print('Fish fed') if size == 5: state = 'FISH' thisFishState = 'Fish' thisFishSize = 1 print(thisFishState, 'is of size', thisFishSize) while thisFishState != 'FISH': feed(thisFishState, thisFishSize) print('It is now a big', thisFishState)
22644506dae3b2e2155179b94d94650ee522c833
ailin546/pyxuexi
/7.字符串和常用数据结构/集合.py
447
3.546875
4
set1 = {1,2,3,3,3,2} print(set1) print("Length=",len(set1)) set2 = set(range(1,10)) set3 = set((1,2,3,3,2,1)) print(set2,set3) set4 = {num for num in range(1,100) if num % 3 ==0 or num % 5 ==0} print(set4) set1.add(4) set1.update([11,12]) set2.discard(5) set2.discard(11) if 4 in set2: set2.remove(4) print(set1,set2...
e6df31ebf1c76496198e81e5eb792ce6aaebf26e
zhuangsen/python-learn
/com/imooc/conditions.py
1,169
3.5
4
# -*- coding: utf-8 -*- # Python之if语句 # 缩进请严格按照Python的习惯写法:4个空格,不要使用Tab,更不要混合Tab和空格,否则很容易造成因为缩进引起的语法错误。 score = 75 if score >= 60: print('passed') # Python之 if-else score = 55 if score >= 60: print('passed') else: print('failed') # Python之 if-elif-else score = 85 if score >= 90: print('excellent') eli...
f9b659aa255bac28e91d506bda5cd97d5198df78
sumitsk/leetcode
/binary_search_tree/lowest_common_ancestor.py
1,738
3.796875
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 lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :t...
62d45f14bf54430b9dac046d42824d1fcdce3cd9
rainfd/leetcode
/python/138.Copy_List_with_Random_Pointer/copyListwithRandomPointer.py
1,161
3.75
4
# Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rt...
89c3017756755d30d169aa609026307fc10d8f61
eternalSeeker/pcc
/pcc/AST/bitwise_operators/bitwise_not.py
799
3.6875
4
from pcc.AST.unary_operator import UnaryOperator class BitwiseNot(UnaryOperator): def __init__(self, depth, operand): """Create a binary operator Args: depth (int): the depth in the tree operand (Expression): the operand """ super(BitwiseNot, self).__init__...
dbdf9c7227fa1b69324e0a670410df6624e1bd96
dlfosterii/python103-small
/n_to_m.py
351
4.28125
4
#Same as the previous problem, except you will prompt the user for the number to # start on and the number to end on. #setup start_num = int(input('Enter a number to begin with: ' )) end_num = int(input('Enter a numbert to end with: ')) num = start_num #code to add and print numbers to console while num <= end_num...
baec15c3865e289112598e833a63fdfbdc500a42
Kunal352000/python_adv
/day4.py
758
3.6875
4
class Person: def __init__(self,age): self.intialAge=age if self.intialAge<0: self.age=0 print("Age is not valid,setting age to 0.") else: self.age=self.intialAge def yearPasses(self): self.age=self.age+1 def a...
3b0506176f1a98011aa8401cbfdbec4e15ce4bb7
AndrewKh7/python_lessons
/python_les_1.2/les21.py
295
3.78125
4
# task 1 # s = 0 # while ...: # a=int(input()) # if not a: # break # s+=a # print(s) # task2 a = int(input()) b = int(input()) a1,b1 = a,b while a1 and b1: if a1>b1: a1 %= b1 else: b1 %= a1 if a1: print(a*b//a1) else : print(a*b//b1)
9f6cd83278ce677d82539866e15cb9b2d50384a0
isnakolah/codewars
/train/parity_outlier.py
883
4.0625
4
# def find_outlier(integers): # odd, even = [0, 0] # for i in range(len(integers)): # if integers[i] % 2 == 0: # even += 1 # else: # odd += 1 # if odd > even: # for i in range(len(integers)): # if integers[i] % 2 == 0: # return int...
2522dcdfb7bc8719ef21a6456e665e2ac6155438
makoshark/wordplay-cdsw-solutions
/solution_2.py
491
4.15625
4
import scrabble # What is the longest word that starts with a q? # This is the most common student solution, which prints the *first* occurence of # the longest word. See solution_2_advanced.py for more info. longest_so_far = '' # Store the longest word we've seen up to this point. for word in scrabble.wordlist: ...
5caf547804491930f49a925747dff8110a0d66dc
ilanaMelnik/PYTHON_PROJECTS
/Find_Total_exercise/find_total.py
3,869
3.9375
4
""" public class MovingTotal { /** * Adds/appends list of integers at the end of internal list. */ public void append(int[] list) { throw new UnsupportedOperationException("Waiting to be implemented."); } /** * Returns boolean representing if any three consecutive integers in th...
a70f494062e98c1fc5cb5d5c6b556feb02c7e297
rhubarbking/NicotineCalculator
/nicotineCalc/testing.py
278
3.6875
4
def GetAndPrint(): this = mustbeNumber() print ("Yay you got a number!"); print (this); def FetchNumbersOnly(): mustbeNumber = raw_input("Gimme a number ") if mustbeNumber == int or mustbeNumber == float: return mustbeNumber else: FetchNumbersOnly() GetAndPrint();
50894bed5b7fbfe2f78f353b33c4bf28f95c8c8f
m4rm0k/Python-Code-GitHUB
/neural_networks/perceptron.py
2,318
4.21875
4
""" Source: https://natureofcode.com/book/chapter-10-neural-networks/ """ import random class Perceptron: """ A perceptron is the simplest type of a neural network: A single node. Given two inputs x1 and x2, the preceptron outputs a value, depending on the weighting. """ def __init__(self, n...
46697d41d5510fed0f1786215123a9c6a1eaf11d
VarTony/Playground
/Python/Just Python/LevelUp/Level_1/exercise1.py
208
3.546875
4
# Рассчитайте площадь поверхности сферы по формуле: S=4πR2. import math def saots(r): result=(4 * math.pi) * (r * 2) print(result) return result saots(15);
639a450e69cf727c769bf051d43525341041bd3e
chunmusic/Data-Science-Training-Camp-I
/Course I/Ex3/Exercise 3.5.py
878
3.703125
4
# Exercise 3.5 # 1 import pandas as pd df = pd.read_csv('homes.csv') import imp from sklearn.preprocessing import scale sell_variable = df['Sell'].values sell_scale = scale(sell_variable) print("SALE") print(sell_scale) tax_variable = df['Taxes'].values tax_scale = scale(tax_variable) print("TAXES") print(tax_sca...
c69a416cde7d90658f7351858c4562bed8931a57
hxdone/tiny-utility
/correlation.py
1,293
3.640625
4
#!/user/bin/python # Written by hxdone, to calculate the correlation coefficient of two variables. # Usage: ./correlation.py FILENAME # Each line in FILENAME must be two numbers separated by '\t' import sys import string import math if __name__ == "__main__": if len(sys.argv) != 2: sys.stderr.write("Usag...
a832c7126689bff0aa5d51ba65d7c9c44633643e
heechul90/study-python-basic-2
/left_hand_coding/CheckiO_Elementary/Bigger_Price.py
334
3.5
4
### Bigger_Price def bigger_price(limit, data): return sorted(data, key= lambda x: x['price'], reverse = True)[:limit] limit = 2 data = [{'price': 138, 'name': 'wine'}, {'price': 25, 'name': 'milk'}, {'price': 10, 'name': 'bread'}, {'price': 15, 'name': 'meat'}] type(data) bigger_pric...
0da0b7f4d9217cc932659929a764398996d465cf
Eylrid/vector
/vector.py
6,266
3.578125
4
import math from numbers import Number class DimensionError(Exception): pass class Vector(tuple): def __new__(cls, components): if any([not isinstance(i, Number) for i in components]): raise TypeError('Vector components must be numbers') item = tuple.__new__(cls, components) ...
a06db6bd74e5b0391822b486347a3838c4c54485
Sreehari78/Turtle-Race
/main.py
2,042
4.125
4
from turtle import Turtle, Screen from random import randint def expand_color(character): color_dict = { 'r': "red", 'o': "orange", 'y': "yellow", 'g': "green", 'b': "blue", 'i': "indigo", 'v': "violet", } return color_dict[character] ...
8a323b61abfe7062ba1c9316d35689d1bf09b289
Jyin98/PythonHangman
/Hangman.py
12,460
3.671875
4
#Gibberish_Hangman.py # #Description: A game of gibberish hangman # #Programmed by: John Chan import random as ran; import turtle as stylus; import turtle as prompt; #Helper Functions def move_pen(xcoord=0, ycoord=0): stylus.penup(); stylus.setpos(xcoord, ycoord); stylus.pendown(); re...
25a65fe438a023b786a1842ce3a81f796fa3ce00
ph504/CompilerProject
/testpackage/tests/codegen/t006-preview-6.py
161
3.84375
4
def abs_mult(a, b): if a > b: c = a - b else: c = b - a return c * a * b a = int(input()) b = int(input()) print(abs_mult(a, b))
b8209485faaa8acd9df468ccfcf47fd550622c4c
evianyuji/the-self-taught-programmer
/6章/6-6.py
82
3.625
4
str = "A screaming comes across the sky." str = str.replace("s", "$") print(str)
6e2921fe32fb907dee43ac0071328d8dae0318ab
diogohxcx/PythonCemV
/desafio031.py
290
3.796875
4
km = float(input('Digite a quantidade de kilometros que será percorrido:')) if km <= 200: print('O valor da passagem será de: R${:.2f}'.format(km * 0.50)) else: print('O valor da passagem será de: R${:.2f} valor promocional para viagens maiores que 200km!'.format(km * 0.45))
871d469819eb6f6baebd0a49a1ec951b71549106
Irenegdp94/carreraTortuga02
/tortugaCircuito.py
1,364
3.734375
4
#carrera de tortugas import turtle import random class Circuito(): corredores = [] __posStartY = (-30,-10,10,30) __colorTurtle = ('red','blue','green','orange') def __init__(self,width,height): self.__screen = turtle.Screen() self.__screen.setup(width,height) self.__screen....
9f4dc4f2e3a5e38895dea13b366df914e775e936
LuckyNick007/tasks_for_IVAN
/2.2 Сумма соседей.py
1,456
3.71875
4
# Напишите программу, на вход которой подаётся список чисел одной строкой. # Программа должна для каждого элемента этого списка вывести сумму двух его соседей. # Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. # Например, если на вход по...
9dbcf09027b27225627257251d83929791d93ddf
pcmaestro/my_repository
/APUNTES/PYTHON/EJEMPLOS_FORMACION/basico16ejercicioCarreras/clases.py
337
3.703125
4
''' clases ''' class Caballo(): nombre = "" color = "" numero = 0 posicion = 0 #Esto es un constructor, que exige cosas cuando se instancie un objeto de la clase caballo def __init__(self, nombre, color, numero): self.nombre = nombre self.color = color self.numer...
89a08877406b66edec7e303b4b5ebdaf6d934541
brandoneng000/LeetCode
/easy/1431.py
592
3.65625
4
from typing import List class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: candy_kid = max(candies) for index in range(len(candies)): candies[index] = candies[index] + extraCandies >= candy_kid return candies def main(): ...
56c1e3dab9f97dbcaafa17f526c40b9af9790d24
jonghoonok/Algorithm_Study
/Array/practice2.py
299
3.859375
4
def powersum(arr): cnt = 0 for i in range(1, 1<<len(arr)): powersum = 0 for j in range(len(arr)): if i & 1<<j: powersum += arr[j] if powersum == 0: cnt +=1 return cnt arr = [-3, 3, -9, 6, 7 ,-6, 1, 5, 4, -2] print(powersum(arr))
6c63087c1e7025ff501e19e84be72d9bb8c60430
KarlYapBuller/Ncea-Level-1-Programming-01-Lucky-Unicorn-Karl-Yap
/08_round_looping_v2.py
1,666
4.1875
4
import random #set for testing purposes balance = 5 rounds_played = 0 #.lower is used just in case user types in exit code, 'xxx' in uppercase play_again = input("Press <Enter> to play").lower() while play_again == "": #Increase #rounds played rounds_played += 1 #Print number of rounds played print...
202ee1514c519d1bdca1c1f9c3fb549ee4fc4e58
SergiuPloscar/FundamentalsOfProgramming-Python-
/Lab2/Problem1Lab2.py
514
4.3125
4
print(" How many numbers are in the list ? ") n=int(input()) l=[] print(" Enter the numbers one by one, pressing enter after each number ") for i in range(n): l.append(int(input())) def product(l): ''' This function takes as argument the list of numbers introduced by the user and returns the product...
90a0f03c7e894bac98dbeab1faee896f266c2cfe
huseyingunes/algoritma_ve_programlamaya_giris
/7. hafta/3_ornek_fibonacci.py
531
3.609375
4
''' 3- 1 ve 1 değerlerinden başlayarak 1000 e kadar olan fibonacci dizisi elemanlarını ekrana yazdıran programı yazınız. Fibonacci dizisi, her sayının kendinden öncekiyle toplanması sonucu oluşan bir sayı dizisidir. Yani 1+1 = 2 2+1 = 3 3+2 = 5 5+3 = 8 ... 1, 1, 2, 3, 5, 8, 13, 21, 34, ... ''' ...
b2f50a8dfb90f76dd838221a1bb62330102759f0
RodrigoEC/Prog1-Questions
/unidade09/diagonais/diagonais.py
603
3.671875
4
# coding: utf-8 # Aluno: Rodrigo Eloy Cavalcanti # Matrícula: 118210111 # Diagonais def diagonais(matriz): lista_diagonal_principal = [] lista_diagonal_secundaria = [] for linha in range(len(matriz)): for coluna in range(len(matriz[linha])): numero = matriz[linha][coluna] i...
33cdf27d2ec2667c8079a2f4f170d856a240b141
gaurav-anthwal-ftechiz/python-mysql-cheatsheet
/starter.py
2,815
3.78125
4
import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "root", password = "password", database = "starter" ) mycursor = mydb.cursor() ########1. Create database mycursor.execute('CREATE DATABASE starter') ########2. Show all Databases mycursor.execute('SHOW DATABASES') f...
36de7ec53164a0aabff8c6df8bc9379e2ccffc7b
JudyH0pps/Algorithms-and-Problem-Solving
/Problemsolving/1194 달이 차오른다 가자/1194 달이 차오른다 가자.py
2,041
3.65625
4
# 1194 달이 차오른다 가자 #####입력 모드 # 0 : txt모드 , 1: 제출용 INPUTMODE = 0 if not INPUTMODE: f = open("input.txt", "r") input = lambda: f.readline().rstrip() else: import sys input = lambda: sys.stdin.readline().rstrip() ################################ from collections import deque # . 빈 칸, # 벽 이동불가, a~f 열쇠...
cf77a2198b2ee89bf1f3137a4600594535294458
SayemG/python-Winter-2018
/Python class Winter 2018/Python codes file/loops on list.py
349
4.125
4
for element in EmployeeNames: print(element) for i in range(0,len(EmployeeNames)): print(EmployeeNames[i]) for i in range(len(EmployeeNames)-1,-1,-1): print(EmployeeNames[i]) for i in range(-1, -1* len(EmployeeNames)-1,-1): print(EmployeeNames[i]) for element in EmployeeNames[::-...
43f470e34511d99b0d9a362fb0f195d634cc6e3f
erdembozdg/coding
/python/python-interview/easy/searching.py
1,576
3.796875
4
# Sequential Search def binary_search(arr, item): first = 0 last = len(arr) - 1 found = False while first <= last and not found: mid = int((first+last)/2) if arr[mid] == item: found = True else: if item < arr[mid]: last = mid -...
2f327fe2e91ba13b5c94d2bf29599af975df27a3
MuhammadNaeemAkhtar/RUST
/IoT/IoT/Exercises/OOP/Exercise_0.py
276
3.640625
4
class Calculator(object): def __init__ (self,brand): self.brand=brand def add(self,a,b): print(f"{a} + {b} = {a+b}") def sub(self,a,b): print(f"{a} - {b} = {a-b}") def mul(self,a,b): print(f"{a} * {b} = {a*b}") def div(self,a,b): print(f"{a} / {b} = {a/b:.3}")
c5577e82ad07e477e1420f2e8d767af61e546a47
cdjasonj/Leetcode-python
/括号生成.py
833
3.796875
4
""" 本质上是一个回溯 在解空间的每个节点有两种选择, 1,添加左括号 2,添加右括号 为了保证添加括号的有效性,在遍历解空间的时候 1的条件: 左边括号剩余数>0 2的条件:只有在左边括号剩余小于右边括号剩余的时候再添加 返回结果条件。 left = right = 0 """ class Solution: def generateParenthesis(self, n): if n == 0: return [] result = [] def backtrack(temp,left,right): if le...
f56a24d2262fedb8795a2aef22449cfe1d351a64
number09/atcoder
/ttpc2015-a.py
160
3.609375
4
s = input() mibun = s[2] if mibun == "B": print("Bachelor " + s[:2]) elif mibun == "M": print("Master " + s[:2]) else: print("Doctor " + s[:2])
f7a4ba1f379a0a71c9dd1f6c67ab79af82790265
msaffarm/InterviewPrep
/LeetCode/Tree/Easy-538-ConvertBSTtoGreaterTree.py
1,888
3.921875
4
# Given a Binary Search Tree (BST), convert it to a Greater Tree such # that every key of the original BST is changed to the original key # plus sum of all keys greater than the original key in BST. # Example: # Input: The root of a Binary Search Tree like this: # 5 # / \ # 2 ...
1c555d3c397b93d8929f1f3d32c733ad9362307a
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
/answers/Utkarsh Srivastava/Day 6/Question 1.py
371
3.65625
4
candies = input("Enter Candies ").split() max = 0 result = [0]*len(candies) extra = int(input("Enter extra candies ")) for i in range(len(candies)): candies[i] = int(candies[i]) if int(candies[i])>max: max = candies[i] for i in range(len(candies)): if(candies[i]+extra>=max): result[i] = True...
00f75fb7f67d6164aceebfadfe811b88036149de
itaknfp/FPB
/koding tugas 1 kel 4.py
280
3.53125
4
def FPB(a, b): if a > b: smaller = b else: smaller = a for i in range(1, smaller+1): if((a % i == 0) and (b % i == 0)): fpb = i return fpb no1 = 1000 no2 = 1250 print("FPB dari", no1,"dan", no2," =", FPB(no1, no2))
7df82b696520fa2e217be89d012a3569c59676e2
JustinTrombley96/cs-module-project-iterative-sorting
/src/space_complexity/space_complexity.py
2,297
4.03125
4
''' Determining time complexity: 1. Compute the big O of each line in isolation. 2. If something is in a loop, multiply its big O by the number of iterations of the loop 3. If two things happen sequentially, add the big Os. 4. Drop leading multiplicative constants from each big O. 5. From all the Big-Os that are added...
2f5d88995a7f4eb40219238f460500c3c5131411
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc014/A/4914523.py
79
3.625
4
a = int(input()) b = int(input()) if a==b: print(0) else: print(b-a%b)
3712cfdbcfd7a531d8c905839aa05677dae45371
FlorisHoogenboom/numpy-net
/numpynet/util.py
223
3.6875
4
import numpy as np def check_2d_array(input): if type(input) is not np.ndarray: raise TypeError('Input is not an array.') if input.ndim != 2: raise TypeError('Input is not of the right dimension.')
1901711946fbd7a57c690aaaf9fd84b4105e1a7c
nahuel-ianni/exercism
/python/triangle/triangle.py
398
3.59375
4
def equilateral(sides): return _guard_triangle_shape(sides) and len(set(sides)) == 1 def isosceles(sides): return _guard_triangle_shape(sides) and len(set(sides)) in (1, 2) def scalene(sides): return _guard_triangle_shape(sides) and len(set(sides)) == 3 def _guard_triangle_shape(sides): s, m, ...
df13daf7ea4d0ab2e8539931458d24b88073807c
chlos/exercises_in_futility
/leetcode/count_servers_that_communicate.py
840
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def countServers(self, grid): """ :type grid: List[List[int]] :rtype: int """ result = 0 server_count_lines = [0] * len(grid) server_count_cols = [0] * len(grid[0]) for line_n in ...
8097779868f909f56a5f7a9ccf760beaf188253c
phittawatch/6230401945-oop-labs
/Phittawat_6230401945-lab2/list_tuple.py
171
3.6875
4
tuple = [(1,), (2, 2), (3, 3, 3)] print(tuple[1][1]) b = [list(range(0, 10)), list(range(10, 20)), list(range(20, 30)), list(range(30, 40))] print(b[0][8:10])
e2f387cf76d36f6d0d05eef27f3b3038f8f7d6ed
adnansadar/Python-programs
/snakify-programs/Sets/colorCubes.py
1,332
4.21875
4
# #Alice and Bob like to play with colored cubes. Each child has its own set of cubes and each cube has a distinct color, but they want to know how many unique colors exist if they combine their block sets. #To determine this, the kids enumerated each distinct color with a random number from 0 to 108. At this point the...
67abe7804d12ebd3cddc2d7575e77b8a3b27c20b
gaebar/London-Academy-of-It
/exercise11to20/Exercise15_BodyMassIndex.py
555
3.984375
4
weight = float(input("Please enter your weight in (kg): ")) height = float(input("Now, enter your eight in (m): ")) BMI_result = weight / height ** 2 # rounded number to two decimals #BMI_rounded = round(BMI_result * 100)/100 print("\nYour BMI is: %.2f" % BMI_result) # %.2f, non ricordo cosa significa category = "...
fe40687a20a9566017065bfac0de89940933d6ad
GreegAV/GuessNum
/game.py
940
4.09375
4
print("Игра \"Угадай число!\"") print("Загадай любое число от 1 до 1000.") print("Программа будет предлагать варианты, числа.") print("Если задуманное число больше предложенного, то введи с клавиатуры знак >") print("Если задуманное число меньше предложенного, то введи с клавиатуры знак <") print("Если программа угадал...
fbbad212b4d9708e6ecf9cd75f508f1e2552c9f4
Hintful/py2048
/src/board.py
4,574
3.625
4
import random import numpy as np import sys from copy import deepcopy def board_identical(b1, b2): if len(b1) != len(b2) or len(b1[0]) != len(b2[0]): return False for i in range(len(b1)): for j in range(len(b1[i])): if b1[i][j] != b2[i][j]: return False return ...
5bc50ef8b58d89ea202f59fba8f93de862baae18
L1ch1v1L/wiki_botPy
/main.py
2,506
3.9375
4
import wikipedia as wiki global lang global title global page global choose russian_alphabet = ["а","б","в","г","д","е","ё","ж","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ч","ш","щ","ъ","ы","ь","э","ю","я"] english_alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q",...
919a2af7e69001f8e2a4cb0a275dbd7d6362aea0
yskang/AlgorithmPractice
/baekjoon/python/sort_word_1181.py
417
3.875
4
# https://www.acmicpc.net/problem/1181 import sys def print_words_in_order(words): prev = "" sw = sorted(words) sw2 = sorted(sw, key=len) for w in sw2: if w != prev: print(w) prev = w if __name__ == "__main__": N = int(input()) words = [] for i in...
a9e3c00a5e9a30ff2b000de7d0fe439fcf47d168
PaulSweeney89/Topic-03-Variables-State
/lab03.02-sub.py
204
4.21875
4
#simple program to calc the difference of 2 inputted numbers x = float(input("Enter value for x:")) y = float(input("Enter value for y:")) z = x - y print("The difference between", x, "&", y, "= ", z)
44783d70ca7097b1aae6df44acb252b45db810bf
Warbo/python-random-walks
/MoonlightForest.py
3,361
3.53125
4
import sys import time import multiprocessing try: import pygame except: print """This program needs PyGame installed. In Debian and Ubuntu, this is in the package "python-pygame".""" sys.exit() import random import math class Point: def __init__(self, position, colour, shift): self.position = position self....
be4b80a1466751194174fc38d4f6802cb24ffe54
Iamsdt/Problem-Solving
/problems/LeetCode/p124.py
950
3.890625
4
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Solution: # 1. use dfs # 2. take max from left and right value, if negative then make it zero # 3. now t...
bad3bedde9883b8c5024ad7c890d2afe4d3226ce
manishkumarsahgopsaheb/python-hub
/machine.py
2,178
3.890625
4
# import numpy # from scipy import stats # # finding of mean median and mode # speed = [99, 86, 87, 88, 86, 103, 87, 94, 78, 77, 85, 86] # # we can find the mean and median using numpy # x_mean = numpy.mean(speed) # x_median = numpy.median(speed) # # for finding mode we have to use scipy module # x_mode = stats...
31f5a45e28ccb77adff1f5f3761e9297a121f0cd
Keshav1506/competitive_programming
/Tree_and_BST/021_leetcode_P_366_FindLeavesOfBinaryTree/Solution.py
2,439
4.25
4
# # Time : O(N) [ We traverse all elements of the tree once so total time complexity is O(n) ] ; Space: O(1) # @tag : Tree and BST ; Recursion # @by : Shaikat Majumdar # @date: Aug 27, 2020 # ************************************************************************** # # LeetCode - Problem - 366: Find Leaves of Binary ...
e0584e2d48bc5c3a170f6f64c74ad9415c634d41
Edson-Padilha/bot_redes_sociais
/Whatsapp/Enviar_msg.py
1,914
3.640625
4
# Abra o cmd e de o comando pip install selenium # Fazer download do "Google Chrome Driver", navegador para automação # Ver versão do google que está sendo usada em seu computador # Acessar e baixar de acordo com sua versão Chrome https://chromedriver.chromium.org/downloads # Crie uma pasta na sua área de trabalho ou o...
e114e76f8b34de17add1120563a5df9d932b6f27
Oualidinx/HackerRank-challenges
/second lowest grade challange.py
1,248
3.84375
4
#second lowest grade challange def mth_smallest_value(array): index = 0 for index in range(0,len(array)-1): i = index+1 found = True while (found and i > 0): if array[i][1] < array[i-1][1]: temp = array[i] array[i] = array[i-1] ...
91b2e6c08eb35451b317ac93f798ec9cf3e794e8
aixiu/myPythonWork
/pythonABC/ls-22-异常处理实例.py
1,296
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # ''' # **** # * * # * * # **** # 0000000000000000000 # 0 0 # 0 0 # 0000000000000000000 # ''' def boxPrint(symbol, width, heigth): # 定义一个函数并设置三个参数为:输入的字符,宽度和高度 if len(symbol) != 1: # 如果字符字符数不为1,侧提示只能输入一个字符 ...
2dd86ffbef8636e4f804686fbb3b67326dfdd5ab
MalikMuneebAhmad/AIS
/Learning/Factorial_using _recursion_func.py
239
4
4
def tri_recursion(k): global result if(k >= 1): result = k * tri_recursion(k - 1) #recursion will happen in that step else: result = 1 return result print("\n\nRecursion Example Results") tri_recursion(6) print(result)
3fc8429799108902c199fc19dbfd17e3be049ed8
jacek-szymborski/zadania
/odd_even.py
259
3.671875
4
liczba = int(input("Podaj liczbę: " )) if liczba % 2 == 0 and liczba % 4 == 0: print("To jest liczba parzysta i podzielna przez 4") elif liczba % 2 == 0: print("To jest liczba parzysta") elif liczba % 2 != 0: print("To jest liczba nieparzysta")
4b6dfe93779be443d48a03e710e3c8148b18e108
chaeonee/Programmers
/level2/괄호변환.py
848
3.625
4
def isCorrect(word): if word[0] == ')': return False num = 1 for w in word[1:]: num = num + 1 if w == '(' else num - 1 if num < 0: return False return True def splitString(word): if word == '': return word num = 1 if word[0] == '('...
3fd8c49a2cf99560ddd09856f43fc87ea15f2a53
ramchinta/python
/bestTimeToBuyAndSellStock.py
731
3.828125
4
'''Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.''' class So...
4d77e83974d01f58f3147085c6d60307aa011746
YeoMinkyu/leetcode_top100
/20_Valid_Parentheses.py
655
3.765625
4
class Solution: def isValid(self, s: str) -> bool: if not s: return True open_list = [] answer = {'(': ')', '{': '}', '[': ']'} result = True if s[0] == ')' or s[0] == '}' or s[0] == ']': return False for ch in s: if ch == '(' or...
c04080351aeaefcdacfd3f589b1852902a651cb6
elitan/euler
/049/main.py
1,027
3.5625
4
#!/bin/py """ The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exh...
3275e3e99fb7dd69b7e684db295bf62c560a8fa7
JohnS-coder/Python-Challenges
/Assignment8_leapyears.py
315
4.21875
4
while True: year = int(input("Enter the year('0' to quit): ")) if year == 0 : break elif year%4 == 0 and year%100 != 0 : print(f"{year} --> is a leap year! ") elif year%400 == 0: print(f"{year} --> is a leap year! ") else: print(f"{year} --> is not a leap year!")
d0fcf0308f2cafbe431b9807611f3deda623acb6
kevinsantana/exercicios
/programacao_competitiva/codeforces/problemset/watermelon.py
89
3.875
4
entrada = int(input()) print("YES") if entrada % 2 == 0 and entrada != 2 else print("NO")
ff11f46e28f980230d1e249810173e4636e180b0
anilmaddu/Daily-Neural-Network-Practice-2
/Understanding_Concepts/Sparse/sparse-filtering/sparse_filtering.py
5,819
3.671875
4
"""Feature learning based on sparse filtering""" # Author: Jan Hendrik Metzen # License: BSD 3 clause import numpy as np from scipy.optimize import fmin_l_bfgs_b from sklearn.base import BaseEstimator class SparseFiltering(BaseEstimator): """Sparse filtering Unsupervised learning of features using the spar...
c2e3413953a15118fce39a7b88cbb5943c3f7581
gabrielmaialva33/uri-problems
/Python/uri_1036.py
304
3.6875
4
import math a, b, c = input().split(' ') a = float(a) b = float(b) c = float(c) x = (b ** 2 - 4 * a * c) if x < 0 or a <= 0: print('Impossivel calcular') else: d = math.sqrt(x) r1 = ((-b + d) / (2 * a)) r2 = ((-b - d) / (2 * a)) print('R1 = %0.5f' % r1) print('R2 = %0.5f' % r2)
53e7ea658179900374e8576a8c871dced69855f5
jtt-berkeley/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
346
4.1875
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): return [replace if element == search else element for element in my_list] # new_list = my_list[:] # for i in range(0, len(my_list)): # if new_list[i] == search: # new_list.pop(new_list[i]) # new_list.insert(i, replac...
c877ba1369c63d06d2a8023b86162a4c49600e02
hookeyplayer/exercise.io
/算法/413_arithmetic slices.py
889
3.546875
4
# 等差数列 # 至少3个元素,相邻元素之差相同 # A slice (P, Q) of A is called arithmetic if: # A[P], A[P + 1], ..., A[Q - 1], A[Q] is arithmetic,this means that P + 1 < Q from typing import List class Solution: def numberOfArithmeticSlices(self, A: List[int]) -> int: if len(A) < 3: return 0 dp = [0 for _ in range(len(A...
ffbc0a515d06a360e3d20262f0fd11d60db11924
Omarfos/Algorithms
/238.product-of-array-except-self.py
2,172
3.625
4
# # @lc app=leetcode id=238 lang=python3 # # [238] Product of Array Except Self # # https://leetcode.com/problems/product-of-array-except-self/description/ # # algorithms # Medium (59.53%) # Likes: 4664 # Dislikes: 404 # Total Accepted: 520.9K # Total Submissions: 874.7K # Testcase Example: '[1,2,3,4]' # # Given...
2c7480aa53e23ee234c2af68575cb72b9f6a3d19
sgzmb/python-modules
/datetime_practice.py
208
3.609375
4
from datetime import datetime, date, time print datetime.now() print datetime.today() print datetime.today().year print datetime.now().weekday() print date.today() print date.today().year print time.hour