blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2c55104e100681e13599c5e033a4750fc3c453d6
gorkemunuvar/Data-Structures
/algorithm_questions/3_find_the_missing_element.py
1,569
4.125
4
# Problem: Consider an array of non-negative integers. A second array is formed by shuffling # the elements of the first array and deleting a random element. Given these two arrays, # find which element is missing in the second array. import collections # O(N) # But this way is not work correctly cause # arrays can h...
true
351e79d71059e89664cddd394ac4db110beab3d3
hsyun89/PYTHON_ALGORITHM
/FAST_CAMPUS/링크드리스트.py
746
4.125
4
#파이썬 객체지향 프로그래밍으로 링크드리스트 구현하기 from random import randrange class Node: def __init__(self,data,next=None): self.data = data self.next = next class NodeMgmt: def __init__(self, data): self.head = Node(data) def add(self, data): if self.head =='': self.head = Node...
false
e02442b00cf41f9d3dd1933bee6b63122225e3b6
johnehunt/python-datastructures
/trees/list_based_tree.py
1,441
4.1875
4
# Sample tree constructed using lists test_tree = ['a', # root ['b', # left subtree ['d', [], []], ['e', [], []]], ['c', # right subtree ['f', [], []], []] ] print('tree', test_tree) print('left subtree = ', test_tree[1])...
true
070be4d1e2e9ebcdbff2f227ec97da5a83c45282
johnehunt/python-datastructures
/abstractdatatypes/queue.py
1,055
4.15625
4
class BasicQueue: """ Queue ADT A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” As an element enters the queue it starts at the rear and ma...
true
ad133e4c54b80abf48ff3028f7c00db37a622ec5
benwardswards/ProjectEuler
/problem038PanDigitMultiple.py
1,853
4.21875
4
"""Pandigital multiples Problem 38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with...
true
1362ec74ae0c72c10bf26c69151e8d6c8d64105c
hopesfall23/Fizzbuzz
/fizzbuzz.py
530
4.125
4
#William's Fizzbuzz program n = 100 #Hard coded upper line # "fizz" Divisible by 3 # "buzz" #Divisible by 5 #"Fizzbuzz" Divisible by 3 and 5 c = 0 #Current number, Will hold the value in our while loop and be printed for c in range(0,n): #Will run this loop from 0 to 100 then terminate if c <= n: ...
true
447850fd37249fc7e61e435c8823d86a73c42512
sprajjwal/CS-2.1-Trees-Sorting
/Code/sorting_iterative.py
2,700
4.25
4
#!python def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. Running time: O(n) because we iterate through the loop once Memory usage: O(1) because we check in place""" # Check that all adjacent items are in order, return early if so if len(items) < 2: ...
true
cf33043df637dff1470547b466ded6b71d4cd434
nightphoenix13/PythonClassProjects
/FinalExamQuestion31.py
1,412
4.125
4
def main(): month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] highs = [0] * 12 lows = [0] * 12 for temps in range(len(month)): highs[temps] = int(input("Enter the highest temperature for " + ...
true
b36b52841f7e33f6a6b849a1ba3d14a6545b31ce
MariDoes/PC-2019-02
/ejercicio3.py
1,056
4.1875
4
3 #Escriba un programa que registre las inscripciones de un curso de natación. #El curso solo acepta 5 personas y se debe preguntar 3 datos: nombre, sexo y edad. #El programa solo debe permitir inscripciones de edades entre 5 y 17 años. # El programa debe terminar cuando se tenga a las 5 personas que cumplan los req...
false
f6076d80cbf22a0af11337a6a329fe64df60477e
Allaye/Data-Structure-and-Algorithms
/Linked List/reverse_linked_list.py
615
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from linked_list import LinkedList L = LinkedList(10) def reverse(L): ''' reverse a linked list nodes, this reverse implementation made use of linked list implemented before ''' lenght = L.length() if(lenght == 0): raise IndexError('The lis...
true
edfba19244397e3c444e910b9650de1a855633b3
Allaye/Data-Structure-and-Algorithms
/Stacks/balancedParen.py
2,399
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from Stack import Stack # personal implementation of stack using python list # In[12]: def check_balance(string, opening='('): ''' a function to check if parenthesis used in a statement is balanced this solution used a custom implementation of a stack u...
true
83ec8968625803240349a9187a081f0fc66ee18d
Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning
/Controle de fluxo/Iterando dicionários com loops for.py
766
4.375
4
# Todo: Quando você iterar um dicionário usando um loop for, # fazer do jeito normal (for n in some_dict) vai apenas dar acesso às chaves do dicionário - que é o que queremos em algumas situações. # Em outros casos, queremos iterar as _chaves_e_valores_ do dicionário. Vamos ver como isso é feito a partir de um exemplo....
false
a4ac445dab9a10302d57fe822da0bfad49eabe7e
Deyveson/Nanodegree-Fundamentos-de-AI-Machine-Learning
/Script/Quiz Lidando com erros.py
2,020
4.125
4
# Todo: Quiz Lidando com a divisão por zero # Neste momento, executar o código abaixo causará um erro durante a segunda recorrência à função create_groups porque ela # se depara com uma exceção ZeroDivisionError. # # Edite a função abaixo para lidar com esta exceção. Se ela se depara com a exceção durante a primeira li...
false
bedc8089b31c69ba198321d399ebad95f7b60f4b
nansleeper/miptlaby2021
/laba2/t11.py
511
4.15625
4
import turtle import numpy as np def circle(r): for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.left(1) for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.right(1) #для начала работы требуется ввести желаемое количество "крыльев" у ...
false
f0c37197681932ed66662da67f577689e3f0748c
nansleeper/miptlaby2021
/laba2/t10.py
588
4.28125
4
import turtle import numpy as np def circle(r): for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.left(1) for i in range(0, 360): turtle.forward(np.pi * r / 180) turtle.right(1) def flower(r, n): for j in range(3): circle(r) ...
false
75b5f5b8da4326b00d7de5d7c613039ecd1c4d25
Marcelove/Python-Tarefas-caro
/QUESTÃO 4 LISTA 2.py
897
4.21875
4
#Checando triângulos e dizendo suas propiedads while True: print ('Olá! Vamos ver se você consegue formar um triângulo com 3 valores de retas.') fi = int(input('Digite o valor da primeira reta:\n')) se = int(input('Digite o número da segunda reta:\n')) th = int(input('Digite o número da ...
false
cc6b56b8c951d7aab983940c8f766ed6d24e0359
ermidebebe/Python
/largest odd.py
725
4.28125
4
x=int(input("X=")) y=int(input("y=")) z=int(input("z=")) if(x%2!=0): print("x is Odd") if(y%2!=0): print("y is Odd") if(z%2!=0): print("z is Odd") if(x%2!=0 and y%2!=0 and z%2!=0 ): if(x>y and x>z): print("x is the greatest of all") elif(y>x and y>z): print("y is the greatest") else : ...
false
cfcf85b40806e49c8cfaf1a51b78b1aa5c96ca18
bislara/MOS-Simulator
/Initial work/input_type.py
728
4.25
4
name = raw_input("What's your name? ") print("Nice to meet you " + name + "!") age = raw_input("Your age? ") print("So, you are already " + str(age) + " years old, " + name + "!") #The input of the user will be interpreted. If the user e.g. puts in an integer value, the input function returns this integer value. If th...
true
36906e07dd7a95969fcfbfb24bc566af77d6c290
w0nko/hello_world
/parameters_and_arguments.py
301
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 18 18:20:48 2017 @author: wonko """ def power(base, exponent): # Add your parameters here! result = base ** exponent print ("%d to the power of %d is %d.") % (base, exponent, result) power(37, 4) # Add your arguments here!
true
bb21d460a800def3b50708218376ed4638a0a841
chenqunfeng/python
/demo1_最简单抓包.py
796
4.21875
4
# 关与urllib和urllib2之间的区别 # http://www.hacksparrow.com/python-difference-between-urllib-and-urllib2.html # 在pythob3.x中urllib2被改为urllib.request import urllib.request # urlopen(url, data, timeout) # @param {string} url 操作的url # @param {any} data 访问url时要传送的数据 # @param {number} timeout 超时时间 response = urllib.re...
false
cc157edc908e4cb99ada1f2f4b880fa939d635cb
alojea/PythonDataStructures
/Tuples.py
1,105
4.5
4
#!/usr/bin/python import isCharacterInsideTuple import convertTupleIntoList import addValueInsideTuple alphabetTuple = ('a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') stringTuple = "" for valueTuple in alphabetTuple: stringTuple = ...
true
c50d0f924ae516d9d6bab320cb1bb71cfc35d7a6
nishantvyas/python
/unique_sorted.py
1,603
4.15625
4
""" Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: a...
true
589f077eb0b0080801f5dc3e7b4da8e3a4d1bf35
applicationsbypaul/Module7
/fun_with_collections/basic_list.py
837
4.46875
4
""" Program: basic_list.py Author: Paul Ford Last date modified: 06/21/2020 Purpose: uses inner functions to be able to get a list of numbers from a user """ def make_list(): """ creates a list and checks for valid data. :return: returns a list of 3 integers """ a_list = [] for index ...
true
726acce695d62e6d438f2abd93b1685daab8f95a
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dict_membership.py
502
4.15625
4
""" Program: dict_membership.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries for the first time """ def in_dict(dictionary, data): """ accept a set and return a boolean value stating if the element is in the dictionary :param dictionary: The given dictionary to search ...
true
d38c77a4b3c2b8448226fa481fc79e177048fa65
applicationsbypaul/Module7
/Module10/class_definitions/student.py
2,597
4.25
4
from datetime import datetime class Student: """Student class""" def __init__(self, lname, fname, major, startdate, gpa=''): """ constructor to create a student :param lname: last name :param fname: first name :param major: Major of student :param gpa: students...
false
8510a11490351504b7bf1707f5ba14318fae7240
applicationsbypaul/Module7
/Module8/more_fun_with_collections/dictionary_update.py
1,563
4.28125
4
""" Program: dictionary_update.py Author: Paul Ford Last date modified: 06/22/2020 Purpose: using dictionaries to gather store and recall info """ def get_test_scores(): """ Gathers test scores for a user and stores them into a dictionary. :return: scores_dict a dictionary of scores """ ...
true
97d812a9b932e9ae3d7db1726be2089627985347
PikeyG25/Python-class
/forloops.py
658
4.15625
4
##word=input("Enter a word") ##print("\nHere's each letter in your word:") ##for letter in word: ## print(letter) ## print(len(word)) ##message = input("Enter a message: ") ##new_message = "" ##VOWELS = "aeiouy" ## ##for letter in message: ## if letter.lower() not in VOWELS: ## new_message+=letter ## ...
true
6700dca221f6a0923ef9b5dbbf1ec56ab69b0671
Reetishchand/Leetcode-Problems
/00328_OddEvenLinkedList_Medium.py
1,368
4.21875
4
'''Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example 1: Input: 1->2->3->4->5->N...
true
56bb70f89a3b2e9fa203c1ee8d4f6f47ec71daf8
Reetishchand/Leetcode-Problems
/00922_SortArrayByParityII_Easy.py
924
4.125
4
'''Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanat...
true
5231912489a4f9b6686e4ffab24f4d4bc13f3a46
Reetishchand/Leetcode-Problems
/00165_CompareVersionNumbers_Medium.py
2,374
4.1875
4
'''Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision ...
true
8937e4cc7b216ba837dcbf3a326b2a75fb325cd0
Reetishchand/Leetcode-Problems
/00690_EmployeeImportance_Easy.py
1,800
4.1875
4
'''You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id. For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then emplo...
true
c0a23174b8c9d3021942781c960a21d2ad0699b5
Reetishchand/Leetcode-Problems
/02402_Searcha2DMatrixII_Medium.py
1,388
4.25
4
'''Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example 1: Input: matrix = [[1,4,7,11,15],[2,5,8,12...
true
99202f99cbf5b47e4f294c8e0da826f993ac5d3b
Reetishchand/Leetcode-Problems
/00537_ComplexNumberMultiplication_Medium.py
1,240
4.15625
4
'''Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example 2: In...
true
68198c760cdb09b8e882088013830389b0b4d19d
Reetishchand/Leetcode-Problems
/00346_MovingAveragefromDataStream_Easy.py
1,289
4.3125
4
'''Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement the MovingAverage class: MovingAverage(int size) Initializes the object with the size of the window size. double next(int val) Returns the moving average of the last size values of the stream. ...
true
68f0b89631b89d1098932cd021cf579348d71004
jaipal24/DataStructures
/Linked List/Detect_Loop_in_LinkedList.py
1,388
4.25
4
# Given a linked list, check if the linked list has loop or not. #node class class Node: def __init__(self, data): self.data = data self.next = None # linked list class class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = ...
true
87f6078f3f99bd3c33f617e2b7b33143fed70369
BonnieBo/Python
/第二章/2.18.py
412
4.125
4
# 计算时间 import time currentTime = time.time() print(currentTime) totalSeconds = int(currentTime) currentSeconds = totalSeconds % 60 totalMinutes = totalSeconds // 60 currentMinute = totalMinutes % 60 totalHours = totalMinutes // 60 currentHours = totalHours % 24 print("Current time is", currentHours, ":", currentMi...
true
83920bc4e32b0dbc42187f9ce0fd8ce8e840a15f
emicalvacho/All-algorithms-and-data-structures-AEDI
/arboles/binary_tree.py
2,433
4.125
4
#TAD de Árbol Binario class BinaryTree(object): """Clase del Binary Tree""" def __init__(self, data): """Constructor del BT: Creo un nodo con el valor que se instancia e inicializo tanto los dos hijos con None.""" self.key = data self.leftChild = None self.rightChild = None def insertLeft(self, ...
false
7b5b3ff7995758cb199808977015ea635a879309
Farazi-Ahmed/python
/lab-version2-6.py
288
4.125
4
# Question 8 Draw the flowchart of a program that takes a number from user and prints the divisors of that number and then how many divisors there were. a=int(input("Number? ")) c=1 d=0 while c<=a: if a%c==0: d+=1 print(c) c+=1 print("Divisors in total: "+str(d))
true
03074b61771fa4e751fd84c97aac21e3a918fa35
Farazi-Ahmed/python
/problem-solved-9.py
326
4.4375
4
# Question 9 : Draw flowchart of a program to find the largest among three different numbers entered by user. x=int(input("Value of x: ")) y=int(input("Value of y: ")) z=int(input("Value of z: ")) if x>y and x>z: print(x) elif y>z and y>x: print(y) else: print(z) MaxValue = max(x,y,z) print(Max...
true
28f739f2ac311a56f42af138f8c3432a4e0620e9
Farazi-Ahmed/python
/problem-solved-7.py
303
4.375
4
# Question 7: Write a flowchart that reads the values for the three sides x, y, and z of a triangle, and then calculates its area. x=int(input("Value of x: ")) y=int(input("Value of y: ")) z=int(input("Value of z: ")) s = (x + y + z) / 2 area = ((s * (s-x)*(s-y)*(s-z)) ** 0.5) print(area)
true
3e5006cf9e83f5127beb05765bf276de6efcc3d3
peoolivro/codigos
/Cap5_Exercicios/PEOO_Cap5_ExercicioProposto03.py
509
4.21875
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 05 # Questão.: Exercício Proposto 3 # Autor...: Fábio Procópio # Data....: 15/06/2019 import random RIFA = [] while True: nome = input("Informe um nome: ") RIFA.append(nome) resp = input("Deseja continuar [S|N]? ") if ...
false
39b6f848cd2579bbc0c33cdafa3a73dbf356244d
peoolivro/codigos
/Cap2_Exercicios/PEOO_Cap2_ExercicioProposto05.py
475
4.375
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 02 # Questão.: Exercício Proposto 5 # Autor...: Fábio Procópio # Data....: 18/02/2019 from math import sqrt print("Dados do ponto P1:") x1 = float(input("Digite x1: ")) y1 = float(input("Digite y1: ")) print("Dados do ponto P2:") x2 =...
false
9badcbc5bc0a142e7fea1b8f5057ada50378e713
peoolivro/codigos
/Cap3_Exercicios/PEOO_Cap3_ExercicioProposto07.py
749
4.3125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: Exercício Proposto 7 # Autor...: Fábio Procópio # Data....: 31/05/2019 altura1 = float(input("Digite a estatura da 1ª pessoa (em metros): ")) altura2 = float(input("Digite a estatura da 2ª pessoa (em metros): ")) altura3...
false
ca22c26a971c31449b679a1e243d835105b0b2a7
peoolivro/codigos
/Cap5_Exercicios/PEOO_Cap5_ExercicioProposto02.py
735
4.125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 05 # Questão.: Exercício Proposto 2 # Autor...: Fábio Procópio # Data....: 15/06/2019 ATLETA = [] TEMPO = [] for x in range(7): nome = input("Informe o nome do nadador: ") tempo = float(input("Informe o tempo do nadador: ")) ...
false
de9d698079b2f694b6233ebc72eb35e899dd530e
peoolivro/codigos
/Cap3_Exercicios/PEOO_Cap3_ExercicioProposto01.py
390
4.28125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: Exercício Proposto 1 # Autor...: Fábio Procópio # Data....: 31/05/2019 num = int(input("Digite um número: ")) if num % 2 == 0: quadrado = num ** 2 print(f"{num} é par e o seu quadrado é {quadrado}.") else: cu...
false
6713ce569d9bd93b9bccdb4e85e9caddb1fc0848
peoolivro/codigos
/Cap3_Exercicios/PEOO_Cap3_ExercicioProposto02.py
958
4.625
5
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 03 # Questão.: Exercício Proposto 2 # Autor...: Fábio Procópio # Data....: 31/05/2019 num1 = float(input("Digite um número: ")) num2 = float(input("Digite outro número: ")) print("\n1. Média ponderada, com pesos 2 e 3, respectivamente...
false
58df08bc90edaf08f828285d1ed3701c50f671ae
peoolivro/codigos
/Cap4_Exercicios/PEOO_Cap4_ExercicioProposto07.py
759
4.125
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 04 # Questão.: Exercício Proposto 7 # Autor...: Fábio Procópio # Data....: 04/06/2019 idade = int(input("Idade: ")) '''Como não há nenhuma idade a ser comparada, neste momento, a primeira idade é, ao mesmo tempo, o mais novo e o mais ...
false
519d04e843b4966f58d0d2ffc1e4a4596ef1ea09
manand2/python_examples
/comprehension.py
2,044
4.40625
4
# list comprehension nums = [1,2,3,4,5,6,7,8,9,10] # I want 'n' for each 'n' in nums my_list = [] for n in nums: my_list.append(n) print my_list #list comprehension instead of for loop my_list = [n for n in nums] print my_list # more complicated example # I want 'n*n' for each 'n' in nums my_list = [n*n for n i...
true
37498e70f1550bd468c29f5b649075ce4254978d
chrishaining/python_stats_with_numpy
/arrays.py
384
4.15625
4
import numpy as np #create an array array = np.array([1, 2, 3, 4, 5, 6]) print(array) #find the items that meet a boolean criterion (expect 4, 5, 6) over_fives = array[array > 3] print(over_fives) #for each item in the array, checks whether that item meets a boolean criterion (expect an array of True/False, in this ...
true
c0585d2d162e48dd8553ccfc823c3e363a2b28c0
samson027/HacktoberFest_2021
/Python/Bubble Sort.py
416
4.125
4
def bubblesort(array): for i in range(len(array)): for j in range(len(array) - 1): nextIndex = j + 1 if array[j] > array[nextIndex]: smallernum = array[nextIndex] largernum = array[j] array[nextIndex] = largernum array[j...
true
148418a17af55f181ecea8ffd5140ba367d7dc2d
youngdukk/python_stack
/python_activities/oop_activities/bike.py
974
4.25
4
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print("Bike's Price: ${}".format(self.price)) print("Bike's Maximum Speed: {} mph".format(self.max_speed)) print("Total ...
true
1a3113a91f5b6ffe95899f952be3248e8197498b
frankiegu/python_for_arithmetic
/力扣算法练习/day86-实现 Trie (前缀树).py
1,698
4.1875
4
# -*- coding: utf-8 -*- # @Time : 2019/5/28 22:15 # @Author : Xin # @File : day86-实现 Trie (前缀树).py # @Software: PyCharm # 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。 # # 示例: # # Trie trie = new Trie(); # # trie.insert("apple"); # trie.search("apple"); // 返回 true # trie.search("app"); // 返回 fals...
false
797d224072c34473343a93e16fbadd7015d5f484
frankiegu/python_for_arithmetic
/力扣算法练习/day39-接雨水.py
1,944
4.15625
4
# -*- coding: utf-8 -*- # @Time : 2019/4/8 21:23 # @Author : Xin # @File : day39-接雨水.py # @Software: PyCharm # 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 # # day39图 # 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。 # # 示例: # # 输入: [0,1,0,2,1,0,1,3,2,1,2,1] # 输出: 6 ...
false
52d35b2a21c30e5f35b1193b123f0b59a795fa17
prefrontal/leetcode
/answers-python/0021-MergeSortedLists.py
1,695
4.21875
4
# LeetCode 21 - Merge Sorted Lists # # Merge two sorted linked lists and return it as a new sorted list. The new list should be # made by splicing together the nodes of the first two lists. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1: ...
true
b1ff4822be75f8fffb11b8c2af5c64029a27a874
prefrontal/leetcode
/answers-python/0023-MergeKSortedLists.py
2,349
4.125
4
# LeetCode 23 - Merge k sorted lists # # Given an array of linked-lists lists, each linked list is sorted in ascending order. # Merge all the linked-lists into one sort linked-list and return it. # # Constraints: # k == lists.length # 0 <= k <= 10^4 # 0 <= lists[i].length <= 500 # -10^4 <= lists[i][j] <= 10^4 # lists[i...
true
9348abc87c6ec5318606464dac6e792960a0bc0f
NNHSComputerScience/cp1ForLoopsStringsTuples
/notes/ch4_for_loops_&_sequences_starter.py
1,795
4.78125
5
# For Loops and Sequences Notes # for_loops_&_sequences_starter.py # SEQUENCE = # For example: range(5) is an ordered list of numbers: 0,1,2,3,4 # ELEMENT = # So far we have used range() to make sequences. # Another type of sequence is a _________, # which is a specific order of letters in a sequen...
true
f6ccf4fa74bc616ae4ef5e5baefa86a979dd2052
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex73.py
921
4.25
4
'''Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times. b) Os últimos 4 colocados. c) Times em ordem alfabética. d) Em que posição está o time da Chapecoense.''' times = ('PALMEI...
false
60a90abddad95055618302d95db8b21cb33d907f
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex93.py
1,037
4.25
4
'''Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o...
false
a73e0adf7527348b492741b5bd782081775d9113
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex72.py
653
4.25
4
'''Exercício Python 72: Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.''' numeros = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'D...
false
f3fdc60439a3a4219e11a6b285eaa0db756244eb
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex105.py
944
4.15625
4
'''Exercício Python 105: Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: – Quantidade de notas – A maior nota – A menor nota – A média da turma – A situação (opcional) ''' def notas(*num, sit = False): """ :p...
false
7cb2c3e5720f6f5fb26c1572b02c2b233ff631e7
EduardoLucas-Creisos/Python-exercises
/Exercícios sobre fundamentos/ex68.py
1,289
4.15625
4
'''Exercício Python 68: Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo. ''' import random jogador = '' computador = '' c = 0 n = 0 s = 0 cont = 0 while True: jogador = in...
false
5640294cdf3d30f67af661fc674b2c35ac60738a
Iftakharpy/Data-Structures-Algorithms
/section 6 reverse_string.py
256
4.15625
4
usr_input = input('Write something : ') reversed_str = '' #custom implementation #O(n) time #O(n) space for i in range(len(usr_input)-1,-1,-1): reversed_str+=usr_input[i] print(reversed_str) #built in function print(input('Write something : ')[::-1])
false
f0499de132924504b7d808d467e88af636eb5d27
KindaExists/daily-programmer
/easy/3/3-easy.py
1,057
4.21875
4
""" [easy] challenge #3 Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pkw2m/2112012_challenge_3_easy/ """ # This can most likely be done in less than 2 lines # However still haven't figured a way to stop asking "shift" input def encrypt(string, shift): return ''.join([chr((((ord(char...
true
d84ec922db8eeb84c633c868b5c440b5de7f9445
gaogep/LeetCode
/剑指offer/28.二叉树的镜像.py
1,116
4.125
4
# 请完成一个函数,输入一棵二叉树,改函数输出它的镜像 class treeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right root = treeNode(1) root.left = treeNode(2) root.right = treeNode(3) root.left.left = treeNode(4) root.right.right = treeNode(5) def showM...
true
90233e801ae204d17c260c32f126d52529858083
gaogep/LeetCode
/剑指offer/25.反转链表.py
771
4.15625
4
# 定义一个函数,输入一个链表的头结点 # 反转该链表并输出反转后链表的头结点 class listNode: def __init__(self, Value, Next=None): self.Value = Value self.Next = Next def insert(self, Value): next_node = listNode(Value) while self.Next: self = self.Next self.Next = next_node head = listNode(...
false
3f508261b762fb7d2e66aae50828e31612af7261
jemper12/ITEA_lesson_igor_gaevuy
/lessons_2/1_task.py
2,003
4.3125
4
""" Создать класс автомобиля. Описать общие аттрибуты. Создать классы легкового автомобиля и грузового. Описать в основном классе базовые аттрибуты для автомобилей. Будет плюсом если в классах наследниках переопределите методы базового класса. """ from random import randrange as rand class Car: engine = 'Gasoline...
false
1e18b7a08b74e804774882603eabc30829622571
pchandraprakash/python_practice
/mit_pyt_ex_1.5_user_input.py
686
4.1875
4
""" In this exercise, we will ask the user for his/her first and last name, and date of birth, and print them out formatted. Output: Enter your first name: Chuck Enter your last name: Norris Enter your date of birth: Month? March Day? 10 Year? 1940 Chuck Norris was born on March 10, 1940. """ def userin...
true
b3cccd80b43cda1068d0990b8823395e7ca570b9
marcin-bakowski-intive/python3-training
/code_examples/builtin_types/tuples.py
1,220
4.25
4
#!/usr/bin/env python3 # https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range animals = ("dog", "cat") lookup = ("dog", "horse", "cat") for lookup_value in lookup: if lookup_value in animals: print("'%s' found in animals tuple" % lookup_value) else: print("'%s' not ...
false
f1501d4453bfbe8b9ac668d0347efd61be61d382
habibi05/ddp-lab-4
/main.py
1,175
4.125
4
# DDP LAB-4 # Nama: Habibi # NIM: 0110220247 # SOAL 1 - Mencetak nama # Tuliskan program untuk Soal 1 di bawah ini # Simpan masukan nama kedalam variabel nama nama = input("Masukkan nama: ") # Simpan panjang nama kedalam variabel lenNama lenNama = len(nama) # Deklarasi variabel iNama dengan nilai 1 untuk kebutuhan pe...
false
b82739886b7bd5e7d35d91b79b87fd0649cd3086
J-pcy/Jffery_Leetcode_Python
/Medium/247_StrobogrammaticNumberII.py
1,342
4.28125
4
""" A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69","88","96"] """ class Solution: def findStrobogrammatic(self, n): """ :type n: int ...
false
1e10d7f86e975ef682821785ebe59bc5e499d219
J-pcy/Jffery_Leetcode_Python
/Medium/418_SentenceScreenFitting.py
2,233
4.28125
4
""" Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. Note: A word cannot be split into two lines. The order of words in the sentence must remain unchanged. Two consecutive words in a line must be separated by a sing...
true
c75df56aed95a3e74e0436c54ea4e22e669c395f
J-pcy/Jffery_Leetcode_Python
/Medium/75_SortColors.py
2,518
4.25
4
""" Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the l...
true
b2c6dc8fdd2f25b0e7ed668f2af2237120e33184
Daneidy1807/CreditosIII
/07/ejercicio4.py
449
4.34375
4
""" Ejercicio 4. Pedir dos numeros al usuario y hacer todas las operaciones básicas de una calculadora y mostrarlo por pantalla. """ numero1 = int(input("Introduce un primer número: ")) numero2 = int(input("Introduce el segundo número: ")) print("#### CALCULADORA ####") print("Suma: " + str(numero1+numero2)) print("...
false
bb7b31b34fc66a0d41b29659eb34187969f05b8f
flavio-brusamolin/py-scripts
/list02/ex02.py
363
4.125
4
numbers = list() option = 'Y' while option == 'Y': numbers.append(int(input('Enter a number: '))) option = input('Keep inserting? Y/N ') even = list(filter(lambda number: number % 2 == 0, numbers)) odd = list(filter(lambda number: number % 2 != 0, numbers)) print(f'All numbers: {numbers}') print(f'Even numb...
false
2d8491624e72ef82b1a1b7179dbc13bbbacb8ebb
juan-g-bonilla/Data-Structures-Project
/problem_2.py
1,293
4.125
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffi...
true
31b93a072533214b5f1e592442d6072e1a83c01c
texrer/Python
/CIS007/Lab2/BMICalc.py
658
4.40625
4
#Richard Rogers #Python Programming CIS 007 #Lab 2 #Question 4 #Body mass index (BMI) is a measure of health based on weight. #It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. #Write a program that prompts the user to enter a weight in pounds and height i...
true
ffbff41905680bde74a7d42f06d0aa90f55fca25
yingwei1025/credit-card-checksum-validate
/credit.py
1,333
4.125
4
def main(): card = card_input() check = checksum(card) validate(card, check) def card_input(): while True: card_number = input("Card Number: ") if card_number.isnumeric(): break return card_number def checksum(card_number): even_sum = 0 odd_sum = 0 card_n...
true
66f0ccab7057084061766ca23e21d790e829922b
irmowan/LeetCode
/Python/Binary-Tree-Maximum-Path-Sum.py
1,307
4.15625
4
# Time: O(n) # Space: O(n) # Given a binary tree, find the maximum path sum. # # For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. # # For example: # Given the below binary tree...
true
9fe261707283f616194ebe30757a6381d500d534
irmowan/LeetCode
/Python/Palindrome-Number.py
1,065
4.125
4
# Time: O(n) # Space: O(1) # # Determine whether an integer is a palindrome. Do this without extra space. # # click to show spoilers. # # Some hints: # Could negative integers be palindromes? (ie, -1) # # If you are thinking of converting the integer to string, note the restriction of using extra space. # # You could a...
true
5f8c9db073643da16d88ef03512b4ca6e97d28ca
LinuxUser255/Python_Penetration_Testing
/Python_Review/dmv.py
308
4.125
4
#!/usr/bin/env python3 #If-else using user defined input: print("""Legal driving age. """) age = int(input("What is your age? ")) if age < 16: print("No.") else: if age in range(16, 67): print("Yes, you are eligible.") if age > 66: print("Yes, but with special requirements.")
true
6361f4914c5a1570c9113a55222c139a9844efb2
mihirbhaskar/save-the-pandas-intpython
/filterNearby.py
973
4.125
4
""" File: filterNearby Description: Function to filter the dataframe with matches within a certain distance Next steps: - This function can be generalised, but for now assuming data is in a DF with lat/long columns named 'latitude' and 'longitude' """ import pandas as pd from geopy.distance import distance d...
true
2096aed0b726883d89aae8c3d886ae5ef3b11518
simplex06/HackerRankSolutions
/Lists.py
1,683
4.3125
4
# HackerRank - "Lists" Solution #Consider a list (list = []). You can perform the following commands: # #insert i e: Insert integer at position . #print: Print the list. #remove e: Delete the first occurrence of integer . #append e: Insert integer at the end of the list. #sort: Sort the list. #pop: Pop the last elem...
true
492689343e28be7cdbb2d807514881925534a010
SynTentional/CS-1.2
/Coursework/Frequency-Counting/Frequency-Counter-Starter-Code/HashTable.py
2,156
4.3125
4
from LinkedList import LinkedList class HashTable: def __init__(self, size): self.size = size self.arr = self.create_arr(size) # 1️⃣ TODO: Complete the create_arr method. # Each element of the hash table (arr) is a linked list. # This method creates an array (list) of a given size and populates eac...
true
1a9ba4cfe848b8529b0aa9eaddd09882f9bcd5bf
khankatan/CP3-Chetsarit-Mesathanon
/assignments/Exercise5_1_Chetsarit_M.py
269
4.15625
4
print("--------- CALCULATOR ---------- ") x = int(input("num1 : ")) y = int(input("num2 : ")) print("=============================== ") print(x,"+",y,"=",x+y) print(x,"-",y,"=",x-y) print(x,"x",y,"=",x*y) print(x,"/",y,"=",x/y) print("=============================== ")
false
aa29cde7070d9c68e6572d9a362fed336488f4a1
SeilaAM/BasicProgramPython
/ModulePractice/CustomerSystemMoveTest/Modules/Asset/BasicData.py
1,767
4.21875
4
# ----------------- 客戶的基本資料 ----------------- # class BasicData: def __init__(self, name, age, gender, phone, email): self.__name = name self.__age = age self.__gender = gender self.__phone = phone self.__email = email def get_name(self): return self.__name ...
false
7f7c20e3c655b59fb28d90a5b7fec803d3b65170
MrSmilez2/z25
/lesson3/4.py
272
4.125
4
items = [] max_element = None while True: number = input('> ') if not number: break number = float(number) items.append(number) if not max_element or number >= max_element: max_element = number print(items) print('MAX', max_element)
true
a2ab21a48d07c3fe753681babeb8cfeea023038c
floryken/Ch.05_Looping
/5.2_Roshambo.py
1,632
4.8125
5
''' ROSHAMBO PROGRAM ---------------- Create a program that randomly prints 1, 2, or 3. Expand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list. Add to the program so it first asks the user their choice as well as if they want to quit. (It will be easier if you h...
true
f95a79a3a2d6c1718efb817cba7c8cb7072ce57f
goateater/SoloLearn-Notes
/SL-Python/Data Types/Dictionaries.py
2,870
4.71875
5
# Dictionaries # Dictionaries are data structures used to map arbitrary keys to values. # Lists can be thought of as dictionaries with integer keys within a certain range. # Dictionaries can be indexed in the same way as lists, using square brackets containing keys. # Each element in a dictionary is represented by a k...
true
333d2fae7916937db479ee1778ed237c59e6e57d
goateater/SoloLearn-Notes
/SL-Python/Opening Files/writing_files.py
2,703
4.5625
5
# Writing Files # To write to files you use the write method, which writes a string to the file. # For Example: file = open("newfile.txt", "w") file.write("This has been written to a file") file.close() file = open("newfile.txt", "r") print(file.read()) file.close() print() # When a file is opened in write mode, th...
true
e7c9ff96bfd41f28f35486d8635a44bbcdb47126
benilak/Everything
/CS241_Miscellaneous/scratch_2.py
2,743
4.28125
4
'''class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self._hours = hours self._minutes = minutes self._seconds = seconds def get_hours(self): return self._hours def set_hours(self, hours): if hours < 0: self._hours = 0 elif hou...
false
cb63ddf5d873dc45e0f46f0c048b06cf17864c53
virenparmar/TechPyWeek
/core_python/Function/factorial using recursion.py
499
4.28125
4
# Python program to find the factorial of a number using recursion def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n==1: return n else: return n*recur_factorial(n-1) #take input from the user num=int(input("Enter a number=")) #check is the number is negative if...
true
830bf963c902c0382c08fca73c71d2fa2f7d1522
virenparmar/TechPyWeek
/core_python/fibonacci sequence.py
479
4.40625
4
#Python program to display the fibonacci sequence up to n-th term where n is provided #take in input from the user num=int(input("How many term?")) no1=0 no2=1 count=2 # check if the number of terms is valid if num<=0: print("please enter a positive integer") elif num == 1: print("fibonacci sequence") print(no1...
true
4ae8ad04f48d102055e470f4ca953940a8ca1f25
virenparmar/TechPyWeek
/core_python/Function/anonymous(lambda) function.py
299
4.46875
4
#Python Program to display the power of 2 using anonymous function #take number of terms from user terms=int(input("How many terms?")) #use anonymous function result=list(map(lambda x:2 ** x, range(terms))) #display the result for i in range(terms): print "2 raised to power",i,"is",result[i]
true
01ab8ec47c8154a5d90d5ee4bd207f143a0051b3
virenparmar/TechPyWeek
/core_python/Function/display calandar.py
242
4.40625
4
# Python Program to display calender of given month of the year #import module import calendar #assk of month and year yy=int(input("Enter the year=")) mm=int(input("Enter the month=")) #display the calender print(calendar.month(yy,mm))
true
17af5750832fde25c0a10ec49865f478fae390d9
jonathansantilli/SMSSpamFilter
/spamdetector/file_helper.py
973
4.1875
4
from os import path class FileHelper: def exist_path(self, path_to_check:str) -> bool: """ Verify if a path exist on the machine, returns a True in case it exist, otherwise False :param path_to_check: :return: boolean """ return path.exists(path_to_check) def re...
true
bd4daf1ee0c3fc74486bc4680a1b3355337eab62
Pythonmaomao/String
/3-52.py
990
4.34375
4
class Human: ''' this is the Human class!!! ''' name = 'ren' __money = 100 def __init__(self,name,age):#对象实例化后init函数自动执行 print('#'*50) self.name = name#只是赋值,没有输出打印;传入实例的属性 self.age = age print('#'*50) #@classmethod#类方法 @property def say(self):#公有方法,...
false
cf5b64089024a35ddd119fc90ae09cc8e404129e
mani-barathi/Python_MiniProjects
/Beginner_Projects/Number_guessing_game/game.py
926
4.25
4
from random import randint def generateRandomNumber(): no = randint(1,21) return no print('Number Guessing Game!') print("1. Computer will generate a number from 1 to 20") print("2. You have to guess it with in 3 guess") choice = input("Do you want to play?(yes/no): ") if choice.lower() == 'yes': while True: nu...
true
3d78394ffe2709a01d1e6a34df7dfcb7ba407a76
mani-barathi/Python_MiniProjects
/Beginner_Projects/DataStructures/Stack.py
948
4.1875
4
class Stack: def __init__(self): self.stack=[] # emty list self.top=-1 def isEmpty(self): if len(self.stack)==0: return True else : return False def push(self): self.top+=1 element = input("Enter the Element: ") self.stack.insert(self.top,element) print(f" {element} ...
false
c3f3c6409e68ceae0d46054bf50c22b7ff56f37b
rsp-esl/python_examples_learning
/example_set-2/script_ex-2_5.py
939
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__...
false
fc67206793cd483acdbb305f621ab33b8ad63083
rsp-esl/python_examples_learning
/example_set-1/script_ex-1_27.py
1,088
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__...
true