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
c3a8d7a4fcc370604db6bcf49ba87e7986c1bb05
hhe0/Leetcode
/Medium/0700-0799/0729/python/Solution.py
723
3.734375
4
class MyCalendar: def __init__(self): self.calendar = [] def book(self, start, end): """ :type start: int :type end: int :rtype: bool """ flag = True for cal in self.calendar: if not (start >= cal[1] or end <= cal[0]): ...
6e932674e5f3ad6cb9d274c3f1f6842b3538978f
hhe0/Leetcode
/Easy/0500-0599/0500/python/Solution.py
975
3.71875
4
class Solution: def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ res = [] letter = { 'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j'...
050e956c1b1c6cb040b3ca933748a6ff6f913a34
hhe0/Leetcode
/Easy/0200-0299/0237/python/Solution.py
587
3.8125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val...
9cc0c5337fe6ce1fb633386c148830fc64946115
hhe0/Leetcode
/Easy/0400-0499/0414/python/Solution.py
484
3.984375
4
class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ nums_list = list(set(nums)) nums_list.sort(reverse=True) # print(nums_list) if len(nums_list) >= 3: return nums_list[2] elif len(nums_list)...
b317a98ba5124c542782bf4580f8efa639d38af9
hhe0/Leetcode
/Easy/0800-0899/0867/python/Solution.py
419
3.59375
4
class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ res = [] for i in range(len(A[0])): res.append([]) for j in range(len(A[0])): for k in range(len(A)): res[j].appe...
76037551bb6a9c165f587f8157ed381a951534e7
hhe0/Leetcode
/Easy/0100-0199/0141/python/Solution.py
648
3.921875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ list = [] while head: if id(...
be8e9f918cc4e3ae60e120dd82d6688b4f69bfd3
Zahidsqldba07/code-signal-solutions-GCA
/arcade/the_core/027-magicalWell.py
1,073
3.625
4
def magicalWell(a, b, n): x = 1 total = 0 if a == b == n: return 1 while x <= n: total += a * b x += 1 a += 1 b+= 1 return total """ You are standing at a magical well. It has two positive integers written on it: a and b. Each time you cast a magic mar...
a92aeb154e664c80a2df7375b3e17767485b7aa2
Zahidsqldba07/code-signal-solutions-GCA
/arcade/intro/035-firstDigit.py
607
4.03125
4
def firstDigit(inputString): for d in inputString: if d.isdigit(): return d """ Find the leftmost digit that occurs in a given string. Example For inputString = "var_1__Int", the output should be firstDigit(inputString) = '1'; For inputString = "q2q-q", the output should be firstDigit(inputSt...
6a18f0968ce70719e8ffc2f234f2d0af07d98366
Zahidsqldba07/code-signal-solutions-GCA
/challenges/001-companyBotStrategy.py
2,609
3.84375
4
def companyBotStrategy(trainingData): a = 0 count = 0 for x,y in trainingData: if x>= 0 and y == 1: a += int(x) count += 1 if count > 0: return a/count return 0 """ Each CodeSignal Company Bot is trained by engineers from that specific company. The w...
a185c1f5b1101ae320e5781d1a73548e270a6f57
Zahidsqldba07/code-signal-solutions-GCA
/GCA/2mostFrequentDigits.py
1,053
4.125
4
def mostFrequentDigits(a): #Tests # a: [25, 2, 3, 57, 38, 41] ==> [2, 3, 5] # a: [90, 81, 22, 36, 41, 57, 58, 97, 40, 36] ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # a: [28, 12, 48, 23, 76, 64, 65, 50, 54, 98] ==> [2, 4, 5, 6, 8] """ Given an array of integers a, your task is to calculate the digits that occur the mos...
da574aa59126be1b3964190559c478a296f5b4a9
Zahidsqldba07/code-signal-solutions-GCA
/arcade/intro/026-evenDigitsOnly.py
515
4.1875
4
def evenDigitsOnly(n): n = [int(i) for i in str(n)] for d in n: if d%2 != 0: return False return True """ Check if all digits of the given integer are even. Example For n = 248622, the output should be evenDigitsOnly(n) = true; For n = 642386, the output should be evenDigitsOnly(n) =...
8d9c2d0492cfb620649087e4e007031357eee827
Zahidsqldba07/code-signal-solutions-GCA
/GCA/2countWaysToSplit.py
1,719
4.1875
4
def countWaysToSplit(s): listS= list(s) # print (listS) lenS = len(listS) count = 0 for i in range(1,lenS): for j in range(i+1, lenS): ab = s[0:j] bc = s[i:lenS] ca = s[j:lenS] + s[0:i] # print("AB is :",ab,"BC is:",bc,"CA is:",ca) ...
b5224f264e6e51d57eacf32a54564688eed5c143
Zahidsqldba07/code-signal-solutions-GCA
/arcade/intro/09-allLongestStrings.py
1,206
4.125
4
""" Given an array of strings, return another array containing all of its longest strings. Example For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. Input/Output [execution time limit] 4 seconds (py3) [input] array.string inputArray A n...
79567f8955ccc289882de1515392e6f204dccccf
hsyao/algorithm
/模拟训练/day03/队列.py
670
4.0625
4
""" """ class Queue(object): """队列""" def __init__(self): self.items = [] def is_empty(self): """判断是否为空""" return self.items == [] def enqueue(self, item): """进队列""" self.items.append(item) def dequeue(self): """出队列""" return self.items....
e73feb9f609233209f905dfe970701b3e995db7b
minrk/sympy
/sympy/core/sets.py
26,995
3.609375
4
from basic import Basic from singleton import Singleton, S from evalf import EvalfMixin from numbers import Float from sympify import _sympify, sympify from sympy.mpmath import mpi, mpf from containers import Tuple class Set(Basic): """ Represents any kind of set. Real intervals are represented by the In...
ac6519b87bdd7461be54798c7a74088110759986
kampetyson/python-for-everybody
/8-Chapter/Exercise6.py
829
4.3125
4
''' Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after t...
b3bc71dff70c5bf4e21e0bc4e2af3f826c41406d
kampetyson/python-for-everybody
/2-Chapter/Exercise3.py
212
4.15625
4
# Write a program to prompt the user for hours and rate perhour to compute gross pay. hours = int(input('Enter Hours: ')) rate = float(input('Enter Rate: ')) gross_pay = hours * rate print('Pay:',gross_pay)
789ffe90d787d656159bbefc7dfeafb7bd02a287
kampetyson/python-for-everybody
/7-Chapter/Exercise2.py
1,108
4.15625
4
# Write a program to prompt for a file name, and then read # through the file and look for lines of the form: X-DSPAM-Confidence: 0.8475 # When you encounter a line that starts with “X-DSPAM-Confidence:” # pull apart the line to extract the floating-point number on the line. # Count these lines and then compute the...
9b3edb65b838b153430aa177b1609260908e98b4
kampetyson/python-for-everybody
/7-Chapter/Exercise1.py
614
4.40625
4
# Write a program to read through a file and print the contents # of the file (line by line) all in upper case. Executing the program will # look as follows: # python shout.py # Enter a file name: mbox-short.txt # FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008 # RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPRO...
4e57c338886649811f9c6b7e32dfe501b2f18adb
kampetyson/python-for-everybody
/2-Chapter/Exercise1.py
121
3.59375
4
# Exercise 1: Type the following statements in the Python interpreter to see what they do: print(5) x = 5 print(x + 1)
307412a808c0c66f0806f253998310b6516d6e8f
RalphMul/DataScientistCourseDS
/zelfstudie/Exercise_List2.py
1,334
3.84375
4
'''' Autor: Ralph Mul File name: Exercise_List2 Info: This exersise is created based on the Python Data Structure Exercise for Beginners assignment as stated in https://pynative.com/python-data-structure-exercise-for-beginners/ Date: 15-08-2020 Version 0.1 ''' #assignment: Given an input list removes the element...
6b38d04135eafbbd3ff8e0b260bb1eecbc9abf2a
RalphMul/DataScientistCourseDS
/COVID-19/Covid-19.py
1,073
3.734375
4
""" Autor: Ralph Mul File name: Zelf study Covid Info: first attemt to read csv file using panda https://stackoverflow.com/questions/16503560/read-specific-columns-from-a-csv-file-with-csv-module Date: 25-09-2020 Version 0.1 """ import pandas as pd Covidfile = pd.read_csv('COVID-19_casus_landelijk_RM.csv', sep=';') '''...
6c9f5c477b4221237ecaca5361da66d3e3a753b0
megatran/selflearning_openCV_ComputerVision
/03-image-manipulation/026-edge_detection_image_gradients.py
1,381
3.5
4
import cv2 import numpy as np #load input image source_input = "/Users/nhant/Google Drive/OnlineLearning/selflearning_CV_with_Python/practice_sources/images/input.jpg" image = cv2.imread(source_input, 0) height, width = image.shape #extract sobel edges (horizontal and vertical, ksize is kernel size) sobel_x = cv2.S...
c71f05a7cf2d3c6f845168dfc7815aad1b3c8129
megatran/selflearning_openCV_ComputerVision
/04-Image-segmentation/034-line_detection.py
1,245
3.71875
4
""" cv2.HoughLines(binarized/threshold image, rho accuracy, theta accuracy, threshold) Threshold here is the minimum vote for it to be considered a line """ import cv2 import numpy as np source_input = "/Users/nhant/Google Drive/OnlineLearning/selflearning_CV_with_Python/practice_sources/images/soduku.jpg" image = cv2....
83f242980b025de16dce959ba38ea7bc6cf58d2f
spradnyesh/misc-tutorials
/python/miscTools/space2underscore.py
969
3.59375
4
#!/usr/bin/env python ########################## # Module: space2underscore.py # Author: Pradnyesh Sawant # Date: 25Apr2007 # Version: 0. """ converts space to underscores in filenames in given directory use os.walk() """ # Log: # # ToDo: # ########################## import os import sys def main(dir): if "~" ...
8bdcbabcf302626619ffb3b522e67cf3707d266f
spradnyesh/misc-tutorials
/python/miscTools/shredder.py
1,156
3.75
4
#!/usr/bin/env python ########################## # Module: shredder.py # Author: Pradnyesh Sawant # Date: 05Jan2008 # Version: 0.2 """ shred files: basically, replace file contents with random chars and then delete the file ;) """ # Log: # 24Jan2007: create # 05Jan2008: traverse directories, and shred all files within...
21045c28a2f3a5e004a2b42b3d6f7d04aa122e8a
usmansabir98/AI-Semester-101
/PCC Chapter 5/5-5.py
779
4.125
4
# 5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elifelse # chain. # • If the alien is green, print a message that the player earned 5 points. # • If the alien is yellow, print a message that the player earned 10 points. # • If the alien is red, print a message that the player earned 15 poin...
7eed10921a91af809614162073c157991d7b1f74
BUSA342-184/f08-dicts-jayreset
/fromto.py
1,956
3.921875
4
#! opt/bin/python """ Read text file 'mbox-short.txt', separate emails that are 'From' and 'To', and print the usernames and hosts and their counts categorized by From Users, From Hosts, To Users, and To Hosts """ emailList = [] fromUser = {} fromHost = {} toUser = {} toHost = {} # open text file as variable emails w...
3f6effd1c5c1c93e6bcddc276e0a345a3bfc19e8
jonathondown89/about_me
/messing.py
636
3.984375
4
name = "Jonathon Down" age = 35 height = 74 #inches weight = 180 #pounds weight_in_kilo = weight * 0.453592 #lbs into kilo (1) height_in_cm = height * 2.54 #inches into cm (1) meter = height / 39.3701 #inches in meter (1) height_in_meters = height_in_cm / 100 #cm into meter (100) print(f"Let's talk about {name}.") p...
f6ece0a48885a582c34a748fbf78cb247059754d
DennisPing/Reinforcement-Learning
/escape-room.py
3,721
3.5
4
from gym import Env from gym.spaces import Discrete, Box import numpy as np import random import matplotlib.pyplot as plt import math # Reference 1: https://www.youtube.com/watch?v=JNKvJEzuNsc # Reference 2: https://www.youtube.com/watch?v=bD6V3rcr_54 class MazeEnv(Env): def __init__(self): self.action_s...
4492aad1637739e24cfc3c1078d5aac1cf792764
pradeepradyumna/Python
/Calculator.py
3,191
3.96875
4
from tkinter import * root = Tk() root.title("Pradeep's Calculator") e = Entry(root, width=40, borderwidth=5) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def button_click(number): current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def buttonClear_clic...
b872342ca0a173306fd0e9e0d1fb4dd0974f5df1
DeliveryBoyy/wizard_warrior_rogue
/game.py
2,216
3.796875
4
""" Main game script. Runs the game for the user. """ import re from exceptions import EnemyDown, GameOver from models import Player, Enemy from settings import COMMANDS def play(): """ Main game function. Handles the user and the game process. """ # Create the player object with the name from input...
126b688bdb1ce4e02353a534a451aba70e743a4d
zainaraza43/Sorting-Algorithm-Visualizer
/SortingAlgorithmVisualizer.py
5,975
3.578125
4
import pygame import random import time pygame.init() class Bar: def __init__(self, value, colour): self.value = value self.colour = colour # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) #Font font = pygame.font.SysFont("arial", 24) # Random numbers to be...
615b52435d98085619b08c26ddcded3acc23e13b
ahujatarang/CodePython
/Sum_of_Two_Numbers.py
164
3.90625
4
n1 = int(input("First number: ")) n2 = int(input("\nSecond number: ")) sum = int(n1) + int(n2) print("The sum of {0} and {1} is {2}" .format(n1, n2, sum))
559df058a37489c076d8614fe585e4ad5816f40b
mpc-msri/EzPC
/Athos/Networks/LogisticRegression/LogisticRegressionTrain.py
2,697
3.8125
4
""" A logistic regression learning algorithm example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ** Original source code from above modified for ...
4de3e14538efe6037ec64128ff8d3299c1fcdbcc
falabretti/uri-online-judge
/python3/beginner/1173.py
184
3.609375
4
entrada = int(input()) lista = [] for index in range(10): lista.append(entrada) entrada *= 2 for index in range(10): print("N[{}] = {}".format(index, lista[index]))
ddefabf13d9b97a0e87184997591fc25f0e9de1d
falabretti/uri-online-judge
/python3/strings/1243.py
1,142
3.625
4
while True: try: frase = input().split() qnt = len(frase) soma = 0 cont = 0 for i in range(qnt): word = True tam = len(frase[i]) for j in range(tam): if(frase[i][j].isalpha() or frase[i][j] == "."): ...
66a72ec37f75999ca7a75dda65ed1e8c432666bd
falabretti/uri-online-judge
/python3/beginner/1146.py
222
3.84375
4
while(True): entrada = int(input()) if(entrada == 0): break for index in range(1, entrada + 1): if(index == entrada): print(index) else: print(index, end=" ")
709635577b5050decbbb86754f332ca655d627a0
falabretti/uri-online-judge
/python3/beginner/1005.py
195
3.609375
4
valor_um = float(input()) valor_dois = float(input()) valor_um = valor_um * 3.5 valor_dois = valor_dois * 7.5 media = float((valor_um + valor_dois) / 11) print("MEDIA = {:.5f}".format(media))
3edab82e6bd8be7d18ac4c8780c2a45e31a49347
falabretti/uri-online-judge
/python3/beginner/1150.py
218
3.625
4
x = int(input()) while(True): z = int(input()) if(z > x): break soma = x cont = 1 while(True): soma = soma + x + 1 x = x + 1 cont = cont + 1 if(soma > z): break print(cont)
add7413b445cb23b69f30373d1084f7336a62734
falabretti/uri-online-judge
/python3/beginner/1040.py
548
3.65625
4
a, b, c, d = input().split(" ") a = float(a) b = float(b) c = float(c) d = float(d) media = (a * 2 + b * 3 + c * 4 + d * 1) / 10 print("Media: {:.1f}".format(media)) if(media >= 7): print("Aluno aprovado.") elif (media < 5): print("Aluno reprovado.") else: print("Aluno em exame.") exame = float(input(...
a10e228cbf0e6600e16aca95408f816c830649a1
falabretti/uri-online-judge
/python3/strings/1234.py
574
3.75
4
while True: try: entrada = input() upper = True tam = len(entrada) saida = [] for i in range(tam): if(entrada[i].isalpha()): if(upper): saida += entrada[i].upper() upper = False else...
85b90485f1864159641cfa84e93ca7b811a9593e
falabretti/uri-online-judge
/python3/beginner/1153.py
113
3.53125
4
entrada = int(input()) fat = entrada for index in range(entrada - 1, 0, -1): fat = fat * index print(fat)
91bbf5e673109d04a4c3e848ece6878a7b170a11
falabretti/uri-online-judge
/python3/beginner/1048.py
474
3.625
4
salario = float(input()) if(salario <= 400): reajuste = 0.15 elif(salario > 400 and salario <= 800): reajuste = 0.12 elif(salario > 800 and salario <= 1200): reajuste = 0.10 elif(salario > 1200 and salario <= 2000): reajuste = 0.07 elif(salario > 2000): reajuste = 0.04 print("Novo salario: {:.2f}"...
95d86665b106facfc38e4e57c7e4f04159d0392d
falabretti/uri-online-judge
/python3/beginner/1164.py
324
3.625
4
testes = int(input()) for caso in range(testes): entrada = int(input()) soma = 0 for index in range(1, entrada): if(entrada % index == 0): soma += index if(soma == entrada): print("{} eh perfeito".format(entrada)) else: print("{} nao eh perfeito".format(entrad...
1f60fd7e54a6071d3c081bc72752d0f8cb741b0b
atk81/SocketProgramming
/udp-eco-client.py
559
3.6875
4
#Write a program in which client send a data and server send the data in reverse order.. import socket s = socket.socket(socket.AF_INET ,socket.SOCK_DGRAM) while True : s.sendto('',('',1111)) data , addr = s.recvfrom(4096) print data message = str(raw_input("Enter the str to reverse (Enter q or Q t...
f0b0d6d4f6d590c287ebb5bf776e8b2da07dbb82
errpv78/Scene-Depiction
/DesktopApp/app.py
667
3.578125
4
from tkinter import * root = Tk() root.title("Video Player App") enter_url = Label(root, text = "Enter Url: ") enter_url.grid(row=1, column=1) url = Entry(root, width=40, bg="white", fg="grey", borderwidth=5) # url.insert(0, 'Enter Url') url.grid(row=1, column=2) or_label = Label(root, text = "OR") or_lab...
4d517f9cfb611d3a9f8a1afe9a38e04f28dbac3f
Freegle1643/leetforfun
/399-mid-Evaluate_Division-180810.py
1,959
3.9375
4
""" 399. Evaluate Division Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0. Example: Given a / b = 2.0, b / c = 3.0. queries are: a / c = ...
5e05e20f64222daa046a69bf13eb645434630a93
Freegle1643/leetforfun
/535-mid-Encode_and_Decode_TinyURL-180729.py
2,371
4.0625
4
""" 535. Encode and Decode TinyURL Note: This is a companion problem to the System Design problem: Design TinyURL. https://leetcode.com/discuss/interview-question/system-design/ https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/ TinyURL is a URL shortening service where y...
b72582993e17dbc48990094275a083ddbd365033
Freegle1643/leetforfun
/temp/t209.py
2,376
3.78125
4
""" 209. Minimum Size Subarray Sum Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length ...
d548edac45eb49fdb9971205bfb9c1facaa353ce
Freegle1643/leetforfun
/136-easy-Single_Number-180722.py
883
3.78125
4
""" 136. Single Number Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4...
061f9ee9ae4710ed97641f1234d0ddcb3e9112f9
Freegle1643/leetforfun
/416-mid-Partition_Equal_Subset_Sum-180728.py
2,066
3.71875
4
""" 416. Partition Equal Subset Sum Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input: [1, 5...
74b048a4b88d5d604315230b4f925b276f631be8
Freegle1643/leetforfun
/141-easy-Linked_List_Cycle-180717.py
1,031
3.625
4
""" 141. Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? Note: 1. If two runner running at different constant speed on a circle track, they will eventually meet each other. See more on https://leetcode.com/problems/linked-list-cycle/so...
cbd852a53a64037acf07087184c0a18df246de43
Freegle1643/leetforfun
/209-mid-Minimum_Size_Subarray_Sum-180721.py
1,244
3.828125
4
""" 209. Minimum Size Subarray Sum Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length...
27df9ebccc2a65c42f04dea34b038be1295be348
Freegle1643/leetforfun
/070-easy-Climbing_Stairs-180730.py
2,342
4
4
""" 70. Climbing Stairs You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. ...
d7ce4d4494a298fba0f97f0b261d1f1d56ba6440
Freegle1643/leetforfun
/306-mid-Additive_Number-180801.py
1,769
4.0625
4
""" 306. Additive Number Additive number is a string whose digits can form additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits '0'-'9', ...
9d69d63050c8a8cc4f84af8003da2700461f1fbc
Freegle1643/leetforfun
/004-hard-Median_of_Two_Sorted_Arrays.py
1,520
4
4
""" 4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0...
8fed0d6bff664401a69963a9167cfc66764a5b64
chaglare/learning_python
/environments/codetest/palindrome2.py
110
4.125
4
s = input("Enter the value : ") reverse = s[:: -1] if( s == reverse ): print("Yes") else: print("No")
f7e1cb8d9e860af0b49892cdfc0a3a077103e771
hoanghapham/alien_invasion
/player_input.py
2,263
3.578125
4
"""Control interactions between human & game""" import sys import pygame from bullet import Bullet import game_functions as gf def check_play_button(ai_settings, screen, stats, scoreboard, play_button, ship, aliens, bullets, mouse_x, mouse_y): """Start new game when player click play. Reset the field""" ...
817ad71245bea3124fc206d0e876d79d317b3995
BugChef/yandex_alghoritms
/sprint1/neighbors.py
1,231
3.953125
4
""" Дана матрица. Нужно написать функцию, которая для элемента возвращает всех его соседей. Соседним считается элемент, находящийся от текущего на одну ячейку влево, вправо, вверх или вниз. Диагональные элементы соседними не считаются. Например, в матрице A: [[1, 2, 3], [...
7ae6e47d2a495ea1f9233b772597f1c203c93ceb
BugChef/yandex_alghoritms
/sprint6/BFS.py
716
3.6875
4
from queue import SimpleQueue n, m = [int(x) for x in input().split()] graph = [[] for _ in range(n + 1)] colors = ['white' for _ in range(n + 1)] for _ in range(m): u, v = [int(x) for x in input().split()] graph[u].append(v) graph[v].append(u) start_vertex = int(input()) for g in graph: g.sort() ...
660e1fea0e26bc30738994c22f0929348a553c82
BugChef/yandex_alghoritms
/sprint1/chaotic_weather.py
1,680
3.921875
4
""" Метеорологическая служба вашего города решила измерять нестабильность погоды новым способом. Назовём хаотичностью погоды за n дней число дней, в которые температура строго больше, чем в день до (если такой существует) и в день после текущего (если такой существует). Например, если за 5 дней температура воздуха сост...
25cfcaa8460e263e0ba9ab8d1cebc693ea9d207f
BugChef/yandex_alghoritms
/sprint0/create_playlist.py
555
3.546875
4
import sys def split_numbers_by_space(string_with_spaces) -> [int]: string_number_list = string_with_spaces.split() number_list = list(map(int, string_number_list)) return number_list n = int(input()) if n < 1: print('') sys.exit() russian_id_list = split_numbers_by_space(input()) foreign_id_lis...
6763b228acc2ec59a592466dd97427ef3bfacc72
BugChef/yandex_alghoritms
/sprint8/reverse_string.py
66
3.578125
4
string = input().split() string.reverse() print(' '.join(string))
cb8c39dde238b4a9d52112fb6b62bd3e512ccaff
BugChef/yandex_alghoritms
/sprint1/function_value.py
1,029
3.796875
4
""" Младший брат Аллы Вася делает тест по математике: вычисляет значение функций в различных точках. Стоит отличная погода, и друзья зовут Васю гулять. Но мама разрешила мальчику пойти на улицу только после того, как он закончит тест. К сожалению, Вася пока не умеет программировать. Зато Алла умеет. Она решила помочь б...
9e49850ea348c0dd67ab880cad9ab1a32762494f
BugChef/yandex_alghoritms
/sprint5/sift_down_heap.py
592
3.671875
4
class Node: def __init__(self, left=None, right=None, value=0): self.value = value self.right = right self.left = left def sift_down(heap, idx) -> int: left = 2 * idx right = 2 * idx + 1 if len(heap) - 1 < left: return idx if right <= len(heap) - 1 and heap[left] ...
9941c490487a0c1ba49be84f1c8f206df031b25f
BugChef/yandex_alghoritms
/sprint3/merge_sort.py
1,341
3.984375
4
def merge(arr: list, left: int, mid: int, right: int) -> list: left_copy = arr[left: mid + 1] right_copy = arr[mid + 1: right + 1] left_copy_index = 0 right_copy_index = 0 sorted_index = left while left_copy_index < len(left_copy) and right_copy_index < len(right_copy): if left_copy[le...
59577c62d49f1f69d9791da54d23fb13bbfe2ca2
BugChef/yandex_alghoritms
/sprint5/bst_insertion.py
385
3.828125
4
class Node: def __init__(self, left=None, right=None, value=0): self.value = value self.right = right self.left = left def insert(root: Node, key: int) -> Node: if root is None: return Node(value=key) if key < root.value: root.left = insert(root.left, key) else...
7b44530026c6d21f0badad1ac50ead41384ca721
yuemeiss/database
/数据库交互练习/f深浅拷贝.py
441
3.90625
4
import copy a = [1,2,3,4,['a','b']] b = a #引用,除非直接给a重新复制,否则a变则b变,b变则a变。 c = copy.copy(a) #浅复制,只会拷贝父对象,不会拷贝父对象中的子对象,所以若a的子对象则c变,但是父对象变c不会变 d = copy.deepcopy(a) #深拷贝,完全拷贝,完全独立于原对象,a变也不变 a.append(5) a[4].append('c') print(a) print(b) print(c) print(d)
576434eb83be86d2c24865bd76e08c7b6a31cc21
njsss/algs4-py
/graph_SymbolGraph.py
978
3.546875
4
# Symbol graphs: # Vertex names are strings # A specified delimiter separates vertex names # Each line reprents a set of edges, # The number of vertices V and the number of edges E # are both implicitly defined. from graph import Graph class SymbolGraph(object): g = '' def __init__(self, fn, sp): self....
d2476bad7c1f14da138107b8f7b1c1f2a1699983
cindyywang/61a18fa
/lec/ex2.py
329
3.625
4
"""Generalization.""" def make_adder(n): """Return a function that takes one argument K and return K + N. >>> add_three = make_adder(3) >>> add_three(4) 7 """ def adder(k): return k + n return adder def square(x): return x * x def triple(x): return 3 * x def composel(f, g): def h(x): return f(g(x)) ...
65aa10ee3c4663585968ea9a6351af7b2617ff03
jnikkiyoke/Tech-Academy-Drills
/python/drill 3; refactored.py
1,811
3.734375
4
# Python 2.7.1 # # Author: Nikki Yoke # # Edited by: Dylan D. (modified code and created function) # # Purpose: The Tech Academy, Drill 3 # Create a program that finds the current # time in multiple timezones to determine if # a branch of a store is cur...
5d5583d3e6db76bddef5b10d282039912231b183
atkabyss/1G_python
/遊び/タイマー カウントダウン.py
234
3.828125
4
from time import sleep target_time = int(input("時間を設定してください>")) def down_timer(secs): for i in range(secs, -1, -1): print(i) sleep(1) print("時間です!") down_timer(target_time)
e7ac11eb81d166ce716385f295ce1c23d1bccd65
atkabyss/1G_python
/テスト/k019c1068_石井恭輔_Test-5.py
285
3.609375
4
a = int(input("年齢>")) b = int(input("会員証(1:有 2:無)>")) if a >= 18 and b == 1: print("料金: 1600円") elif a >= 18 and b == 2: print("料金: 2400円") elif a < 18 and b == 1: print("料金: 800円") elif a < 18 and b == 2: print("料金: 1200円")
bdd4a634cb4733796279b3a0d83123da38b682d8
atkabyss/1G_python
/Exam/Exam_06 条件分岐if文/k019c1068_石井恭輔_Exam-6_3.py
160
3.796875
4
password = input("入力>") if len(password) < 8: print("短すぎます") elif len(password) >= 13: print("長すぎます") else: print("O.K.")
04bd7376c90b6e4d2543ed6c7a41e5a96efbadad
atkabyss/1G_python
/テスト/k019c1068_石井恭輔_Test-2.py
124
3.53125
4
a = input("入力>") b = a.split(",") d = 0 for c in b: d = int(c) + d d = d / len(b) print("平均:" + str(d))
11fa4ea05c5651c6390752472d6e6f6b8e9a7ac1
atkabyss/1G_python
/Exam/Exam_05 繰り返しfor文/k019c1068_石井恭輔_Exam-5_3.py
95
3.6875
4
animal = ['rat','ox','tiger','rabbit','dragon'] for p in animal: print(p+':'+str(len(p)))
6b5e5964c2de188750784e07763cae336e7a3ce4
Mugwe/DAY-1
/primeno_tests.py
641
3.609375
4
import unittest import day1.prime_no_solution from primenumbers class testprimenumbers(unittest.Testcase): def test_if_number_is_integer(self): answer = primenumbers("tracy") self.assertEqual(answer, "Enter an integer") def test_if_number_is_divisible_by_2(self): self.assertTrue(4%2 ==...
8f6f7f0c6308b83fa51fbdf2f2e00717f736b63e
CISVVC/test-ZackaryBair
/dice_roll/main.py
2,080
4.28125
4
""" Assignment: Challenge Problem 5.13 File: main.py Purpose: Rolls dice x amount of times, and prints out a histogram for the number of times that each number was landed on Instructions: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An...
e3bb84a0c62df7f5b729901237419e87611c869f
Felix-xilef/Curso-de-Python
/Aulas/Aula16C.py
152
3.53125
4
pessoa = ('Gustavo', 39, 'M', 99.88) print(pessoa) del(pessoa) # del() - apaga uma variável da memória input('\n\nPressione <enter> para continuar')
24edf2f1fedc793d4efb824891a4a72dfcc4094e
Felix-xilef/Curso-de-Python
/Desafios/Desafio83.py
348
3.75
4
abreP = [] fechaP = list() for i in input('\n\tDigite uma expressão matemática: '): if i == '(': abreP.append(i) elif i == ')': fechaP.append(i) if len(abreP) == len(fechaP): print('\n\tSua expressão é válida!') else: print('\n\tSua expressão não é válida!') input('\n\nPressione <enter...
ba4a74c8e4180d250c7de4f40c67e3ada1a4cc78
Felix-xilef/Curso-de-Python
/Desafios/Desafio63.py
463
3.703125
4
n = int(input('\n\tDigite a quantidade de termos da Sequência de\n\tFibonacci você deseja mostrar: ')) print('\n\t',end='') for i in range(0, n): print('~~~~~',end='') print('~~~\n\t0 -> 1 -> ',end='') i = 2 n0 = 0 n1 = 1 while i < n: n2 = n0 + n1 print('{} -> '.format(n2),end='') n0 = n1 n1 = n2 ...
bf90192742f98f4cd9f9ee43c72f1694a63d922c
Felix-xilef/Curso-de-Python
/Aulas/Aula20C.py
200
3.53125
4
def soma(a, b): print(f'a = {a}; b = {b}') print(f'a + b = {a + b}') # Programa Principal soma(4, 5) soma(8, 9) soma(b=2, a=1) soma(a=4, b=1) input('\n\nPressione <enter> para continuar')
94d2efc5d288f7be2d6a2347a11c0334b9df77ea
Felix-xilef/Curso-de-Python
/Desafios/Desafio44.py
940
3.796875
4
from os import system preco = float(input('\n\tDigite o preço normal do produto: ')) pagamento = int(input(""" \t ----------------------------------------- \t | OPÇÕES DE PAGAMENTO | \t ----------------------------------------- \t | [1] À vista em dinheiro/cheque | \t | [2] À vista no cartão ...
fda2f62076b4b418e02dcc1cd9448f2f9b00f625
Felix-xilef/Curso-de-Python
/Aulas/Aula12A.py
430
3.8125
4
from os import system nome = input('\n\tDigite seu nome: ').strip().split()[0].capitalize() if nome == 'Felix': print('\n\tQue nome bonito!') elif nome == 'Pedro' or nome == 'Maria' or nome == 'Paulo': print('\n\tSeu nome é bem popular no Brasil!') elif nome in 'Ana Cláudia Jéssica Juliana': print('\n\tBel...
8260ff0f9237df0e336c805c8ad0567702b0d167
Felix-xilef/Curso-de-Python
/Desafios/Desafio86.py
384
3.828125
4
from auxiliar import receberInt matriz = [[], [], []] for i in range(0, 3): for j in range(0, 3): matriz[i].append(receberInt()) for i in range(0, 3): print(f'\n\t+{"-" * 17}+', end='\n\t') for j in range(0, 3): print(f'|{matriz[i][j]:^5}', end='') print('|' if i < 2 else f'|\n\t+{"-" ...
8a8e1abb693c8a95423956e7587082f398c73ced
Felix-xilef/Curso-de-Python
/Desafios/Desafio75.py
629
3.953125
4
valores = (int(input('\tDigite o 1° número inteiro: '))), (int(input('\tDigite o 2° número inteiro: '))), (int(input('\tDigite o 3° número inteiro: '))), (int(input('\tDigite o 4° número inteiro: '))) if 9 in valores: aux9 = valores.count(9) else: aux9 = 0 if 3 in valores: aux3 = f'Posição do primeiro númer...
c2b42de08a78ccfb1987b0d48a96d2b0fa5b70fc
Felix-xilef/Curso-de-Python
/Desafios/Desafio15.py
258
3.671875
4
import os print('Digite\n') dias = int(input('\tQuantidade de dias que o carro foi alugado: ')) km = float(input('\tQuantidade de kilometros (km) percorridos: ')) print('\nPreço a pagar = R$ {:.2f}\n'.format((dias * 60) + (km * 0.15))) os.system('pause')
7b810e03fc9ed93a3cad44074b3fb62c02b6565a
Felix-xilef/Curso-de-Python
/Aulas/Aula20E.py
278
3.90625
4
def dobra(lst): for i in range(0, len(lst)): lst[i] *= 2 # como é pasado uma lista toda alteração feita na lst alterará a principal # Main valores = [6, 3, 9, 1, 0, 2] print(valores) dobra(valores) print(valores) input('\n\nPressione <enter> para continuar')
2471f37148c4952a59bd78ddc148600bad17827b
Felix-xilef/Curso-de-Python
/Aulas/Aula16A.py
942
3.84375
4
# Tupla - (declaração com ou sem parênteses) como um array porém imutável e podem ter dados de diferentes tipos lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim') # lanche = 'Hambúrguer', 'Suco', 'Pizza', 'Pudim' print(lanche) print(lanche[1]) print(lanche[-2]) # indices negativos começam do último elemento e terminam ...
fa1d5e3f2c417c538fdf715611a6428ae585cd70
Felix-xilef/Curso-de-Python
/Aulas/Aula19C.py
468
4
4
estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = input('\n\tUnidade Federativa: ').strip() estado['sigla'] = input('\tSigla: ').strip().upper() brasil.append(estado.copy()) # .copy() - retorna uma cópia do dicionário (não é possível fazer fatiamento em dicionário) - para não criar víncul...
bdf85d504cc36970032b9e5675b9b44b0f413d5b
Felix-xilef/Curso-de-Python
/Desafios/Desafio57.py
336
3.625
4
sexo = input('\n\tDigite o seu sexo (M / F): ').strip().lower() while (sexo != 'm') and (sexo != 'f'): sexo = input(""" \t !!!!! SEXO INVÁLIDO !!!!! \t Digite: \t • M para masculino \t • F para feminino \tDigite o seu sexo (M / F): """).strip().lower() input('\n\nPressione <enter> para c...
8f08e7b83dfbc05154f1c92175235fd4a4c78c40
Felix-xilef/Curso-de-Python
/Aulas/Aula17B.py
360
3.796875
4
valores = [] # ou valores = list() # valores.append(5) # valores.append(9) # valores.append(4) for i in range(0, 5): valores.append(int(input('\tDigite um valor: '))) for c, i in enumerate(valores): print(f'\n\tNa posição {c} encontrei o valor {i}!', end='') print('\n\n\tCheguei ao final da lista') input('\...
3b4e0cfe77aee4f7b2352907bfc08d7e2d80bc6e
Felix-xilef/Curso-de-Python
/Aulas/Aula15A.py
481
3.828125
4
# n = s = 0 # while n != 999: # n = int(input('\tDigite um número: ')) # s += n s = 0 while True: n = int(input('\tDigite um número: ')) if n == 999: break # break interrompe o loop no qual está contido s += n # print('\n\tA soma vale {}'.format(s)) print(f'\n\tA soma vale {s}') # nova for...
3bfbcf3ff45b55c5018f1c93bea499977f1b0083
eloyrutman/manejo-de-listas
/listas manejo teorico.py
565
4.03125
4
lista = ["jose", "jose" , 33 , 56.7 , True, "jose@gmail.com"] #Agrega elemento al final de la lista lista.append("casado") #Agrega más de un elemento al final de la lista lista.extend([44, "Jardin"]) #Agrega un elemento en la posición que se indique lista.insert(0,"Juan") #Elimina o borra un elemento lista.re...
bb3e967a7776b571cca10fdb988cb09b8980cf63
gptix/cs-module-project-algorithms2
/moving_zeroes/moving_zeroes.py
458
4.28125
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # Your code here original_length = len(arr) out = [element for element in arr if element is not 0] out = out + [0]*original_length return out[:original_length] if __name__ == '__main__': # Use the main funct...
b243836428bc96290d75ba52e2d43c6f2ed64cfd
WenkaiBai/rl-stock-portfolio-management
/preprocess.py
1,771
3.546875
4
import yfinance as yf import tensorflow as tf def get_data(all_tickers, training_ratio=0.8, validating_ratio=0.1): """ Import data from yfinance and split data into training set and testing set :param all_tickers: a list of all the Stock names whose data needs to be retrived :param training_ratio: th...
b4d75431128c90ed7a65c6a4c365fa14d7d3b8a0
senecal-jjs/Neural-Network
/RBF.py
4,158
4.1875
4
import numpy as np from typing import Sequence from trainingArray import trial_run import Layer ''' The network class in RBF.py is used to initialize a radial basis function network. It contains the methods required to train the network, as well as a method to calculate the output of the network given an arbitra...
d7c90e3849d24aaa84a12f0c62f63184fc37adf8
kamaravichow/advent-of-code-2020-python
/day1/part2.py
1,190
3.96875
4
def subsum_finder_helper(num_list,target): # Solve the subset sum problem for two target numbers for item in num_list: sub_target = target - item if sub_target in num_list: return item*sub_target return None def subsum_finder(num_list,target,num_nums): if num_nums==2: ...
38e76f23c5a5b2166290f7e1ccd8e131119fb8d8
jessica7890/jtp
/jpt3-3.2.py
507
3.703125
4
""" [문제2] 학급의 평균 점수 for문을 이용하여 A 학급의 평균 점수를 구해 보자. [문제3] numbers = [1, 2, 3, 4, 5] result = [] for n in numbers: if n % 2 == 1: result.append(n*2) 위 코드를 리스트 내포(list comprehension)를 이용하여 표현하시오. """ #문제2 A = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100] sum = 0 for i in A: sum += i print (sum/len(A)) #문제3 ...