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
4bf9e8997132bb85ff8cf9266c2bbff8c0db6bdc
psiionik/CodingProblems
/DailyCodingProblem/medium/originalSentenceInList.py
2,454
4.09375
4
""" Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, return null. For example, given the set of words 'quick', 'brown', 'the', 'fox', and th...
30c57bd02196465e48066a176de4a25154f7b20f
psiionik/CodingProblems
/DailyCodingProblem/hard/kthLongestSubstring.py
1,417
3.921875
4
""" Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = 'abcba' and k = 2, the longest substring with k distinct characters is "bcb". """ """ Solution 1, Keep a running window of the longest substring. Keep a dictionary that ...
76e0ee8a15d9760f9391566ee1983fccea4a15be
psiionik/CodingProblems
/LeetCode/DailyPractice/totalFruit.py
1,340
3.640625
4
""" In a row of trees, the i-th tree produces fruit with type tree[i]. You start at any tree of your choice, then repeatedly perform the following steps: Add one piece of fruit from this tree to your baskets. If you cannot, stop. Move to the next tree to the right of the current tree. If there is no tree to the rig...
b9f5390084d0a7b059229ac4532d7a091bd5b81b
psiionik/CodingProblems
/ProjectEuler/Problem5/SmallestMultiple.py
1,303
3.75
4
import math def smallestMultipleV1(): for i in range(2521, 10000000000000): theNum = True for num in range(20, 1, -1): if (i % num != 0): theNum = False break if (theNum == True): return i def smallestMultipleV2(): for i ...
ef9a396c91669635e0bdea3fd98149516493923e
psiionik/CodingProblems
/LeetCode/DailyPractice/mergetwobinarytrees.py
610
4.03125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def mergeTrees(t1: 'TreeNode', t2: 'TreeNode') -> 'TreeNode': if(t1 == None): return t2 if(t2 == None): return t1 if(t1 != None and t...
93720a208b363a936f2c9d2a2712e4fcd3f6ceb6
tchelmella/pythonpractice
/triangle.py
298
3.953125
4
''' import math base = float(input("Enter the base")) height = float(input("Enter the height")) area = float(0.5 * base * height) print(area) ''' def triangle(base,height): return (base*height*1/2) x = float(input("Enter the base")) y = float(input("Enter the height")) print(triangle(x,y))
7d394e79fb5f1b84d7b672e1bd103eb8e36f4500
satyaholla/Programming-Assignments
/Project Euler/ProjectEuler.py
10,322
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 13 15:17:58 2020 @author: satyaholla """ """Project Euler Problems""" import math from itertools import combinations # def primeList(n): # """Returns an ordered list of all primes under n""" # assert isinstance(n, (int, float)) # if n...
03d79c32134a277ea444dfe637b3ab6ccad6dded
satyaholla/Programming-Assignments
/6.0001 Psets/1_ps4/ps4a.py
2,917
4.0625
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx # Late Days Used: x # Part A0: Data representation # Fill out the following variables correctly. # If correct, the tests named data_representation should pass. treeA = [[14,19],[[3,5],0]]# TODO: change this assignment treeB = [[9,3],6] # TOD...
4b544fe1fdd84e7b307fb3bf65e458b3237c1234
dcarmod2/VisionZeroTheory_Submission
/FINAL_Night/windower.py
283
3.578125
4
import datetime name="Manhattan night" print(name) (start_evening_rush,end_evening_rush)=(18,23) # 6 to 11 PM window_length = 6 def timewindower(dt): if (dt.isoweekday()>5): return False #immediate return false if weekend return (start_evening_rush<=dt.hour<=end_evening_rush)
ffd2e72e60734438c1321a5d92c3389d22509f34
ronyaryaW1/dasar-python
/ifels.py
297
3.640625
4
# angka1 = 10 # angka2 = 20 # if angka1 > angka2: # print("betull!!!!") # else: # print("salah woiii") uang = input("Uangmu brp? ") utang = 20000 if int(uang) < utang: print("sory bos duitmmu kurang") elif int(uang) == utang: print("suwun bos") else: print("duitmu lewih")
9f646ec7e27158abefeef6da59d93f481478a42d
Hp2197/CE_450-HW-4
/4_5.py
292
3.703125
4
# coding: utf-8 # In[1]: def mrg(ls1, ls2): ls=ls1+ls2 sorted=[] def srt(ls): x=min(ls) ls.remove(x) sorted.append(x) if not ls: return sorted return srt(ls) return srt(ls) print(mrg ([1, 3, 5], [2, 4, 6]))
f92a5face59bb9bcf41e1e8d67b35551a08b92a4
Hp2197/CE_450-HW-4
/4_2.py
194
3.5
4
# coding: utf-8 # In[1]: def rm_all(elem, lst): x=[] for a in lst: if(elem!=a): x.append(a) return x x = [3, 1, 2, 1, 5, 1, 1, 7] print(rm_all (1, x))
fc820241fcfa0279c60118c457e7dc423a3605c6
adelattia/euler
/005.py
342
3.859375
4
from time import time start = time() def smallest_multiple(d): n = d t = d while True: while n % d == 0: d -= 1 if d == 1: return n d = t n += 1 print(smallest_multiple(20)) end = time() total_time = end - start print("done in : {} second...
b7ee8f4f43dd6adae8585a83de5334cde2cbb09d
adelattia/euler
/016.py
140
3.53125
4
def digits_sum(n): st = str(n) s = 0 for i in range(len(st)): s += int(s[i]) return s print(digits_sum(2 ** 1000))
81bff4606792b564ae99b46c51359f10cb6b7e14
NightCrawler96/Kalkulator-drzew-filogenetycznych
/actions/common.py
795
3.75
4
import os from typing import Any def ask_if_finished(): return ask("Have you finished?") def ask(question: str) -> bool: while True: print(f"{question} (yes/no)") answer = input() if answer == "yes": return True elif answer == "no": return False def ...
0387ac109f0f2e642b644dd2e3768d2629c193dd
HediaBougi/3D_House
/v1.0/BBox.py
396
3.53125
4
#class BBox to check boundries class BBox(object): def __init__(self, left, bottom, right=None, top=None): self.left = left self.bottom = bottom self.right = right if right else left self.top = top if top else bottom def isIn(self, bb): return self.left >= bb.left and ...
36165090d16279c7e0fa60a1a7cdfb5dc0d6d1e0
VChristlein/textsegment
/utils/tf_image_processing.py
10,329
3.65625
4
import tensorflow as tf """Image processing tools for image segmentation.""" def get_random_angels(shape, deviation=0.5, distribution='NORMAL', name=None): """ Get random angels using a normal or a uniform distribution. `distribution` can be one of: * `NORMAL`: Normal distribution * `UNIFORM`: Uniform d...
53039014b78ac16e0a91532a12b0920baa2ed637
jerome-diver/python_tests
/phone_number_format/phone_number_format.py
229
3.953125
4
"""from [0,1,2,3,4,5,6,7,8,9] format phone number: (012) 345-6789""" def phone_number_format(n): return "({}{}{}) {}{}{}-{}{}{}{}".format(*n) print("[0,1,2,3,4,5,6,7,8,9] ==>", phone_number_format([0,1,2,3,4,5,6,7,8,9]))
8a1317dde401bfb69fe8504bb8b9eada09e1933d
Ayushchauhan009/Python-programs
/Contact Book Directory Project/main.py
2,568
3.65625
4
import contact import addressbook import re from sys import exit import random __author__ = 'Muhammad Arslan <rslnkrmt2552@gmail.com>' app = addressbook.addressbook(str(input("Enter name of book (Will be created if doesn't exist) \n> "))) main_menu = '\n1. Show all contacts.\n2. Add contact.\n3. Search.\n4. Delete ...
f5df8af88f3449e2124e9cc0899300bc2eff9fb7
mzanzilla/Python-For-Programmers
/Files/ex3.py
1,239
4.5
4
#Updating records in a text file #We want to update the name for record number 300 - change name from White to Williams #Updating textfiles can affect formattting because texts may have varrying length. #To address this a temporary file will be created import os tempFile = open("tempFile.txt", "w") accounts = open("acc...
17ee83f78ffc75ddc60789152a67d32531fff727
mzanzilla/Python-For-Programmers
/Exceptions/ex1.py
656
4.375
4
#demonstrating how to handle a division by zero exception while True: #attempt to convert and divide values try: number1 = int(input("Enter numerator: ")) number2 = int(input("Enter denuminator: ")) result = number1 / number2 except ValueError: #Tried to convert non-numeric value to ...
851fb62de4466199a6ce0579b5ec72972dea1eab
kgraper/python-challenge
/PyBank/Main.py
1,700
3.890625
4
import pandas as pd import path import os from datetime import datetime import sys csvpath = "raw_data/budget_data_1.csv" budget = pd.read_csv(csvpath) budget.head() #Assigning Var to find total number of months in dataset total_month = budget["Date"].count() total_month #Assigning Var to find total revenue in the d...
b02d174d43b5d726bcb1bda099d66f759c5b8115
nobodysshadow/HangmanGame
/Python/Lib/library_start.py
3,894
4.03125
4
""" [library_start.py] from the HangmanGame Defines the function of GW for the game HANGMAN_PICS Definition of the Definition of the hangman pictures getRandomWord(length) Word selection function that return the to word to guess displayBoard(missedLetter,wordStatus): Function that displays the game status...
00509c63f5b36a1acfce6a6c7bc82d7e251b9ef1
ramyaavak/set6
/prime_num.py
148
3.625
4
n=int(raw_input()) flag=0 for i in range(2,n): if(n%i==0): flag=flag+1 if(flag==0): print("yes") else: print("no")
25f12e032971a403bfc346e15b536c8934bf4e47
kotrenn/crystal
/recipe/recipe.py
785
3.53125
4
class Recipe(object): def __init__(self, name): self.name = name self.label = '[Undefined Label (' + self.name + ')]' self.cost = [] self.input = [] self.output = [] self.req = [] self.code = [] def __str__(self): ret = '' ret += 'Recipe '...
f1960bb76a053982c8ed3b125ed6dc23cc1773a0
tmemud/Python-Projects
/ex47.py
140
3.890625
4
#filtering a loop print ('before') for numbers in [1,2,3,4,5,6]: if numbers > 4: print('largest:', numbers) print('done')
4461ea009cb18cfc2b7167372e5d31c1a8e35c2f
tmemud/Python-Projects
/ex72.py
1,110
4.40625
4
# Use the file name mbox-short.txt as the file name #7.2 Write a program that prompts for a file name, then opens that file and reads through the file, #looking for lines of the form: X-DSPAM-Confidence: 0.8475 #Count these lines and extract the floating point values from each of the lines and #compute the av...
dbbf8e248aa3020e2c2a932367b68daac11fb8e0
AVoss84/My-Python
/Linear_model_in_Python.py
2,339
3.953125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 11 11:32:38 2017 @author: z002ffcz """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score from numpy import random as r # Load the diabetes dataset diabetes...
18cd64c19d6cb25b8c1c0b46f1a41c7a4a6ce80d
HMJ10/Python
/Calculator.py
4,917
4.125
4
Calculator import tkinter # The main frame of the calculator window = tkinter.Tk() window.title("CALCULATOR") window.geometry('312x324') window.resizable(0, 0) # Getting the function or command to perform from the user def button_click(item): global expression expression = expression + str(item) input_...
e7498e5e17a52bf70e054e4de69125d3a770ba37
EmmaAnif/cme211
/hw2/similarity.py
5,296
3.640625
4
import math import sys import time def checkSimilar(rTup): """ Returns the similarity coefficient of the two rates represented as a list of tuples rTup is a list of pairs of rate1 and rate2 """ num = 0; den1 = 0; den2 = 0 rLen = len(rTup) #get average of the two lists unzip_rTup = li...
770afa7ca3d673b8ff2be3fc4c11511caa2cb5ff
GRUPO7-RAMIREZ-AVENDANO/GRUPO7_Ramirez_Avendano
/Trabajo_5/Actividad_3.py
91
3.875
4
a='b' print(a) b=a+'b' print(b) c=a+'a' print(c) d=a*2+'b'*3 print(d) e=2*(a+'b') print(e)
0c2986fa15bf8d3ec64f1f233ee536c7a3e513a3
GRUPO7-RAMIREZ-AVENDANO/GRUPO7_Ramirez_Avendano
/Trabajo_5/Actividad_6.py
330
4.03125
4
num_1=int(input("Ingresar primer número: ")) num_2=int(input("Ingresar segundo número: ")) if num_2 is (num_1**2): print("El segundo es el cuadrado exacto del primero.") elif num_2 < (num_1**2): print("El segundo es menor que el cuadrado del primero.") else: print("El segundo es mayor que el cuadrado del pr...
c8ad893bb45f030a70d13a4691a9c80e20003730
akcssk/study_deeplerning
/logic_gate.py
1,633
3.53125
4
import numpy as np def perceptron (x1, x2, w1, w2, bias): #2017/01/29 #パーセプトロンを利用したNAND回路 #パーセプトロンはXORを出せない。直線を引いて分断するだけなので #非線形の分類でないと無理 #ここで多層パーセプトロンですよ x = np.array([x1, x2]) w = np.array([w1, w2]) tmp = np.sum(w*x) + bias if tmp <= 0: return 0 else: return 1 def NAND (x1, x2): ...
d0300494b73b1ebbad013b92bbd3abee12910308
faruk-ahmad/ml-proj-init
/ml_proj_init/data/network/lstm_nn.py
2,439
3.78125
4
""" A module to build simple LSTM network for Text classification related Deep learning experiment. Author: Faruk Ahmad Date: 23 May, 2020 Ref: https://keras.io/ """ # lets import necessary stuffs here import tensorflow as tf from tensorflow.keras.layers import Input, Dense, Dropout, Embedding, Bidirectional, LSTM f...
ff79541316940fd80dc8aff1b1ee4d26ada99496
faruk-ahmad/ml-proj-init
/ml_proj_init/validation.py
2,643
3.875
4
""" A module for validatinig different parameters given by user """ import os import string import sys # import configs from .config import configs class Validation(): """ A class holding required methods for validating user inputs """ def __init__(self): self.valid_choice_run_mode = configs...
a66eb6701527182c48aab9084c2ea8d7d8ebf754
catchsaurabh0209/nptel_programming_work
/printProgram.py
322
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 18 22:15:42 2019 @author: OCEAN """ print("welcome to fizz buzz game") n=int(input()) for i in range(1,n+1): if(i%3==0 and i%5==0): print(i,"fizzbuzz") elif(i%3==0): print(i,"fizz") elif(i%5==0): print(i,"buzz") else: print(...
5bc628e1d85404ef428bb5ac259669ff9542a57a
lumafragoso/Basico_Condicionais_Contador_Cedulas
/main.py
1,116
3.984375
4
print('=-=-=-= Bem-vindo ao Caixa Eletrônico =-=-=-=') print('Tenho cédulas de R$100, R$50, R$20, R$10 e R$5') valor = float(input('Qual valor deseja sacar: R$ ')) while (valor % 5) != 0: print('Não é possível sacar este valor!') valor = float(input('Qual valor deseja sacar: R$ ')) else: print('Certo, lhe e...
62b53a19658898b8e97e5638c22d3feb6da76022
sathyanglg/code_samples
/Python/euler/2.py
517
4
4
# Each new term in the Fibonacci sequence is generated by adding the previous two # terms. By starting with 1 and 2, the first 10 terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values do not # exceed four million, find the sum of the even-value...
41a93c8c8149ba43fbdd054fb331293a44a621a5
reenal/rolling-mean-std-deviation
/RollingMeanStdDeviation.py
1,150
3.796875
4
# Run on terminal to install packages # pip install pandas # pip install matplotlib # 1 - Required imports import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() # 2 - Load data from CSV file path = 'C:\AllTech\Code\...
f40b01184dfe6171ce6614278f436aab72768ae3
itsthebrownrice/parsel_tongue
/00_GuessingGame/01_GuessingGame.py
1,605
4.09375
4
import random rnd_num = random.randint(1,100) print('Enter any number to guess the computer-generated number.') num_list = [0] count = 0 while True: try: # First try if count == 0: guess_num = int(input('Enter any number from 1 to 100: ')) num_list.append(guess_num) co...
a7351fb387a69885aad636368da7e110c0ec1696
crossihuy/MyRepo
/idk_with_loops.py
353
4.15625
4
my_list = [] while True: question = input("Do you want to add a name: \ny|n: ").lower() if question == "y" or question == "": my_list.append(input("Give me a friend's name: ")) continue elif question == "n": break else: print("You did not select y or n") for i in my_list:...
634bdab2eafe6683c090eb281459bbff8a4dc003
crossihuy/MyRepo
/save_data.py
626
3.796875
4
gbday = "" try: with open("day.txt", "r") as fileday: yesterday = fileday.readlines() if yesterday == "good": print("Glad you had a good day yesterday") elif yesterday == "bad": print("Sorry you had a bad day, tomorrow will be better.") except FileNotFoundError: ...
21e4f6682d558e19baf340cf753df5d1f9516f45
harushimo/python_programs
/month_validator.py
304
4.125
4
#!/usr/bin/python months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def valid_month: for i in months: if(i.lower() == months.lower()): return i print valid_month("January") print valid_month("january")
75f5eafe760f8ef05d72681f9998cf2272e21d31
Sneha46749/Object-Oriented-Programming-in-Python
/BankAccount-Creating-DataMembers.py
1,442
3.875
4
class Account: def __init__(self, filepath): self.filepath = filepath with open(filepath, 'r') as file: self.balance = int(file.read()) def withdraw(self, amount): self.balance = self.balance - amount def deposit(self, amount): self.balance = self.balance + amo...
2aba16588af91b6a483f1d1029891d5d3e65d41f
sanjaysingatalur/pymongo
/First.py
563
3.640625
4
#for single record from pymongo import MongoClient client=MongoClient('mongodb://localhost:27017') print (client) db=client.library #db name collection=db["Books"] #collection name book={} book["title"]="Anatomy" book["year"]=1997 book["author"]="rahim" collection.insert_one(book) prin...
7a61a752829549fa49bbd21c5cfa45802f2b0ad6
juanall/Informatica
/TP5.py/5.1.py
859
3.859375
4
#Dada la siguiente clase, identificá la interfaz y el estado de la misma: class Perro: def __init__(self): self._alimento = 0 self._caricias = 0 def energia(self): return self._alimento + (self._caricias * 10) def comer(self, gramos): self._alimento += gramos def acar...
230305855dd6284c061fc408a7805931cb0cb7c8
juanall/Informatica
/TP2.py/2.14.py
703
4.125
4
#Ejercicio 14 #Creá una función que calcule la temperatura media de un día a partir de la # temperatura máxima y mínima. Escribí un programa principal, que utilizando # la función anterior, vaya pidiendo la temperatura máxima y mínima de cada # día y vaya mostrando la media. El programa tiene que pedir el número de dí...
d0e6bd9f0552753764de59cacfc0ed6225772f5e
Alien178/Python-Projects
/WhiteHatJr_Python_Projects/ICP - Data Visualization/line.py
202
3.65625
4
import pandas as pd import plotly.express as px df = pd.read_csv("CSV-Files/line_chart.csv") fig = px.line(df, x="Year", y="Per capita income", title="Per capita income", color="Country") fig.show()
8e0aef22a931976b07ce941a149a9c964bb69bb8
gurucharanD/python
/python/gen.py
659
3.859375
4
def create_cubes(n): result = [] for x in range(n): result.append(x**3) return result def create_cubes_gen(n): result = [] for x in range(n): yield x**3 # for i in create_cubes_gen(10): # print(i) def fibo(n): a = 0 b = 1 for i in range(n): ...
6f3f32210bfb5d95df6000a4a0542986513c8f7d
gurucharanD/python
/python/bin.py
632
3.609375
4
import math elements = [1, 2, 3, 4, 6, 7, 8, 100, 344, 987, 999] key = 1500 def binary_search(elements, left, right, key): mid = math.floor((left+right)/2) print(left, right, mid) if elements[mid] == key: print('key found', key) return if mid == len(elements)-1: p...
09ddac4fa710c12fca2b1181478b82ec8b48cda3
bkoehler2016/python_projects
/book.py
307
3.5
4
class Book: def __init__(self, name, year, author_first, author_last ): self.name = name self.year = year self.author = Author(author_first, author_last) pass class Author: def __init__(self, first, last ): self.first = first self.last= last pass
b527e70db8dd5f3cf9afa0047c9a4140cbb94e82
bkoehler2016/python_projects
/forloop.py
458
4.28125
4
""" a way to print objects in a list """ a = ["Jared", 13, "Rebecca", 14, "Brigham", 12, "Jenn", 3, "Ben", 4] # printing the list using * operator separated # by space print("printing the list using * operator separated by space") print(*a) # printing the list using * and sep operator print("printing list...
d3d3ca0355a7d81f2af45f9e4bbc487e4d04c6b0
damienlancry/.leetcode
/73.set-matrix-zeroes.py
779
3.5625
4
# # @lc app=leetcode id=73 lang=python3 # # [73] Set Matrix Zeroes # # @lc code=start class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ m = len(matrix) n = len(matrix[0]) zeroedrows =...
f853fa35b591b35eae0d4a2e4a5d3f2b277863ac
damienlancry/.leetcode
/342.power-of-four.py
1,128
3.5
4
# # @lc app=leetcode id=342 lang=python3 # # [342] Power of Four # # https://leetcode.com/problems/power-of-four/description/ # # algorithms # Easy (41.92%) # Likes: 877 # Dislikes: 253 # Total Accepted: 229.9K # Total Submissions: 548K # Testcase Example: '16' # # Given an integer n, return true if it is a powe...
a0d3a36489a7e5f822e99f3a43ba7ddfcd5c646e
damienlancry/.leetcode
/263.ugly-number.py
1,289
3.84375
4
# # @lc app=leetcode id=263 lang=python3 # # [263] Ugly Number # # https://leetcode.com/problems/ugly-number/description/ # # algorithms # Easy (41.68%) # Likes: 773 # Dislikes: 793 # Total Accepted: 240.1K # Total Submissions: 576.2K # Testcase Example: '6' # # An ugly number is a positive integer whose prime f...
5bbca3644863017c40ecaaa00718455b44e33c69
damienlancry/.leetcode
/225.implement-stack-using-queues.py
3,056
3.796875
4
# # @lc app=leetcode id=225 lang=python3 # # [225] Implement Stack using Queues # # https://leetcode.com/problems/implement-stack-using-queues/description/ # # algorithms # Easy (48.11%) # Likes: 1057 # Dislikes: 685 # Total Accepted: 220.4K # Total Submissions: 457.7K # Testcase Example: '["MyStack","push","pus...
e5e117932b4e07e107b8dd226d9833d2af5d9e90
damienlancry/.leetcode
/72.edit-distance.py
2,052
3.546875
4
# # @lc app=leetcode id=72 lang=python3 # # [72] Edit Distance # # @lc code=start class Solution: # brute force O(3^n) # def minDistance(self, word1: str, word2: str) -> int: # def dp(i, j): # if i >= len(word1) or j >= len(word2): # ans = abs(len(word1) - i - len(word2) + j...
c649b55afef079e7c0109b2d70ef586259e5ffed
damienlancry/.leetcode
/414.third-maximum-number.py
800
3.609375
4
# # @lc app=leetcode id=414 lang=python3 # # [414] Third Maximum Number # # @lc code=start import random class Solution: def thirdMax(self, nums: List[int]) -> int: nums = list(set(nums)) if len(nums) < 3: return max(nums) return self.quickselect(list(set(nums)), 3) def q...
b763e380dd8713be4fc8461ae4a8018f67884692
Yair99/EjercicioPrueba
/VelocidadPromedio.py
291
3.84375
4
#Autor: David Yair Fernández Salas #Calcula la velocidad promedio en un viaje tiempo= int(input("Teclea el tiempo de viaje en hrs. enteras: ")) distancia= int(input("Teclea la distancia del viaje en km enteros: ")) velocidad=distancia/tiempo print("La velocidad promedio es: ", velocidad, "km/h")
9257561acddd02bd56de08bd1122f91c14000de5
yuanchangwang/cheshi
/L04(下)迭代器、map、reduce、sorted、filter、列表、字典、集合推导式、生成器函数/课件/8.生成器.py
1,018
4.25
4
# ### 生成器 元组推导式是生成器(generator) ''' 定义:生成器可以实现自定义,迭代器是系统内置的,不能够更改 生成器的本质就是迭代器,只不过可以自定义. 生成器有两种定义的方式: (1) 生成器表达式 (里面是推导式,外面用圆括号) (2) 生成器函数 ''' # (1) 元组推导式的形式来写生成器 gen = (i * 2 for i in range(5)) print(gen) from collections import Iterator print(isinstance(gen,Iterator)) # (2)使用for循环进行调用 for i in gen: print(i) # ...
3725f3519dcaaa993db6aabb5eb7f225798e2b09
yuanchangwang/cheshi
/L04(下)迭代器、map、reduce、sorted、filter、列表、字典、集合推导式、生成器函数/课件/4.sorted.py
1,112
4.25
4
# ### sorted ''' sorted(iterable,reverse=False,key=函数) 功能:排序 参数: iterable:可迭代性数据(常用:容器类型数据,range对象,迭代器) reverse : 是否倒序 默认正序reverse= False(从小到大) 如果reverse=True 代表倒序 (从大到小) key = 自定义函数 或者 内置函数 返回值: 排序的序列 ''' listvar = [1,2,-88,-4,5] # 按照从小到大默认排序 res = sorted(listvar) print(res) # 从大到小排序 res = sorted(listvar,revers...
c6bd2d143bd8f5b6d2af15f59719a9d79a736ca3
yuanchangwang/cheshi
/L16 数据结构与算法/oldboy/algo/sort_algo/merge_sort.py
1,177
3.9375
4
# coding=utf-8 """ author = jamon """ # 归并排序 def merge_sort(alist): n = len(alist) # 递归结束条件 if n <= 1: return alist # 中间位置 mid = n // 2 # 递归拆分左侧 left_li = merge_sort(alist[:mid]) # 递归拆分右侧 right_li = merge_sort(alist[mid:]) # 需要2个游标,分别指向左列表和右列表第一个元素 left_point, righ...
0f9780633ca13f512cc670ed45b99119da788611
yuanchangwang/cheshi
/L07 单例模式、魔术方法(__new__、__add__、__str__、__repr__、__call__、__del__)、装饰器、re正则表达式/课件/10.装饰器.py
4,212
4
4
# ### 装饰器 ''' 扩展函数新功能的@ 定义:替换旧函数,返回新函数,在不改变原有代码的前提下,为该函数扩展新功能; 语法:@ (语法糖) ''' # (1) 装饰器的原型 def kuozhan(func): def newfunc(): print("厕所前,蓬头垢面") func()#print("我是个屌丝") print("厕所后,精神气爽") return newfunc def func(): print("我是个屌丝") # func = kuozhan(func) func = kuozhan(func) # func = newfunc <==> func() 就是new...
4a8da306347868372f60a92b1d31b3e420f85c38
yuanchangwang/cheshi
/L16 数据结构与算法/oldboy/algo/sort_algo/shell_sort.py
490
3.6875
4
# coding=utf-8 """ author = jamon """ L = [1, 3, 2, 32, 5, 4] def Shell_sort(L): step = int(len(L)/2) while step > 0: for i in range(step, len(L)): #在索引为step到len(L)上,比较L[i]和L[i-step]的大小 while(i >= step and L[i] < L[i-step]): #这里可以调整step从小到大或者从大到小排列 L[i],L[i...
e9d69c7289ef210bc7bad6cc6355c027003f7c57
yuanchangwang/cheshi
/L06 面向对象初识、三大特性、装饰器/课件/3.动态为类添加成员属性方法.py
1,424
3.5625
4
class Plane(): # 公有成员属性 captain = "王铁杵" # 私有成员属性 __air_sister = 20 # 公有绑定方法 def fly(self): print("飞机会飞") # 公有普通方法 => 只能使用类来调用 def fly2(): print("灰机会飞2") ''' 类只有一个,而对象可以实例化多个 多个对象都可以访问类中的公有成员属性方法 而类无法访问对象中的成员 对象和对象之间彼此独立,资源不共享. 对象可以调用类中公有成员,有使用权,没有归属权(不能修改或者删除) ''' # (1)定义的类访问公有成员属性和方法 print(Plane.capt...
1df84b4a6921cb86bbe0b3a86d1af753752ce0c2
yuanchangwang/cheshi
/L06 面向对象初识、三大特性、装饰器/课件/12.property装饰器.py
1,412
4.0625
4
# ### property 装饰器 ''' 功能:可以把类中的方法变成属性 作用:控制该属性的 获取, 设置 ,删除 的操作 @property 用来获取值 @自定义名.setter 用来设置值 @自定义名.deleter 用来删除值 ''' # 方法一 class MyClass(): def __init__(self,name): self.name = name @property def username(self): return self.name # pass @username.setter def username(self,val): # self.name = val ...
8cf709c0bb6cb2eafff35021d62436f8f9e87a75
yuanchangwang/cheshi
/L10 生产者消费者模型、线程、守护线程、线程锁、信号量、队列、协程、线程池、进程池/课件/1.进程队列.py
1,687
3.5
4
# ### 进程队列 from multiprocessing import Process,Queue # (1) 基本语法 '''先进先出,后进后出''' """ q = Queue() # 1.把数据放到q队列中 put q.put(111) # 2.把书局从队列中拿出来 get res = q.get() print(res) """ # 3.当队列里面的值都拿出来了,已经没有数据的时候,在获取会阻塞 # res = q.get() # 4.get_nowait 无论有没有都拿,如果拿不到,直接报错 # res = q.get_nowait() # 异常处理 : 抑制错误 """ try: code1 code2 e...
f28af27ea4abe94809f6f1ef93e24037e5fa2d21
yuanchangwang/cheshi
/L23_爬虫/04 单线程+异步协程.py
2,305
3.515625
4
# # 基本使用 # import asyncio # # # 定义了一个特殊函数 # async def hello(name): # print("hello " + name) # # return "hello " + name # # # 通过函数名加括号执行这个特殊函数,并不会立即执行,而是返回一个协程对象 # c = hello("oldboy") # # # 实例化一个事件循环对象 # loop = asyncio.get_event_loop() # # # 将协程对象注册到事件循环中, 并执行事件循环 # loop.run_until_complete(c) # # task的使用 # ...
aedc8c58001c6daf877e700e8ac48e026dfe9185
jokipatiaraja/My-Answer-for-Online-Test-Pt.-Jeli-Cipta-Teknologi
/Number 7.py
522
3.75
4
def solutionNumberSeven(myString): # If at any time we encounter 2 # same characters, return false for i in range(len(myString)): for j in range(i + 1,len(myString)): if(myString[i] == myString[j]): return False; # If no duplicate characters # encounter...
6bac3b8e87227b9fcca7f94b3df07d78f18baa05
wutyiwin/practice_python
/2019_code/python_turtle.py
372
3.65625
4
import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") alex = turtle.Turtle() alex.color("blue") alex.shape("turtle") '''print(list(range(5, 60, 2))) alex.up() for col in range(5, 60, 2): alex.stamp() alex.forward(col) alex.right(24) wn.exitonclick()''' alex.forward(50) alex.left(90) alex.forward(50...
8652d45d2d668f0a709c1b4574844c3bdb0bca45
benchizhao/RayTracing-week1-4
/Prism_RayTracing.py
5,658
3.84375
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 09:23:07 2020 This file needs three packages:numpy, matplotlib.pyplt, math. This .py file simulate the behavior of the prism. The geometry of the prism is equilateral triangle. To trace the ray, we use the state of ray to describe. To trace the ray while refrac...
56a5ad9e3a488887d22d183ec38ee49e499baf87
lederpp/roundTwo
/2.18*.py
633
4.0625
4
# Look Over import time timeZone = eval(input("Enter the time zone offset to GMT: ")) currentTime = time.time() totalSeconds = int(currentTime) # total seconds since unix epoch currentSecond = totalSeconds % 60 # obtain current second totalMinutes = totalSeconds // 60 #...
e744db1de9f63cc5ac06a5f424ca5be7257180d3
lederpp/roundTwo
/2.1.py
169
4.25
4
celsius = float(input("Enter a degree in Celsius: ")) fahrenheit = (9 / 5) * celsius + 32 print(celsius, "Celsius converted to Fahrenheit is: ", fahrenheit, "degrees")
1531a7ff475581babb7a77874df1f4e5bb359537
lederpp/roundTwo
/3.2*.py
166
3.5
4
# Look Over import math p1 = eval(input("Enter point 1 (latitude & longitude) in degrees: ")) p2 = eval(input("Enter point 2 (latitude & longitude) in degrees: "))
9f882d1cbd026a009beced486eb00ad1363bcced
liuxing19900528/python_exc
/exc6.py
171
3.734375
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys def fib(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a print fib(int(sys.argv[1]))
c24fddd77f710efbfeb716ef5777f781d50cadb1
jwun95/programmers
/k번째수.py
304
3.71875
4
def solution(array, commands): answer = [] for item in commands: k = array[item[0]-1:item[1]] k.sort() answer.append(k[item[2]-1]) return answer array = [1, 5, 2, 6, 3, 7, 4] commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]] print(solution(array, commands))
2c9738739a82f5c5df387036d6e1dd4b928cecb9
johnnyshi1225/leetcode
/problems/374_Guess_Number_Higher_or_Lower.py
1,135
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: Johnny Shi # Created Time: 2018-10-30 20:25:40 # File Name: 374_Guess_Number_Higher_or_Lower.py # Description: ######################################################################### # T...
1fbe9e22e1320ee0332ec8a9a68baefb7870bf3c
johnnyshi1225/leetcode
/problems/219_Contains_Duplicate_II.py
1,338
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: Johnny Shi # Created Time: 2018-09-26 12:40:57 # File Name: 219_Contains_Duplicate_II.py # Description: ######################################################################### class Solu...
62b9c86e6b28d8906d1bf1e2232af231a9e6497b
johnnyshi1225/leetcode
/problems/283_Move_Zeroes.py
934
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: Johnny Shi # Created Time: 2018-09-05 19:58:31 # File Name: 283_Move_Zeroes.py # Description: ######################################################################### class Solution: ...
946013b211c5d2f35e399817d567c3bd267006a0
johnnyshi1225/leetcode
/problems/21_Merge_Two_Sorted_Lists.py
2,069
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: Johnny Shi # Created Time: 2018-09-14 13:17:08 # File Name: 21_Merge_Two_Sorted_Lists.py # Description: ######################################################################### from simple_...
2cbf1c6911c9561a25e2ab0c000d0afce03fa184
johnnyshi1225/leetcode
/problems/557_Reverse_Words_in_a_String_III.py
704
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: Johnny Shi # Created Time: 2018-09-02 00:28:04 # File Name: 557_Reverse_Words_in_a_String_III.py # Description: ######################################################################### cl...
292488503af3007b2ed526be94cb6037d610e988
johnnyshi1225/leetcode
/problems/94_Binary_Tree_Inorder_Traversal.py
923
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # Author: Johnny Shi # Created Time: 2018-09-29 21:32:07 # File Name: 94_Binary_Tree_Inorder_Traversal.py # Description: ######################################################################### # D...
f9cf6f5f0132cbb5f95ccd8f866d81ec4b10c757
kosiginiv83/Python_course
/homework/5.2/v1/dz_5.py
3,277
4.34375
4
""" Домашнее задание для лекции "Задачки на собеседованиях для продвинутых, с тонкостями языка" Описание 1. Перестроить заданный связанный список (LinkedList) в обратном порядке. Для этого использовать метод `LinkedList.reverse()`, представленный в данном файле. 2. Определить сложность алгоритма. 3...
726d10ac663e78dab7007cebf1d976f8ab6d31e8
dudupo/introcomputerscience
/exercises/ex/ex3/ex3.py
1,835
3.75
4
def create_list(): ret = input() return list() if ret == "" else [ret] + create_list() def contact_list(str_lst): ret = "" for _str in str_lst: ret += _str return ret def average(num_list): _sum = 0 for _number in num_list : _sum += _number return _s...
38277718953e82cc6e7528b9f282e895ade59329
Vladimir-Voronin/Different
/Pycheck/double functions.py
712
3.625
4
def make_min(*,lo,hi): def inner(first,*args): res = hi for arg in (first,) + args: if arg < res and lo < arg < hi: res = arg return max(res,lo) return inner def coloriz(retcolor): color = retcolor print('Your color is ',color) def changecolor...
ada2d570e477873429c60edce00ffed577831d67
cwerner/ml-assignments
/a1/hw1_regression.py
4,942
4.28125
4
# HOMEWORK 1 # ========== # # Call: $ python hw1_regression.py lambda sigma2 X_train.csv y_train.csv X_test.csv # # NOTE: The values of lambda and sigma2 will be input as strings. You must convert # them to a number for your code to work. All numbers should be double-precision # floating-point format. # # Infiles:...
92414ece12e89638fdb7a10a51edb9cc93017367
randyshao/martello-murder-mystery
/data/data.py
2,568
3.53125
4
import json from datetime import datetime def main(): with open('dataset.json') as json_file: data = json.load(json_file) running = True pData = getData(data) while running: choice = str(input("Enter (1) to create personnel tracker files \n Enter (2) to get data sorted by time...
af8add1b54ecc15e4eb4b92a04ea861c2c59e7fb
Redul94/codeforces_python
/025 - 467A - George and Accommodation.py
231
3.5
4
no_of_rooms = int(input()) count = 0 for i in range(no_of_rooms): occupied, available = input().split() occupied = int(occupied) available = int(available) if available-occupied >= 2: count +=1 print(count)
b8b922d7f778919890fa23946934178481ddb8e2
Redul94/codeforces_python
/006 - 282A - Bit.py
160
3.59375
4
no_of_opertion = int(input()) data = 0 for i in range(no_of_opertion): operation = input() if '++' in operation: data += 1 else: data -= 1 print(data)
7c17cdb7c78b9e8ff6a008e879e35957ac3d70c9
Redul94/codeforces_python
/020 - 110A - Nearly Lucky Number.py
171
3.65625
4
n = input() lucky_count = 0 for i in n: if i == '7' or i == '4': lucky_count += 1 if lucky_count == 7 or lucky_count==4: print("YES") else: print("NO")
d474056e38261a18b343471ef980584c4669e0ca
Redul94/codeforces_python
/037 - 443A - Anton and Letters.py
152
3.640625
4
letters = list(input().replace("{","").replace("}","").replace(" ","").split(",")) if letters[0] == '': print(0) else: print(len(set(letters)))
9ddd9714d5b18d053e9fceaea18d10f96af7f715
OctaveC/holbertonschool-higher_level_programming
/0x08-python-more_classes/101-nqueens.py
814
4.0625
4
#!/usr/bin/python3 """ This module defines a chassboard and solves the N queen puzzle """ from sys import argv """ class NQueen: """ """ This class solves a N Queen puzzle for a given N""" """ for ite in range(size): """ if len(argv) != 2: print("Usage: nqueens N") exit(1) try: size = in...
091ad70053e25fc51ac502a53946d36d96219715
OctaveC/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
566
4.375
4
#!/usr/bin/python3 """ This is a module that prints a text with 2 new lines after each of these characters: ., ? and : """ def text_indentation(text): """ This function indents text based on special characters """ if type(text) is not str: raise TypeError("text must be a string") leap = T...
56ee89edd2e08688bbf1dd3851b3394bb709fe9c
OctaveC/holbertonschool-higher_level_programming
/0x0B-python-input_output/5-save_to_json_file.py
250
3.765625
4
#!/usr/bin/python3 """ Module for save_to_json_file """ import json def save_to_json_file(my_obj, filename): """ Writes an Object to a text file. """ with open(filename, "w", encoding="utf-8") as opening: json.dump(my_obj, opening)
9735052368034d7259a96c9f6d7ef09e18d27816
OctaveC/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/4-cities_by_state.py
620
3.5625
4
#!/usr/bin/python3 """ lists all cities from the database hbtn_0e_4_usa """ import sys import MySQLdb if __name__ == "__main__": database = MySQLdb.connect( host="localhost", port=3306, user=sys.argv[1], passwd=sys.arg...
336f7dceecb7159f83843c18544377e9506c7fd1
sondber/krypto
/Jacob/jacob_support.py
1,151
3.5
4
import math def logreturn(price): # takes list of prices, returnsH equal length list of log returnsH returnlist = [0.00] * len(price) for i in range(0, len(price) - 1): # The last entry will always be zero try: returnlist[i] = math.log(price[i + 1]) - math.log(price[i]) except Val...
46d865879d61d5949a9219a58c2572dea5155433
Deepika-Srinivasan/Projects
/Artificial_Intelligence_Problem2/gbfs.py
2,988
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ vanilla breadth first search - relies on Puzzle8.py module """ import Puzzle8 from Puzzle8 import* ### ++++++++++++++++++++++++++++++++++++++++++++++++++++ ### Greedy_Best_First_Search_stats def Greedy_Best_First_Search_stats(): print('Stats') print('Tota...
b6ce8a003aef52b9e83533f123ee75dfde6345fa
Indigo-N-I/CS-115
/project 1/filre_reader.py
2,547
3.515625
4
class FileReader(): def __init__(self, train_times, crew_times): self.in_file_train = open(train_times, 'r') self.in_file_crew = open(crew_times, 'r') self.train_times = [] self.crew_times = [] self.unloading_times = [] self.new_crew_times = [] # to read the trai...
38aaa4ce02ab230639336ac3c64f3bf574252c03
cloudaice/stackview
/stack.py
4,062
3.734375
4
# -*- coding: utf-8 -*- import cmd import sys class stack: def __init__(self): self.lists=[] def put(self,value): self.lists.append(value) def get(self): lenth = len(self.lists) if lenth: print self.lists[lenth-1] del self.lists[lenth-1] else...
183e49a5349c95ef8196ad65754fec65fedf3a35
Invecklad-py/New_start
/What_is_your_name_input.py
295
4.125
4
first_name = input("What's your first name?") last_name = input("What's your last name?") answer = input("So your name is " + first_name + " " + last_name + "?") if answer == "yes": print("Great!") if answer == "no": print("I'm sorry we got that wrong, please try again")