blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f51dbf395282489f9e524eef5d0acdbf1a17e070
luoyanhan/Algorithm-and-data-structure
/Leetcode/medium/107.py
668
3.734375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrderBottom(self, root): if not root: return list() res = list() pre = [r...
347ba74160971ecb191e48a20887ae84c6cab87e
betalantz/CodingDojo_LearningProjects
/Python/Fundamentals/Scores_Grades.py
590
4.03125
4
def randScore(): import random randNum = random.randint(60,100) return randNum score = randScore() print score def assignGrade(score): if score >= 60 and score <= 69: grade = "D" elif score >= 70 and score <= 79: grade = "C" elif score >= 80 and score <= 89: grade = "B" ...
236d790e5588701c823af1d786527edd3e642c28
poppod/OCRtest02
/vvom.py
657
3.5
4
from tkinter import * import time import threading class ScaleValue: def __init__(self): self.value1 = None self.value2 = None def tkinter_loop(scale): root=Tk() s1 = Scale(root, from_=0, to=42, tickinterval=8, command=lambda v: setattr(scale, 'value1', v)) s1.set(19) s1.pack() ...
51f6ed5c90a875d42cc921a2941574040a90c927
IanCarreras/graphs
/projects/ancestor/ancestor.py
1,540
3.90625
4
# create directed graph of ancestors # iterate over the ancestor list # create child keys with a set of parent values # if child is already in the graph add parent to the set # search through the graph and return the earliest # ancestor of the starting node # get parent of starting node # ...
0827355b419a746dc5c9e6dca89ae14484ff2667
Simon220902/Coding-Pirates-Python-projekter
/RECAP/1_navn_ind_og_ud.py
333
3.75
4
"""navn = input("Skriv dit navn her: ") alder = int(input("Skriv din alder her: ")) højde = float(input("Skriv din højde her: ")) print("Goddag hr./fru:", navn) print("Du er", alder, "år gammel og er", højde, "meter høj.") """ navn = input("Skriv navn: ") print("HAHAHA HVAD ER DET FOR ET NAVN, man kan da ikke hedde"...
3e75d6da9724329cc2cbab45d9d3d9af5b7b6b77
scarint/usingpython
/22 python-rpg-game.py
2,487
3.78125
4
def showInstruction(): #print a main menu and the commands print("RPG Game") print("========") print("Commands:") print("'inventory'") print("'go [direction]'") print("'look'") print("'take [item]'") print("'place' [item]'") print("Note: no error checking") def showStatus(): ...
1a70417cb6e01114dbaa1f38c683299cbc7c0d45
utkarsh-max/tutorial
/BloodBank.py
335
3.546875
4
from tkinter import * root=Tk() window_height=root.winfo_screenheight() window_width=root.winfo_screenwidth() root.geometry("%dx%d"%(window_width,window_height)) def mainheading(): label=Label(root,text="Blood Bank Login Window",font=('Ariel',30,'bold'),padx=450,bg="green") label.grid(row=0,column=0) mainheadi...
380bffb2243b1bb2713dd349f986a2f5b0f59dfb
julioribeiiro/Programinhas
/Lista_Icaro_1_periodo/Questao 3.py
724
3.875
4
# -*- coding: utf-8 -*- """ Uma forma de avaliar se uma pessoa está acima do peso é através do calculo do índice IMC. Se o valor do IMC estiver acima de 25, significa que a pessoa está acima do peso. A fórmula é: IMC = Peso(Kg) / (Altura(m)*Altura(m)). Com base na altura e peso fornecido no console exiba...
44a9fd67bc056e19777792f001a5910a378714bc
AndresSern/holbertonschool-machine_learning-1
/pipeline/0x02-databases/30-all.py
300
3.578125
4
#!/usr/bin/env python3 """ function that lists all documents in a collection """ def list_all(mongo_collection): """ Args: -mongo_collection :{collection object} """ documents = [] for item in mongo_collection.find(): documents.append(item) return documents
c6e4b83794ae44ef3c9717acdda65e5d75b45dcd
Rythsman/My-python-exercise
/10.6-10.22/dayinlinxing.py
716
3.9375
4
#根据已经给出的一个菱形图案,用python方法完成一样效果的输出。 from sys import stdout for i in range(4): for j in range(3-i): stdout.write (' ') for k in range(2*i+1): stdout.write ('*') print ('\n') for i in range(3): for j in range(i+1): stdout.write(' ') for k in range(5-2*i): ...
60e57fad540ac2b6078a7d069278a23bb9e32658
paunovaeleonora/SoftUni-Python-Basics-2020
/While-Loop/greater_number.py
221
4.03125
4
import sys max_num = -sys.maxsize while True: number = input() if number != 'Stop': number = int(number) if number > max_num: max_num = number else: break print(max_num)
23c07d767ea049143459a68a73cf6bdc2d977913
brav97/Simple-grading-system
/gradin_sytem.py
2,658
3.96875
4
def read_test_scores(): print("ENTER STUDENT ID: ") id = int(input()) print("ENTER YOUR SCORES: ") exam = int(input()) print("ENTER OTHER SUBJECT SCORES: ") score1 = int(input()) score2 = int(input()) score3 = int(input()) score4 = int(input()) score5 = int(input()) score...
14de578a04d8c0f7555e92188327f1e9bf2f2c0f
Esamantha7/Girls_Who_Code
/binBubble.py
831
3.875
4
##FUNCTIONS def bubbleSort (lissy): for index in range(len(lissy)-1,0,-1): for index2 in range (index): if (lissy[index2]>lissy[index2+1]): num = lissy[index2] lissy[index2] = lissy[index2+1] lissy[index2+1] = num def binSearch(lissy,...
41e0e1472eea6f263b99abaeacfdea305b6d5685
cleyber/exercism
/leap/leap.py
195
3.890625
4
def is_leap_year(year): if(year %100 == 0 and year% 400 == 0): return True elif(year %100 == 0 or year% 400 == 0): return False elif(year%4 == 0): return True
bf19862ce0f25f107539196bda023362f5ca5fea
TDeVries/Deep-Learning-Rosetta-Stone
/linear_regression/linear_regression_keras.py
1,302
4.0625
4
''' A linear regression learning algorithm example using the Keras library. Author: Terrance DeVries Project: https://github.com/TDeVries/Deep-Learning-Rosetta-Stone ''' from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_regression from keras.laye...
9e3bfafdee57e713e78891516d49286558705221
dkarapetyan-zz/interview_prep
/leetcode/remove_element.py
933
4.09375
4
# Given an array and a value, remove all instances of that value in place and # return the new length. # # Do not allocate extra space for another array, you must do this in place # with constant memory. # # The order of elements can be changed. It doesn't matter what you leave # beyond the new length. # # Example: # ...
4f15a9044038fe67e28e3bacd456407b60edf17f
AmbujaAK/practice
/python/oearray.py
847
3.5
4
''' def fact(num): return num * fact(num-1) def cal(n,r): return fact(n)/(fact(n-r)*fact(r)) ''' def cal(dis): res = 0 while dis > 0: res = res + dis dis -= 2 return res print('Enter the size of array') sz = int(input()) print('Enter the elements of Array :') arr = [int(item) for item in input().split()] pr...
c4ce2c384e041b13c89f19c74605387504b54314
zitkat/ukoly_py_zs2018
/03_cykly/okobere.py
494
3.59375
4
""" Hraje hru oko bere """ from random import randint body = 0 while body <= 21: print("Máte {0} bodů, to je dobré".format(body)) pokracovat = input("Prejete si pokracovat [ano]/ne? ") if pokracovat != "ne": # dealer je neuprosny a kdyz chces prestat musis to rict! body += randint(2, 10) # jinak...
cb9cad553dac3115d6cb032ad841b7e452ddfbf3
t-eckert/ctci_solutions
/c16_moderate/q1_Number_Swapper.py
501
4
4
""" 16.1 Number Swapper: Write a function to swap a number in place. """ test_numberPairs = [ (2, 3), (1, 1), (362943.273415, 15115234283.9958300288593), (-3.14159, 3.14159), ] def swap_in_place(a, b): a = a - b b = a + b a = b - a return a, b def main(): for test_numberPair i...
1f02ab1ab148014931330b7f8e8f2e0bcc052de3
ewenbramble/euler_project
/p22.py
1,139
3.96875
4
# Project Euler # Problem 22 # Solution by Ewen Bramble # Name scores (alphabetic value of name multiplied by its sorted position in name list) # What is the total of the name scores in the given file (comma-separated names) def alpha_value(string): '''Takes a string and returns its alphabetic value''' value ...
4c9285118e32b8a0b9032286df776061aaf0200d
Dagiman007/Python-exercise
/Location.py
1,243
4
4
class Location: def __init__(self, row, column, maxValue): self.row = row self.column = column self.maxValue = maxValue def getRow(self): return self.row def getColumn(self): return self.column def getMaxValue(self): return self.maxValue ...
feedbf88435af6b186da9dcd85041587edcee515
DinakarBijili/Data-structures-and-Algorithms
/BINARY TREE/6.Inorder Tree Traversal – Iterative and Recursive.py
1,406
3.921875
4
""" Inorder Tree Traversal – Iterative and Recursive Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 output = 4 2 1 7 5 8 3 6 ...
24112b3795586c18087115fb80cab14fadd0b8fd
Localde/scripts-python
/ex8-conversor-de-medidas.py
131
3.703125
4
valor = float(input("Digite um valor: ")) print("Centimetros: {}".format(valor * 100)) print("Milimetros: {}".format(valor * 1000))
80bfbf993ff57a9ebf2f55294a4ab4b9f81058e5
siddharth-143/simple-python-program
/default_constructor.py
193
3.5625
4
class addition: def __init__(self): self.a=10 self.b=20 def add(self): self.c=self.a+self.b print('addition ;',self.c) a1=addition() a1.add()
f461875037598c165c7073012412150809fad96e
AdemHodzic/python-learning
/Day #26/averages.py
569
3.75
4
# We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum # of the average of each group. What is the largest score we can achieve? def solution(arr, length): results = [] for i in range(0, len(arr) - length): temp = arr[i:i+length] new_...
4ea5e02e99b9d4e783d7d8b5622a4ff76ea52bee
MeinSpaghett/C4T16
/Session 11/Part 8/Skill.py
2,147
4.09375
4
import random from random import randint Character = { "Name": "Light", "Age": 17, "Strength": 8, "Defense": 10, "HP": 100, "Backpack": ["Shield", "Bread Loaf"], "Gold": 100, "Level": 35, } skill_1 = { "Name": "Tackle", "Minimum Level": 10, "Damage": 5, "Hit Rate": 0.3, }...
ed2e26810cc9d68065b67efc73609819b5d167c9
Vituuuu/Fila---FLA
/fila.py
1,690
4.09375
4
import sys print (''' Simulador de fila - Tera 3 filas em uma fila sera de pessoas normais, na outra tera gestantes, e na ultima fileira tera idosos.''') tuto = input ('Voce deseja jogar? [S/N]').lower() if tuto == 'n': print ('Tchau!:)'), sys.exit() elif tuto == 's': prin...
d46f4187651abe94d7cca3a0ba580eee490e8727
thraddash/python_tut
/17_scripting_arguments/misc_example/my_name_is_slim_shady.py
725
3.921875
4
#!/usr/bin/env python # my_name_is_slim_shady.py # __name__ is a built-in variable which evaluates to the name of the current module # thus it can be used to check where the current script is being run on its own or being imported somwhere else print(__name__) class MyNameIsSlimShady(object): def say_my_name(s...
8349e46c1850d3475fce8989092a6024e4b9e203
nbeckman/dotcom
/war/software/recipeMaker.py
6,550
3.890625
4
# Recipe Maker # v1.0 # # Nels Beckman # # April 11, 2006 # # This is a simple GUI application for creating recipes in the RecipeML. # format. After going through the steps of adding ingredients and steps # of the directions, if you press output to file, a file browser will # open up that you can use to specify where t...
440939893eacfb61175eea8e60608de5f9581944
notesonartificialintelligence/07-01-20
/chapter_4/even_number.py
357
4.40625
4
#Gabriel Abraham #notesonartificialintelligence #printing out the value in a range, this time with a set increment even_numbers = list(range(2,11,2)) print(even_numbers) #A list will be created with value between 2 and 10. The third argument in range is the value of the increment to be followed. #The program will go ...
c23450fbd226ca7467c5b3a03a2f10a6e17db4ec
PRAVEEN-77491/Hacktoberfest_2021-1
/code/BMI-Calculator_WilliamJaber.py
1,313
4.3125
4
import sys print('\nWelcome to your BMI calculator!!\n' 'Please insert units expressed in centimeters, meters, and kilograms.') def main(): """Calculates your Body Mass Index (BMI) and classify according to the result.""" while True: bmi = calculate_BMI() if bmi < 18.5: print(f...
80e9900202dd93965416fb873ef8274b9e543045
gabriellaec/desoft-analise-exercicios
/backup/user_372/ch149_2020_04_13_20_35_11_963020.py
1,502
3.8125
4
def calcula_imposto_de_renda(x,y): x=int(input('Qual o seu salário bruto? ')) y=int(input('Quantos dependentes você possui? ')) while x>0: if x<=1045: aliquota=0.075 contribuicao=x*aliquota break elif x>1045 and x<=2089.60: aliquota=0.09 ...
7c293506d79338a40e7ee8d0fa3a9bfb0bf6f51e
darshan8850/assignment-2-Linear-Regression-using-Gradiant-descent
/q8_compare_time.py
1,264
3.5
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from metrics import * from linearRegression.linearRegression import LinearRegression from time import time for i in [20,40,60]: N=10000 P=i X=pd.DataFrame(np.random.randn(N,P)) y=pd.Series(np.random.rand(N)) model=LinearRegress...
8622f00ec7a68ff1515e9115f52027f7d48449d8
MikhailRyskin/test1
/test286_1.py
1,237
3.984375
4
from abc import abstractmethod, ABC class Transport(ABC): def __init__(self, color, speed): self.__color = color self.__speed = speed def __str__(self): return f'{self.__color} {self.__speed}' @property def color(self): return self.__color @color.setter def c...
1e9d68f603bd9395efae853f0bc117da8bcd47e7
Crazysniperr/Python
/stopwacth.py
451
3.96875
4
import time def time_convertor(diffrence_time): diffrence_time = (diffrence_time) miin = diffrence_time // 60 hour = miin // 60 sec = diffrence_time % 60 print(f'the time is {int(hour)}:{int(miin)}:{round(sec,2)}') input('press enter to start the stopwacth: ') start_time = time.time() input('pr...
d35aa19b91507e57984cac4114a6d2af65322df6
monicaihli/tenn-share_2019
/A_Getting_Data/A1_python_requests.py
3,871
3.890625
4
######################################################################################################################## # # Demonstrates different ways of using requests library to make an HTTP request and grab content from a web page # This is just like using your browser, only we can use Python instead! # To watc...
b84a539a0a1e80abc66f3d5cff12b5206503ee39
Zoogster/python-class
/Lab 3/Lab03P4.py
763
4.0625
4
customer_type = input( 'Enter R for residential customer or B for business customer: ') gallons_of_water = float(input('How many gallons of water were used? ')) customer_type = customer_type.upper() if customer_type == 'R': low_rate = 0.005 high_rate = 0.007 if gallons_of_water <= 6000: total_co...
fbbf43e056f06d8350e2e93919d86c0d1817d72c
gjvera/LeetCode
/python/problem9.py
261
3.921875
4
def isPalindrome(x): num = x if num < 0: num *= -1 reverse = "" while num != 0: reverse += str((num % 10)) num //= 10 if x == int(reverse): return True else: return False print(isPalindrome(121))
8313de43cf150426f4507b7e3badc8e2f487f42b
XanderXAJ/static-site-helpers
/lib/date.py
684
4
4
import datetime import typing def parse_date(date_string: str, matcher_strftime_format: str) -> datetime.date: """ Uses `matcher` to parse `date` string. Return a tuple of (True, parsed_date) on match, or (False, None). The `matcher_regex` must supply a date group (e.g. `(?P<date>...)`). Note: T...
6ed1cbb02d6ddf6cd99f157cc1b3d94920c8b237
lakenn/interview_questions
/redmart/rpn.py
1,670
3.53125
4
#!/usr/bin/env python # an rpn calculator in python # > 19 2.14 + 4.5 2 4.3 / - * # [85.297441860465113] # only supports two operands and then an operator import operator ops = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } unary_ops = \ { '--': operat...
edee73f7d9c42a3b747894fa233912609199f075
ipcoo43/pythonthree
/lesson104.py
203
3.609375
4
#!/opt/conda/bin/python import os clear = lambda: os.system('clear') clear() import re #data = input('>>> ') data = "abc 33 bb 1 dd" regex = re.compile("^[a-zA-Z]*$") mo = regex.search(data) print(mo)
c9c2d86b3f3728fd3f7b220ee736d9e2ad18ccf8
amyzheng95/MultiSensor_robot
/Server_pi/sensor.py
1,467
3.65625
4
import RPi.GPIO as GPIO import time def init(): GPIO.setmode(GPIO.BOARD) def getAllSensor(): a = getSensor(12,11) b = getSensor(3,7) c = getSensor(31,29) d = getSensor(37,35) e = getSensor(21,22) f = getSensor(23,24) ans = [a,b,c,d,e,f] ans = [str(i) for i in ans] return an...
eaaeaa16773e9334fccd145484fc0a38e0dc68ee
mkhalil7625/hello_sqlite_python
/reading_list/bookstore.py
6,451
3.96875
4
import sqlite3 from model import Book database_file = 'books.sqlite' class BookStore: """ Singleton class to hold and manage a database of books """ instance = None class __BookStore: def __init__(self): self._db = sqlite3.connect(database_file) self._db.row_factory = ...
060a93bb7939dc81855275f44412dd463b46fcb1
xerprobe/LeetCodeAnswer
/107. 二叉树的层次遍历 II/pythonCode.py
1,138
3.78125
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] node...
a60800b06bc49d37772620d64e6adedc969903b5
KFranciszek/PyLove-Python-Workshops
/PyLove 1.2 Files and JSON/task 2.7.py
882
3.84375
4
# 2.7 Load a JSON file. Create a file containing all the ships in sentences from the most expensive one to the cheapest: # <name> kosztuje <123> credits import json with open("py1.2zd.json") as file: data = json.load(file) list = [] list2 = [] for ship in data: credits = ship["cost_in_credits"] if credit...
baa5804842031c4921f7a31c6adf40350d201975
mario8f/Evaluacion1
/ejercico1.py
389
3.953125
4
#multiplicacion def ejercicio1(): print "Escriba la multiplicacion" producto=0 while(producto==0): a=input(" Dime la a= ") b=input(" Dime la b= ") c=input(" Dime la c= ") d=input(" Dime la d= ") producto=a*b*c*d if(producto==0): print "Er...
62c2df0712b09191d67443dc696da9484bd5af8f
pandahuang/PythonStudy
/python27/basiclearn/PyLearnBasic.py
22,829
3.921875
4
# -*-coding:utf-8-*- ''' First Stage... ''' # 1.input output # print "Please Input Your Name:" # Name = raw_input() # print "%s,Welcome to Python!"%(Name) # 2.not to transform # print r'\\\n\\\\' # encode decode # print '中文'.decode('utf-8') # 列表生成式的两层循环 # print [m+n for m in range(1,10) for n in range(11,20)] # imp...
0509cf40b4366cba017d4ce22f34fd58930f3840
muskangupta423/guvi_pos_neg
/range_armstrong.py
247
3.546875
4
a,b=(input("enter both numbers").split(" ")) if(a.isdigit() and b.isdigit()): for i in range(int(a)+1,int(b)): j=i s=0 while(j>0): r=j%10 s+=r**3 j=j//10 if(s==i): print(i) else: pass else: print("Invalid")
99eefecb5c5fe307dfa9678178ac5d90d10766c5
yashbhokare/cse576_project_2
/test/test_formats.py
284
3.703125
4
import unittest from src.data import formats class Format1(unittest.TestCase): def test_formatting(self): sent = formats.format_1('maximum', [1, 2, 3], 3) self.assertEqual("The maximum value among 1, 2, and 3 is 3.", sent, "should create the correct sentence.")
66f0184919eb9d0f6bbd4ec133854ccb94866eef
kimgy0/Python_Practice
/IF_FOR_WHILE/FOR_8_ListComprehension2.py
124
3.734375
4
#리스트 내포 사용하기 a=[1,2,3,4] print("a =",a) result=[num*3 for num in a if num % 2==0] print("result =",result)
da395188e0c7ad22badd1663e177f7b1c86f98c7
idan10000/University
/Intro. comp/hw5/hw5_322522111.py
19,599
3.78125
4
import copy import time ############ # QUESTION 1 ############ class SparseMatrix: """ Represents a rectangular matrix with n rows and m columns. """ def __init__(self, n, m): """ Create an n-by-m matrix of val's. Inner representation: list of lists (rows) """ ...
eb8dfc6e62a65b1d0aeccb71ba2d50b18b5bd45a
chenwenzhuo/AeroDataVisualizationSystem
/src/main/Visualization_PythonModule/visualization/test.py
337
3.640625
4
import numpy as np import matplotlib.pyplot as plt def stream(): w = 3 Y, X = np.mgrid[-w:w:100j, -w:w:100j] U = -1 - X ** 2 + Y V = 1 + X - Y ** 2 plt.streamplot(X, Y, U, V, density=[0.5, 1]) print(U) print("-----------------------") print(Y) plt.show() if __name__ == '__main_...
e58484c1681da7f8052b885d9c06220a27e67975
alaminbhuyan/Python-solve
/problem/word_score.py
509
3.828125
4
# def score_words(words_list): # score = 0 # for word in words_list: # num_vowels = 0 # for letter in word: # if letter in 'aeiouy': # num_vowels+=1 # if num_vowels%2==0: # score+=2 # else: # score+=1 # return score # # n =...
a658eced27e442370836476701d7db01c5f264c8
AgentRatz/VITAP-FRESHERS-CSE1002-AS1
/Program to Check a Number is Palindrome or Not Using While Loop.py
738
4
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 19 23:01:11 2021 @author: Rahul Bharadwaj """ #VITAP assignment-1 #School: SCOPE #Semester: Fall Sem 2021-22 #Subject: Problem Solving using Python #Subject Code: CSE1012 #Program to Check a Number is Palindrome or Not Using While Loop num = int(input("e...
8533bb45a3d1282f21f0c9c5cfd0cc62aa184e7f
wfeliciano20/pythonBootcamp
/PythonFundamentals/returnValues.py
497
3.734375
4
def calculate_mpg(car_to_calculate): mpg = car_to_calculate["mileage"] / car_to_calculate["fuel_consumed"] return mpg def car_name(car_to_calculate): name = f'{car_to_calculate["make"]} {car_to_calculate["model"]}' return name def car_info(car): mpg = calculate_mpg(car) name = car_name(car)...
0832bc6857463efe1a774c249c21db967dd5e62d
cxdtotsj/study_notes
/python/others/1.py
208
3.546875
4
# -*- coding: utf-8 -*- # @Data : 2020-04-03 str01 = 'aabbcdbaaabc' def remove_ab(s): if "ab" in s: s = s.replace("ab",'') return remove_ab(s) return s s = remove_ab(str01) print(s)
84a35e52509fa31df960a3d5c5e50280790327dc
Shorokhov-A/repo-algorithms_python
/lesson_8/task_8_2.py
1,270
3.703125
4
# 2. Закодируйте любую строку из трех слов по алгоритму Хаффмана. import heapq from collections import Counter, namedtuple class Node(namedtuple('Node', ['left', 'right'])): def walk(self, code, acc): self.left.walk(code, acc + '0') self.right.walk(code, acc + '1') class Leaf(namedtuple('Leaf', ...
c2f28318c03e380cc712027a571398c134c13690
lawy623/Algorithm_Interview_Prep
/Algo/Leetcode/138CopyListWithRandomPointer.py
980
3.734375
4
""" # Definition for a Node. class Node: def __init__(self, x, next=None, random=None): self.val = int(x) self.next = next self.random = random """ class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ if he...
c33f9bef7cb5e2ef378c4fe7b9cc28fad3478a62
ahmedzitouni586/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/100-weight_average.py
268
3.5
4
#!/usr/bin/python3 def weight_average(my_list=[]): if not isinstance(my_list, list) or len(my_list) == 0: return 0 avrg = 0 som = 0 for couple in my_list: avrg += (couple[0] * couple[1]) som += couple[1] return (avrg / som)
a64141e7dff56b9d25e93f75a1d9eab0d1acdb09
Matthew1996i/Exercicios_Uri
/1064.py
223
3.6875
4
x = 6 contador = 0 i = 0 e = 0 while i < x: valor = float(input()) if(valor >= 0): e += valor contador += 1 i += 1 media = e / contador print(contador, "valores positivos") print("%.1f" %media)
e6d781dcb58d691cb84d7913e3c9c3626be69604
hanelso/weblib
/PythonExam/PythonExam3.py
266
3.734375
4
def PrintCost(menu): str = input("메뉴: ") # if str == '오뎅': #오뎅 가격이 600일때... # return int(menu[str]/2) return menu[str] menu = {"오뎅":300,"순대":800,"만두":600} # print(menu) print("가격: " + str(PrintCost(menu)))
4baf40b1f3cf330617d071405af770b252f3ac7b
arnabs542/Competitive-Programming
/CodeForces/problem/A/281A_WordCapitalization.py
121
3.515625
4
# https://codeforces.com/problemset/problem/281/A s = input() mark = s[0] s = s[1:len(s)] print(mark.upper(),s,sep='')
a775281f3a6d2e300d9f4ff953ff146b0340730c
chaofan-zheng/python_leanring_code
/month01/night_study/exercise02.py
429
3.9375
4
""" 不使用循环计算1+2+3+....+n """ # 使用递归的方法 class DiGuiCalculate: def di_gui(self, n): if n < 1: return 0 return n + self.di_gui(n - 1) di_gui_calculate = DiGuiCalculate() print(di_gui_calculate.di_gui(10)) def di_gui(n): print(n, "<===1====>") if n > 0: di_gui(n - 1)...
2b2026545fdc15da8c4bb81e80a4032ae9c3488e
AdamZhouSE/pythonHomework
/Code/CodeRecords/2721/60649/258429.py
118
3.546875
4
T=int(input()) for i in range(T): s1,s2=input().split() int1=int(s1,2) int2=int(s2,2) print(int1*int2)
d7e1168d2ee3915d0af6885af20dc2672650250f
erjan/coding_exercises
/count_nodes_equal_to_average_of_subtree.py
784
3.765625
4
''' Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. ''' class Solution: def averageOfSubtree(self, root: Optional[TreeNode]) -> int: result = 0 def traverse(node): nonlocal result ...
62f03f96797748dbf5d503e4d592c3be37c7483c
lp2016/New_Algorithm
/leetcode_threeSum.py
805
3.671875
4
class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] self.threeSumHelper(nums,0,[],0,res,0) res = list(map(sorted,res)) res2 = set() for item in res: item = map(str,item) ...
5983a700296d129a3083a0417b9c159f456e9d98
chengchaoyang/my-leetcode-record
/hash-table/0290-word-pattern.py
1,269
3.90625
4
""" 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 示例1: 输入: pattern = "abba", str = "dog cat cat dog" 输出: true 示例 2: 输入:pattern = "abba", str = "dog cat cat fish" 输出: false 示例 3: 输入: pattern = "aaaa", str = "dog cat cat dog" 输出: false 示例 4: 输入: pattern =...
136c610907be09a464d33c775bdd87677982f160
legitpotato/DAA
/T3Greedy.py
722
3.828125
4
def Puntaje(array): if len(array) == 0 or len(array) == 1: print("error1") return(0) if len(array) == 2: print("error2") return(array[0]+array[1]) else: i = j = pos = total = 0 min = array[0] + array[1] for i in range(len(array)-2): if mi...
3354bc3d05df31dab230fc80fb4a732b0c404396
yanfriend/python-practice
/licode/perm2.py
1,425
3.609375
4
import copy class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ret=[] nums.sort() self.perm(ret,nums,0) return ret def perm(self,ret, nums, ind): if ind==len(nums)-1: ...
d342e65487c27f203c0b04a1174eb38968994896
ddrkaser/CS520_P2
/partial_sensing.py
19,375
3.671875
4
#!/usr/bin/env python3 import numpy as np import pandas as pd from math import sqrt import matplotlib.pyplot as plt import time import copy # Generates a length * width size gridworld # Each square has a probability chance of being blocked 0 means unblocked, 1 means blocked # The start and end squares are...
a9edbaa913f7e3916b1b38385503da7637116288
Ken0706/Crash_Course_Book_Python
/7.4_Pizza_Toppings.py
271
3.796875
4
def toppings(): while True: topping = input("Enter topping (enter 'quit' when you done): ") if topping == 'quit' : break else : print(f"Add {topping} success !!!") def main(): toppings() if __name__ == '__main__': main()
50ce6f0945ec25d451b3f3171a87491bb92c7226
bendeleon1226/pythonjourney
/001_Steven.py
1,241
3.984375
4
print("hi welcome to math class") print("Welcome to Easy") a=input("what is 1+1:") if a== str(1+1): print("great job 9 more to go to reach medium") else: print("Sorry you are wrong if you want to start again press stop and run") b=input("what is 8+1:") if b==str(8+1): print("yay you did it") else: print...
b5173a8ce5705d7493837ad1f9ab21f55817857d
tiger80156/pythonBasic
/udemyAlgorithm/stringreverse.py
166
4
4
x = input("Please entry a string : ") # rev = "" # for char in x: # rev = char + rev rev2 = list(x) rev2.reverse() rev = "".join(rev2) print(rev)
1b5ea3873be64ce8da8797bd9a6a7ab1178201f0
spaziochirale/CorsoPythonML
/sort2.py
279
3.984375
4
# crea lista vuota l=[] # chiedi un nome nome=input("Nome>") # finché il dato inserito non è 'STOP' aggiungi alla lista e chiedi un nuovo nome while nome != '': l.append(nome) nome=input("Nome>") # ordina la lista l.sort() # stampa la lista for n in l: print(n)
ce128dd4e90f244c34a1b432f0fb89035a917776
sunyi1001/leetcode
/142.py
1,133
3.703125
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ # 使用set """ find_map = set() iscycle = self.iscycle(hea...
93db6ad489ac2c98268146cb88ec6a2ea846b17b
rafaelmaframg/conversor-temperatura
/main.py
1,818
3.640625
4
import tkinter as tk from tkinter.messagebox import showerror #função para limpar dados e preencher com os novos valores def texto_set(entry, texto): entry.delete(0,tk.END) entry.insert(0,str(texto)) def convert_to_fahr(*args): global trace_fahr varfahr.trace_remove("write", trace_fahr) cels...
5ee50fffef8e55bca009cd0e33dc316f955ffa9a
analyticalbadger/RoboGarden
/grading.py
422
4.21875
4
print ("Estimate the letter grade from five scores") score_total = 0 for i in range(5): user_input = int(input("Enter score from 0 to 20: ")) score_total = score_total + user_input if score_total >= 85: grade = 'A' elif score_total >= 75: grade = 'B' elif score_total >= 65: grade = 'C' elif score...
f20a394dffa277ba8529351e62399f5aaee3c067
NathanTurcotte/CS3130
/ASS4/Client.py
2,847
3.640625
4
#!/usr/bin/env python3 import socket import cdb import ra import re MenuString = """ -- Employee FMS Select one of the following: 1) Add a new employee 2) Search for an employee 3) Remove an employee from FMS 4) Display entire employee FMS 5) Quit --""" def send(host, port, data): """ Esta...
41d5c4d8d69c042c49cc265d6560229616bf67dd
freebz/Effective-PYTHON
/ch02/better_way_20/ex20-2.py
435
3.875
4
def log(message, when=None): """Log a message with a timestamp. Args: message: Message to print. when: datetime of when the message occurred. Defaults to the present time. """ when = datetime.now() if when is None else when print('%s: %s' % (when, message)) log('Hi the...
91d5ed5dd02be7604718abf12fecbf1c12f60629
rkdr055/BOJ
/11653.py
136
3.59375
4
n=int(input()) div = 2 while div*div<=n: while n%div==0: print (div) n //= div div += 1 if n != 1: print(n)
15056071e4bc41d86cc0c9e2e17a7a7a0b287acf
dgh1000/sean
/automate/chap7_regex.py
1,153
4.09375
4
import re def isPhoneNumber(text): if len(text) != 12: return False for i in range(0,3): texttest = text[i] if not texttest.isdecimal(): return False if text[3] != "-": return False for j in range (4,7): if not text[j].isdecimal(): retu...
9a61ce8130300a39a021c216611aaef64787af2b
jinurajan/Datastructures
/LeetCode/easy/shortest_completing_word.py
3,940
4.1875
4
""" 748. Shortest Completing Word (Easy) Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word...
58fc67a35100248377c1535235868041170e7601
naitokit/example
/FMR.py
9,209
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import pandas as pd import numpy as np import scipy.optimize import math import matplotlib.pyplot as plt import os #Fitting function(lorenssian) #def lorenssian(x,A,x0,r): # f = A*(r/2)**2/((r/2)**2+(x-x0)**2)+A*r/2*(x-x0)**2/((r/2)**2+(x-x0)**2) # return...
1fbca50064784ea0e6b594ad0d0fb89bbc8d9d64
verdantfire/Python-Tutorial-for-Beginners-2019---Programming-with-Mosh
/guess_game.py
265
3.890625
4
secret=9 guess_count=0 guess_limit=3 while guess_count < guess_limit: guess=int(input("guess the number:")) guess_count+=1 if guess==secret: print("You won") break else: print("You failed") print("End of the game")
93cc6e2e4eff87432cc21adff0325bcbf0c89543
prakashatul1/interview_prep
/dsa/sorting/quick_sort.py
2,834
4.125
4
"""quick sort easy way with increased space complexity""" # def quick_sort(arr): # length = len(arr) # if length <= 1: # return arr # else: # pivot = arr.pop() # items_greater = [] # items_smaller = [] # # for each in arr: # if each > pivot: # ...
06493e34a8988b6055898023de3ba7a6015f86d5
firstep710/baekjoon
/음계.py
443
3.640625
4
a=list(map(int,input().split())) b=[1,2,3,4,5,6,7,8] if a==b: print('ascending') elif a==b[::-1]: print('descending') else: print('mixed') ######################################### a=list(map(int,input().split())) asc=True desc=True for i in range(1,len(a)): if a[i]>a[i-1]: desc=False eli...
ccc3d1accf9dcec5b5b4c5c4c563c37d02419aae
JuHyang/today-I-learned
/Algorithm-Study/programmers/level_3/2_tile_art.py
217
3.625
4
def solution(N): answer = 0 before = 1 after = 1 for i in range (N - 1) : temp = after after = before + after before = temp answer = after * 2 + before * 2 return answer
eac5f4e391e700ac19f9bbf5ae9d8b3a84aa5b59
AbantikaKarmakar/guessgame
/practiceprob6.py
1,316
4.03125
4
from random import randint a = int(input("Enter the lower bound: ")) b = int(input("Enter the upper bound: ")) # Generate some random integer value1 = randint(a, b) value2 = randint(a, b) # print(value) count1 = 0 count2 = 0 while True: print("Player 1:") m = int(input(f"Please guess the number b...
72361e92353b29b5b31ffb7cc906b2e34ebe8ca8
MichaelDeutschCoding/Python_Baby_Projects
/Battleship2.py
4,043
4.0625
4
from random import randrange, choice from string import digits # TO DOs # various sized ships # define class (ship) # two players def battleship(): print() print("\t \t ~~~ Let's Play Battleship! ~~~") print("You may type 'Q' at any time to quit.") sz = input("What size board would...
d9c138317d3251148d78395a5d3aeab437e60bb6
cleyton27mb/app-comerciais-kivy
/test/main.py
247
4.125
4
num1 = float(input("Digite um numero:")) num2 = float(input("Digite outro numer")) divisao = num1/num2 resto = num1 %num2 print(num1, "dividido por ", num2, "é igual a: ", divisao) print("O resto da divisao entre", num1, "e", num2, "é", resto)
a88527d271fd54fb46a8a21d6e761230916788f5
KayZinPhone/Programming_2_CP1404_Practical
/practical_10/wiki.py
330
3.53125
4
import wikipedia var1 = input("Search Keyword: ") print("Search: \n", wikipedia.search(var1)) try: print("Summary: \n", wikipedia.summary(var1)) except wikipedia.exceptions.DisambiguationError as e: print(e.option) page = wikipedia.page(var1) print("Page: ", page) print("URL: ", page.url) print("Title: ", pa...
7bb8fb69ce072c9dff391b1f4c88469a03299559
kevinhynes/algorithms-and-data-structures
/2-4-anagram.py
1,054
3.859375
4
# This program is a linear O(n) solution to determining if two strings are # anagrams. from string import ascii_lowercase def find_anagram(s1, s2): s_lists = [s1.lower(), s2.lower()] s_dicts = [{}, {}] # Create a dictionary for each string. Fill keys with lowercase # a-z and all values initialized ...
0053828d637c38038ea9d12f4ddd9c07c0dd3b94
reshmarn28/Python-Programs
/HP/HP-evening-5-13/OOP.py
897
4
4
# class my_class: # def display(self,name,age): # self.name=name # self.age=age # print("My name is"+self.name+" My age is",self.age) # c1=my_class() # c1.display("Sunny",25) # class myclass: # name = "" # def display(abc): # print("Welcome"+abc.name) # c1=myclass() # c1.nam...
fa4fcee2204d433138c0875c9e429a985150f8e5
j611062000/leetcode
/Classical Dynamic Programming Problems/Unbounded Knapsack.py
1,406
3.796875
4
for i from 1 to capacity of knapsack: for volume from (the first item) to(the last item): [4.1] # 0/1 knapsack problem with unlimited supply of items # dp[i] = True --> a knapsack with volume i can be filled with. if dp[i - volume] == True: dp[i] == True else: dp[i] = False [4.2] # [4.1] and each item ...
c94e1bb613f7fb8cf3a30ccb6a7ff8b3a830680c
heman18173/Python-Tutorial
/Chap11_TestCode/test_survey1.py
883
3.9375
4
import unittest from survey import ASurvey class ASurveyTest(unittest.TestCase): def setUp(self): """ Create class to test with setUp Method """ question = "What language you learn first?" self.my_survey = ASurvey(question) self.responses = ['Gujarati', 'Hindi'...
bb3e64563ad4870b4710f623218a10ea751a66dc
GBoshnakov/SoftUni-Advanced
/Multidimensional Lists/Symbol in Matrix.py
387
4
4
rows = int(input()) matrix = [] for row in range(rows): matrix.append([n for n in list(input())]) position = None searched_symbol = input() for row in range(rows): for col in range(rows): if matrix[row][col] == searched_symbol: position = (row, col) print(position) ...
4184757c8e136a173c63297bb7f2a275c8c5927a
lanzhiwang/common_algorithm
/data_structures/01_binary_tree/04_red_black_tree/02_red_black_tree.py
11,001
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class RedBlackTree: def __init__(self, label=None, color=0, parent=None, left=None, right=None): self.label = label self.color = color # 0 黑色, 1 红色, 默认黑色 self.parent = parent self.left = left self.right = right def rotate_...
a4bd33955fd0cc5f995b25e9cdbad5517ad5ae5d
gcspanda/Python-Crash-Course
/ch15/15-01.py
341
3.765625
4
import matplotlib.pyplot as plt x_values = [1, 2, 3, 4, 5] y_values = [x**3 for x in x_values] plt.scatter(x_values, y_values, c='red', s=20) plt.axis([0, 10, 0, 150]) plt.show() x_values = list(range(1, 5001)) y_values = [x**3 for x in x_values] plt.scatter(x_values, y_values, c='red', s=20) plt.axis([0, 5100, 0,...
2bef816a1850d218025aa6f64ed530664762a817
behrouzmadahian/python
/python-Interview/9-binarySearchTree/1-search-insertion.py
1,918
3.71875
4
''' Binary Search Tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also...
e0e6ee7e997ccdcc861d7be06c8017a1bd4981b7
Sandbox4KidsTM/Python_Basics
/Supplemental_Material/PythonProjects/10. GUI_Tkinter/GUI_BindingButtons_nb.py
281
4.0625
4
from tkinter import * root = Tk() def printName(): print("hello, my name is Bucky") button_1 = Button(root, text="Print my name", command=printName, bg="red", fg="white") # command binds the function printName() to the button_1 button_1.pack() root.mainloop()