blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
144479ac2534b0e816e30defcc1c1a4e0b4a95d4
BilboSwaggins33/Test
/55.py
545
3.859375
4
#Array has to increase than decrease #at some point def ValidMountainArray(arr): counter = 0 if len(arr) < 3: return False else: for i in range(len(arr) - 1): if (arr[i] < arr[i + 1] and counter == 0): continue elif arr[i] > arr[i + 1] and counter == 0...
1ca1971ed2b8025251093cf9e82f1769b149016b
mtbthebest/PythonTraining
/StrKeyDict0.py
522
3.578125
4
# coding=utf-8 class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): raise KeyError return self[str(key)] def get(self, key,default=None): try: return self[key] except KeyError: return default def __contains__(self, key): return key in self.keys() or str(key) in self.keys() ...
c501ca8f0ece9587841ef244f7fad0dacc710915
yovanycunha/P1
/opbancarias/opbancarias.py
500
3.8125
4
#coding: utf-8 # Operações Bancárias # (C) 2016, Yovany Cunha/UFCG, Programaçao I cliente,saldo = raw_input('').split() saldo = float(saldo) while True: entrada = raw_input('') if entrada == '3': break operacao,quantia = entrada.split() operacao = int(operacao) quantia = float(quantia) if operacao == 1: #qu...
66e180d3b3062177ace4e2d8b210219b9b1efaf8
wyh2023/Software-Eng-Computing-I
/PythonCode/Alice_Bob_and_Chocolate.py
857
3.640625
4
"""write your code in method solve""" def solve(): num = int(input()) candies = list(map(int, input().split(' '))) p1 = 0 p2 = num - 1 sum1 = 0 sum2 = 0 if p1 == p2: sum1 += 1 while p1 < p2: flg_1, flg_2 = p1, p2 candies[p1] -= 1 candies[p2] -...
b0f02c31ff246eaaf84e3b180e57281d71e72cb3
trinhgliedt/Algo_Practice
/2021_06_19_word-search.py
3,092
3.921875
4
# https://leetcode.com/problems/word-search/ # Medium # Given an m x n grid of characters board and a string word, return true if word exists in the grid. # The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may...
6551efd4adb28d0cffe971e85807c27941bfe840
amit-kr-debug/CP
/Geeks for geeks/stacks/Nearest greatest to right.py
1,358
3.90625
4
""" Given an array A of size N having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1 Input: The first line of input contains a single integer T denoting the number of test cases.Then T test ca...
7cb39993202d7444a2148fa54474c085c22e1944
OfirDG/Whatsapp
/Matala3.py
2,261
3.671875
4
import datetime import re import json def read_file(file): '''Reads Whatsapp text file into a list of strings''' x = open(file,'r', encoding = 'utf-8') #Opens the text file into variable x but the variable cannot be explored yet y = x.read() #By now it becomes a huge chunk of string that we need to separat...
5122c29ea6a6cadfc3d4f88309cebaa4d30cf85d
Timmi239/algorithms
/A_/841.py
534
3.546875
4
from collections import defaultdict def main(): counts = input().split(' ') letters = input() _, k = map(int, counts) result = task(letters, k) print(result) def task(letters: str, k: int): letters_dict = defaultdict(int) for letter in letters: letters_dict[letter] += 1 if a...
720a9b787d805c31939cc7a1f92819e57e46307a
nicol337/minesweeper
/game.py
1,296
3.8125
4
from minesweeper import Minesweeper import time import os def getLevel(): levels = ['easy', 'medium', 'hard'] level = input("Please type "+ ', '.join(levels) + " for level").lower().strip() while level not in levels: level = input("Please type "+ ', '.join(levels) + " for level").lower().strip() return levels.i...
efb25bd41b1c1ef3c15649e74df6daaed38b6451
sourav-coder/Python-Code-Challanges
/Python Code Challenges/100-plus-Python-programming-exercises-extended-master/solutions/Day-11/Q39.py
87
3.5
4
t=(1,2,3,4,5,6,7,8,9,10) func=lambda :print(tuple(i for i in t if i%2==0)) func()
002737feaf12fd3093c45f776a8a2350a74a1315
Gadhy/trabajo-n-7
/iteracion-en-rango/ir5.py
249
3.796875
4
#imprimir los años m "" import os m=int(os.sys.argv[1]) m_invalido=(m<0 or m>5) while(m_invalido==True): m=int(os.sys.argv[1]) m_invalido=(x<0 or x>5) for i in range(m): print(i) #fin iterador en rango print("fin del bucle")
dd847701164392dbf0e3339c6814de60360803b8
BJMX/PythonText
/list_dict_set_tips/named_tuple_col.py
204
4.0625
4
from collections import namedtuple # 本质是创建的一个类 Student = namedtuple('Student', ['name', 'age', 'sex', 'email']) s = Student('jim', 16, 'male', 'jim1234@gmail.com') print(s.name, s.sex, s.email)
97be5954d0baabd3c727077d1d5c58339a2e8bee
claytonkristiansen/BunnyBunnyFooFoo
/fibonacci.py
401
3.6875
4
#1 1 2 3 5 8 13 21 34 arr = [1, 1] startingNumber = int(input("First: ")) endingNumber = int(input("Last: ")) i = 2 num = arr[i - 1] + arr[i - 2] while num <= endingNumber: arr.append(num) i = i + 1 num = arr[i - 1] + arr[i - 2] index = 0 while(arr[index] < startingNumber): index = index + 1 betw...
046cae2e6ebd2a49d33539e4c49ea424a6e8060e
workready/pythonbasic
/ejercicios_resueltos/t06/t06ejer03.py
1,373
4
4
class Shape: @property def area(): raise NotImplementedError("Por favor, implementa este método en una clase hija") @property def perimeter(): raise NotImplementedError("Por favor, implementa este método en una clase hija") class Rectangle(Shape): def __init__(se...
fe884c5601eff95e1085fce8882abcf62d32b4ef
AdinaFakih/python
/comparisonOperators.py
228
3.625
4
# a = 1 < 2 <3 # print(a) # a = 1 < 2 > 3 # print(a) # a = 1<2 and 2<3 # print(a) # a = ('h' == 'h') and (2 == 2) # print(a) # a= 100 == 1 or 2==2 # print(a) # a = not 1==1 # print(a) a = not 400>50000 print(a)
d18651bc1d4490ea043234fed76700958a41dabe
hanjasn/ctci
/linked_lists/partition/linked_list.py
521
3.9375
4
class LinkedList: def __init__(self) -> None: self.head = None def add(self, data): node = LinkedListNode(data) node.next = self.head self.head = node def print_list(self): node = self.head result = "" while node != None: if node.next == None: result += str(node.dat...
2bc072b17b9c2cd4b379b84b91f101ac168f23b5
chlee1252/dailyLeetCode
/book/problems/union.py
684
4.0625
4
def findParent(parent, v1): if parent[v1] != v1: parent[v1] = findParent(parent, parent[v1]) return parent[v1] def union(parent, a, b): a = findParent(parent, a) b = findParent(parent, b) if a < b: parent[b] = a else: parent[a] = b def algorithm(v, unionNodes): # parent 테이블 생성 ...
83c5a12eec15974eaed418fdb38ec30d66e6faf6
erastusk/sort_aligorithm
/bubble_sort.py
230
4
4
def bubble_sort(list_in): sort = True while sort: sort = False for i in range(len(list_in) - 1): if list_in[i] > list_in[i + 1]: sort = True list_in[i], list_in[i + 1] = list_in[i + 1], list_in[i] return list_in
aeb811f692a21e4b5c50bae0488e3ac98b403e19
chennan625/Coursera-Python-Data-Structures
/Chapter10/assignments10.2.py
777
3.9375
4
''' 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2...
c65f13d045eeafc311ff274f8395c30686bc8749
Kavekha/NoGoNoMa
/data/random_table.py
829
3.671875
4
from random import randint class RandomEntry: def __init__(self, name, weight): self.name = name self.weight = weight class RandomTable: def __init__(self, current_depth=1): self.entries = [] self.total_weight = 0 self.current_depth = current_depth ...
426170867b520f48fc320a14c3a1c4376244e787
giochajon/evolveu-python
/comp200/array.py
509
3.703125
4
contents = [] def my_array(func, value=0): global contents if func == "add": value = int(input('Enter item to add: ')) contents.append(value) elif func == "show": print("array", contents) elif func == "total": print(sum(contents)) elif func == "clear": con...
626b457f050eb8d190ab8532502eb304a490956b
RoniKish/NewClassCreation
/Main.py
4,335
3.5625
4
from DataStructuresManager import DataStructuresManager def linked_list_example(my_manager): my_manager.create_new_linked_list() my_manager.linked_lists[0].add_node("a") my_manager.linked_lists[0].add_node("b") my_manager.linked_lists[0].add_node("c") my_manager.linked_lists[0].add_node("d") m...
64c29591296b26cc215af5fab30f098d33a31f0a
renjieliu/leetcode
/0001_0599/278.py
1,463
3.625
4
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ s = 1 e = n output = n while s <= e: ...
bf88ab757358d3a35a1b3553262410716a12632c
ignaziocapuano/workbook_ex
/cap1/ex_8.py
516
4.0625
4
#An online retailer sells two products: widgets and gizmos. Each widget weighs 75 #grams. Each gizmo weighs 112 grams. Write a program that reads the number of #widgets and the number of gizmos in an order from the user. Then your program #should compute and display the total weight of the order. peso_gizmo=112 peso_w...
49e4f168c8f4d83ab5419baf3464525e2722d486
DIEGORIBEIRO9080/curso_metodos_numericos_em_Python_e_C-
/5_aula_metNewton.py
1,083
3.671875
4
# -*- coding: utf-8 -*- ''' ************************************************************************************** * Name: Método de Newton em python * * Copyright: NDF * * Author: Luciano Mendes ...
74b43bd7beea17d9ec6712e84ec908bfbd26a16b
ferreret/python-bootcamp-udemy
/18-functions-exercices/ex04.py
332
3.84375
4
''' number_compare(1,1) # "Numbers are equal" number_compare(1,0) # "First is greater" number_compare(2,4) # "Second is greater" ''' def number_compare(first, second): if first > second: return "First is greater" elif second > first: return "Second is greater" else: return "Numbers...
3ab3c17ff67cf8725452794d3c0e177e5f7b81e7
TOKPE627/python_learning
/practicalList/program4.py
397
4.625
5
#Python program to find largest number in a list #creation of empty list arr1= [] print() print("---Welcome in largest number finder program----") print() arrSize=int(input("Enter the number of elements of the list: ")) for i in range(1,arrSize+1): element = int(input("Enter an element: ")) arr1.append...
cbee7f1b32a308e373f42df026b7ddefe768ff3a
barajasr/Euler
/Problem_032/Problem_032.py
1,483
3.953125
4
#! /usr/bin/env python # -*- coding: iso-8859-15 -*- # Problem 32: Pandigital products #-------------------------------------------------------------------- # We shall say that an n-digit number is pandigital if it makes use # of all the digits 1 to n exactly once; for example, the 5-digit # number, 15234, is 1 throug...
6aab6a657e485e83c9d2c91921af2d595493d6ad
zy10zm/path-planning
/simulate.py
6,724
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 31 14:23:41 2020 @author: Saif """ import math import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import global_planner import local_planner def length(path): """ Calculates the total path length of an input...
dab68f55e4c373502e348d93b4ca1ae74845c9df
bdloko/myPackage
/mypackage/test.py
331
3.71875
4
from recursion import sum_array, factorial, reverse, fibonacci from sorting import bubble_sort, merge_sort, quick_sort print(sum_array([1, 2, 3])) print(fibonacci(10)) print(factorial(5)) print(reverse("abcdef")) print(bubble_sort([5, 4, 1, 2, 4, 9])) print(merge_sort([1, 3, 2, 5, 4, 7, 6])) print(quick_sort([3, 2, 4,...
23bff36e2c1dd8a52e2cee3970aa990902dc4343
andyhasit/june_workshop_solutions
/shopping_basket/shopping_basket/Product.py
375
3.625
4
class Product(object): """ A product in the shop. Descriptions must be unique, handle elsewhere. """ def __init__(self, description, price): self._description = description self._price = price @property def description(self): return self._description @p...
80db65c6603637972258b2a257692bbd1a09f043
NiravModiRepo/Coding
/DSA/DynamicProgramming/70_ClimbingStairs.py
680
3.84375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 20 15:02:33 2018 @author: Nirav Modi Runtime: O(n) """ class Solution: # Base dictionary for the stairs dictStairs = {0:0, 1:1, 2:2, 3:3} def climbStairs(self, n): """ :type n: int :rtype: int """ # ...
2ccc728a871626b99a433765ffa5f42bd5bac160
maria-j-k/control-sum
/control_sum_validators/pesel_validator.py
3,259
4.0625
4
def leap(year): ''' Function checks if a year is a leap year. Accepts: integer: four digits integer representing year. Returns: boolean: True if year is a leap year, False otherwise. ''' return (not year % 4 and year % 100) or not year % 400 def check_control_sum(pesel): ...
eda52089d21f1f119a1437b3da3fa2ed9abe5b3d
dattnguyen/Leetcode_exercises
/MergeSort Implementation.py
1,446
4.09375
4
def merge(A, left, middle, right): #example [4,2,3,7,8,3,1]. left = 0, right = 7-1 =6. middle = (0+6)//2 =3 n1 = middle - left + 1 #middle is at 3, we +1 to account for the first index starting at 0 n2 = right - middle L = [0] * n1 #create empty arrays R = [0] * n2 #copy data to temp arrays L and R...
f298b6f594e00cbeb2ded306adb11282982210b1
Xmn0721/MTA-pythan
/Day1-梯形面積.py
89
3.59375
4
a=input("up?") b=input("down?") c=input("high?") print((float(a)+float(b))*float(c)/2)
f4fc5abf9c427a000abaf6f99d208775d8da35e4
bopopescu/heyy
/venv/session20.py
424
3.859375
4
import pandas as pd numbers = [10,20,30,40,50] s1 = pd.Series(numbers) print(s1) print() ages = {"john":20, "jennie": 30, "jim":40, "jack":50, "joe":60} s2 = pd.Series(ages) print(s2) print() #access elements print(s1[0]) print(s2["jennie"]) print("==============") #slice elements print(s1[1:]) print() print(s...
dc95402101461c78b31b242eda869c11d96e0b83
gabriel-valenga/CursoEmVideoPython
/ex094.py
563
3.546875
4
jogador = {} partidas = [] totalGols = 0 jogador['nome'] = input('Digite o nome do jogador:') jogador['numPartidas'] = int(input(f'Quantas partidas o {jogador["nome"]} jogou?')) for p in range(0, jogador['numPartidas']): partidas.append(int(input(f'Quantos gols o jogador fez na partida {p}?'))) jogador['partidas'] ...
21d9b92e096a11f3bc1f04a86fc7bd109a80680b
marseille6/leetcode
/InsertSort.py
455
4.15625
4
""" 人一生不会踏进同一条河流 __author__ = 'marseille' __date__ = '2021/1/14 13:21' """ class InsertSort(): def insert_sort(self,A): for j in range(1,len(A)): key = A[j] i = j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i] i = i - 1 A[i + ...
1afc96aade2536945e7690609244594129d6124f
magnuskonrad98/max_int
/FORRIT/timaverkefni/22.08.19/ticket_price.py
207
4.15625
4
age = int(input("Input age: ")) # Do not change this line # Fill in the missing code below if age <= 5: price = float(0) elif age >= 65: price = float(15) else: price = float(30) print(price)
4de3ebebfbfe1494a4fdb0c30ae4beaaa5ec2376
RW21/competitive-code
/leetcode/_118.py
528
3.65625
4
from pprint import pprint from typing import List def generate(numRows: int) -> List[List[int]]: if numRows == 0: return [] triangle = [[1]] for i in range(numRows): if i != 0: row = [] for j in range(i + 1): if j == 0 or j == i: ...
1c6ddaa4c490b155b258ad1b7c4389ce7d0180c6
CristinaFdezBornay/ComputorV1
/api/src/displayer.py
1,581
3.671875
4
def display_reduced_form(equation): print('Reduced form\t\t: '+equation.reduced_form) def display_degree(equation): print('Polynomial degree\t: '+str(equation.degree)) def display_discriminant(equation): if equation.degree == 2: print('Δ = b² - 4ac\t\t: {:+.2f}'.format(equation.discriminant).rstri...
7ce59e3fddbfff51183f2c4c658551fbdf14c304
IanMendozaJaimes/compiladores
/6/funciones_sintactico.py
3,378
3.546875
4
class Manejador_sintactico(): def __init__(self): self.producciones = list() self.productores = dict() self.producidos = dict() self.inicial = '' self.siguientes_calculados = dict() self.visitados = None def primero(self, simbolo): if simbolo[0] not in ...
40cdee8676def700acbf911bcc060d7fef4f3b07
Academies/sca
/solutions/day1/vigenere/vigenere.py
682
3.953125
4
import cs50, sys if len(sys.argv) != 2 or len(sys.argv[1]) == 0: print("Usage: python vigenere.py keyword") exit(1) keyword = sys.argv[1] if not keyword.isalpha(): print("invalid keyword") exit(1) print("plaintext: ", end="") plaintext = cs50.get_string() index = 0 print("ciphertext: ", end="") for...
9339bdc3c1480588d11a100e4237dbed7a3d012f
zlzlelzl/PythonPractice
/Z_task3/main.py
913
3.859375
4
import requests import os input_yn = "y" input_urls = "" while(input_yn != "n"): os.system('clear') print("Welcome to IsItDown.py!") print("Please write a URL or URLs you want to check. (seperated by comma)") input_urls = input() input_url = input_urls.split(',') for url in input_url: error_string ...
eed420171cf0c1a747cae85a31e004bccff542f3
seungdaegoh/practice_python
/p20_BSTree/test_BSTree.py
2,680
3.625
4
#!/usr/bin/env python3 #from random import randint import random import string from bstree import BSTree max_numbers = 500 def randomString(stringLength=5): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength))...
199822b5adb94f70e858f2767bd75aef3564ca02
mcialini/EchoClientServer
/server.py
4,359
3.734375
4
#!/usr/bin/env python """----------------------------------------------------------------------------------------------------------------------------------------------- Full Echo Server by Matt Cialini This server will will bind a socket to the port number input by the user on the local machine. It then will listen f...
b54688cf5856a98e734443063940b7a44f47d7ca
lucet15/FP_2P
/auxiliar.py
381
3.625
4
def numero_cel(n): """funcao auxiliar que recebe uma lista e confirma se o primeiro elemento e 0, 1 ou -1""" return n[0]==0 or n[0]==1 or n[0]==-1 def numero_coor(c): """funcao auxiliar que recebe uma lista e confirma se os elementos sao 0, 1 ou 2""" for i in range(len(c)): if c[i]!=0 or...
d8a364593f35d7b4f03eb22e6660155a3ff525e4
RuslanGlaznyov/snapcraft.io
/webapp/metrics/metrics.py
8,776
3.5
4
import pycountry from operator import itemgetter def _calculate_colors(countries, max_users): """Calculate the displayed colors for a list of countries depending on the maximum number of users :param countries: List of countries :param max_users: Maximum of number users :returns: The list of cou...
02ba1ece47b4f9130f53ade11be68d9e89ef18e7
arturbardzinski/Python_A_Z
/names.py
411
3.5
4
from name_function import get_formated_name print("Wpisz 'q' aby wyjść.") while True: first = input("\nPodaj imię: ") if first == "q": print("\n===Koniec programu===") break last = input("\nPodaj nazwisko: ") if last == "q": print("\n===Koniec programu===") break formatted_name = get_forma...
ca9d0bd1e25bb2452815e8fab61117959cb04747
aanguss/leetcode
/lc_python/aoa/zombieInMatrix.py
3,355
3.921875
4
# https://leetcode.com/discuss/interview-question/411357/ # Given a 2D grid, each cell is either a zombie 1 or a human 0. Zombies can # turn adjacent(up/down/left/right) human beings into zombies every hour. # Find out how many hours does it take to infect all humans? # Example: # Input: # [[0, 1, 1, 0, 1], # ...
79f083f5905c266565532480b9b115f0bdec1a66
zhexxian/SUTD-The-Digital-World
/Homework/coding_week2/Q3.py
342
3.6875
4
def posVel(v0,t): a = 9.81 y = float(format((v0 * t - 0.5 * a * t ** 2),'.2f')) #why can't I use round function here? y0 = float(format((v0 - a * t),'.2f')) # what are other unicode other than .2f? #y = float (format(y, '.2f')) #y0 = float (format(y0, '.2f')) # why return (y, y0) print posVel(...
47d00cbc10171a190c69c5d26eddf6dd9bb08cec
brian-sherman/Python
/C859 Intro to Python/Challenges/09 Lists and Dictionaries/9_16 Additional Practice/Task1.py
506
4
4
""" Task 1 Complete the function to return the first two items in the given list # Complete the function to return the first two items in the given list def getFirstTwo(mylist): # Student code goes here # expected output: [8, 3] print(getFirstTwo([8,3,5,2,10])) # expected output: [15, 2] print(getFirstTwo([15,2,...
cc28a6440a1978b0384a8ee45c27813e11931783
Hugocorreaa/Python
/Curso em Vídeo/Desafios/Mundo 2/ex0058 - Jogo da Adivinhação v2.0.py
1,356
4.3125
4
''' Melhore o jogo deo DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. ''' print('-=-' * 15) print(' Jogo da adivinhação') print('-=-' * 15) '''from random import ra...
9bf574a7bcc26668b199972da26e4b83ae69cf27
tim-andes/conways-game-of-life
/conways.py
2,568
4.34375
4
# Conway's Game of Life import random, time, copy WIDTH = 60 HEIGHT = 20 num_cycles = 100 # set number of cycles here count_cycles = 0 def main(WIDTH, HEIGHT, num_cycles, count_cycles): """ Conway's Game of Life: An example of cellular automaton. Set number of cycles with num_cycles. :param WIDTH: Width of grid...
9c8cd37156772480e58bc197edc3954115ed3c52
murchelon/Python_Projects
/Ex1/ex1.py
292
3.84375
4
from datetime import datetime name = input("Digite seu nome: ") age = input("Digite sua idade: ") times = int(input("Quantas vezes devo repetir ? ")) year = datetime.now().year year100 = 100 - int(age) + year for x in range(times): print(name + ", vce tera 100 em " + str(year100))
b8f9ec2c44d40de3cd1f7ee166775cda5f297962
chowell2000/hash-tables
/hashtable/challenge.py
174
3.96875
4
array = ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] def alphabetize(arr): arr.sort() return arr print(alphabetize(array))
42029f8ff19a5c342107ee825bd1ad97b97250cb
eric82714/LeetCode_599--Minimum-Index-Sum-of-Two-Lists
/Python3/minimum_index_sum_of_two_lists.py
522
3.5
4
class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: result = [] least = len(list1) + len(list2) for i in range(len(list1)): for j in range(len(list2)): if list1[i] == list2[j] and (i+j) == least: ...
f37ef99b673c0ff43147b5960c734e50930cd02c
osmya/codesignal
/almostIncreasingSequence.py
711
3.890625
4
def almostIncreasingSequence(sequence): for i, x in enumerate(sequence): s = sequence[:i] s.extend(sequence[i+1:]) if s == sorted(set(s)): return True return False """ def almostIncreasingSequence(sequence): def is_increasing(lst): for idx in range(len(lst)-...
7d511858a20102a61a4d09f50a14b26a78d7e8f8
mateuszpieniak/codility
/triangle.py
318
3.59375
4
def is_triangular(A, P, Q, R): cond1 = A[P] + A[Q] > A[R] cond2 = A[Q] + A[R] > A[P] cond3 = A[R] + A[P] > A[Q] return cond1 and cond2 and cond3 def solution(A): A.sort() N = len(A) for i in range(0, N - 2): if is_triangular(A, i, i + 1, i + 2): return 1 return 0
8b5d8c7d98bd931d93e1ae9d8419d9c4ed63742d
quan191/AlgorithmInPython
/SolveCSESProblem/Introduction/TwoSet.py
750
3.59375
4
n=int(input()) if n%4==3: print("YES") x=n//4 list1=[1,2] list2=[3] for i in range(1,x+1): list1.append(4*i) list1.append(4*i+3) list2.append(4*i+1) list2.append(4*i+2) print(len(list1)) for i in list1: print(i,end=" ") print() print(len(list2)...
c7213046720fbad689f90eda2854187df5ad6f06
refine-P/NLP100Knock
/question10-19/question18.py
238
3.53125
4
#coding:utf- # sort -k3nr hightemp.txt sort_list = [line.split() for line in open("hightemp.txt", encoding='utf-8').readlines()] sort_list.sort(key=lambda line:float(line[2]), reverse=True) for line in sort_list: print(" ".join(line))
dec8c7da17472145e5e7ca77c1e8274d7cbca21e
stoneeve415/LintCode
/_88_lowest_common_ancestor_of_bt.py
1,938
3.625
4
""" @title: 88, 二叉树最近公共祖先 @author: evestone """ ''' 存在父指针 ''' def lowestCommonAncestorII(root, A, B): # write your code here _dict = {} while A != None: _dict[A]=True A = A.parent while B != None: if B in _dict: return B B = B.parent return None # 转换为...
a192819a96c5a304bc4238f6b07167d456a4f451
hobin-jang/2021cryptocontest
/No.3/3-1.py
504
3.53125
4
# -*- coding: utf-8 -*- import SimpleStack as st import sys # 남은 횟수 없을 시 종료 def error_check(cnt): if cnt <= 0: sys.exit() else: return stack, cnt = st.init() stack, cnt = st.push(stack, cnt) error_check(cnt) stack, cnt = st.push(stack, cnt) error_check(cnt) stack, cnt = st.add(stack, cnt) ...
4d6a9e84789f511a54b58f843f7a6c07684ee9b2
bogipeneva/-Programming-101-Python-2019
/week03/test_rpn.py
1,292
3.71875
4
import unittest from rpn import rpn_calculate class TestReversePolishNotation(unittest.TestCase): def test_when_single_digit_is_passed_then_return_same_digit(self): expr = '45' expected_result = 45 self.assertEqual(rpn_calculate(expr), expected_result) def test_when_two_digit_are_passed...
a9655d7cf36deead30a7289ed728aa714ab52510
veeteeran/holbertonschool-higher_level_programming
/0x11-python-network_1/3-error_code.py
572
3.71875
4
#!/usr/bin/python3 """Takes in a URL, sends a request to the URL and displays the body of the response """ from urllib.request import urlopen, Request from urllib.error import HTTPError from urllib.parse import urlencode from sys import argv if __name__ == "__main__": url = argv[1] try: req = Reque...
969c1d47e4a7d42c923ded9169d4ad41533aefa1
UltraChris64/Learn-Python-the-Hard-Way
/labs/ex40a.py
266
3.59375
4
#mystuff = {'apple': "I AM APPLES!"} #print(mystuff['apple']) import mystuff #mystuff.apple() #print(mystuff.tangerine) mystuff['apple'] # get apple from dict mystuff.apple() # get apple from the module mystuff.tangerine # same thing, it's just a variable
97587688589758b5604989c6bb9778ce09438c0f
bsurmanski/inflation_card_simulator
/cards.py
2,593
3.609375
4
import random values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] names = ['2', '3', '4', '5', '6', '7', '8', '9', 'X', 'J', 'Q', 'K', 'A'] class Card(object): def __init__(self, value, name): self.value = value self.name = name def __repr__(self): return self.name def __cmp__(self...
e444d68faaa4cb7f052d0dca150bb81c6ace09cc
flavianeferrares/Algoritmos-Grafos
/HeapMax.py
2,625
3.703125
4
import math class HeapMax: def __init__(self): self.nos = 0 #quantidade de nos self.heap = [] def adiciona_no(self, u): #u valor do no, adiciona na ultima posição self.heap.append(u) self.nos += 1 f = self.nos #f = filho while True: if f == 1: ...
5a7d60ac030ac117447c49041b410f8c7e85cbcb
MiroVatov/Python-SoftUni
/Python Advanced 2021/LISTS AS STACKS AND QUEUES/Lab 01.py
225
3.8125
4
initial_text = input() stack = [] for ch in initial_text: stack.append(ch) reversed_text = [] while len(stack) > 0: pop_char = stack.pop() reversed_text.append(pop_char) print(''.join(reversed_text))
2aa4b128ccff4d84b3167561763aadf0dd6c3160
Ziang-Lu/Software-Development-and-Design
/Interview-System Design Practice/Library Information System/Python/items.py
4,726
3.546875
4
#!usr/bin/env python3 # -*- coding: utf-8 -*- """ Items module. """ __author__ = 'Ziang Lu' from abc import ABC, abstractmethod from datetime import date, timedelta class Item(ABC): """ Abstract item class. """ __slots__ = ['_title'] def __init__(self, title: str): """ Construc...
fd134536488a98392390370df76fea965801a602
IcourtDuraiSelvaraj/WorkedExamples
/01-07-2019/Func3.py
459
3.5625
4
def simple_interest3(p, t, r): print(p) return (p * t * r) / 100 def simple_interest3(p, t, r, k=10): print(k) return (p * t * r *k) / 100 def simple_interest3(p, t, r, k=10, l=90): print(l) return (p * t * r *k) / 100 print("Simple Interest: ", simple_interest3(p = 1900, t = 10, r = 10)) p...
0cef71e4feeba4e7fe09b2a3df6a8a600eedeab3
vjsecret/python_prac
/functionbasic4.py
2,273
3.515625
4
# def input(): # a1=raw_input("請輸入數值一:"); # a2=raw_input("請輸入數值二:"); # a3=raw_input("請輸入數值三:"); # a4=raw_input("請輸入數值四:"); # a5=raw_input("請輸入數值五:"); # list1=[a1, a2, a3, a4, a5] # show(list1) # # def show(list): # for i in range(0,len(list)): # print(list[i]) # # e...
5bf1f05703fa7b28aa97d3c54827b4b83a3f003c
hemanthkumarbattula/python-tasks
/Linked Lists/nth_to_last_node.py
937
3.90625
4
class Node(object): def __init__(self,value): self.value = value self.nextnode = None def nth_to_last_node(self,n,head): l = [] l.append(head) while head != None and head.nextnode!= None: l.append(head.nextnode) head = head.nextnode ret...
c40b6da317d4297a1a4be50228a0c4cf4632daba
bainco/bainco.github.io
/course-files/lectures/lecture12/for_loops/00_for_loop_example.py
497
4.15625
4
def make_call(phone_num:str): """ function to call a phone number Inputs: phone_num (str): a phone number to call Outputs: No output (prints to the screen instead) """ print("Making phone call to {}...number dialed.".format(phone_num)) print("Survey issued.\nCall Complete....
5735e8454bb502e01af81093daae21b8b35df24a
gaoshang18/python
/04_函数/hm_06_函数的返回值.py
300
3.875
4
# 函数的返回值 return def sum_2_mun(num1,num2): """对两个数字的求和""" result = num1 + num2 return result # return 接收返回值 # 可以使用变量,来接受函数执行的返回结果 sum_result = sum_2_mun(1,2) print("计算求值结果%d" % sum_result)
be22ec31dcf693507de660ff29d6606958ef02f4
Kuehar/LeetCode
/Kth Largest Element in a Stream.py
682
3.640625
4
import heapq class KthLargest: def __init__(self, k: int, nums: List[int]): self.lists,self.num = [],k for i in nums: self.add(i) def add(self, val: int) -> int: heapq.heappush(self.lists, val) if len(self.lists) > self.num: heapq.heappop(self.lists) ...
c34c0e4285b9384dee887e67086cae0707d7f266
brandoneng000/LeetCode
/medium/623.py
1,252
3.734375
4
from typing import Optional import collections # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> ...
47451e54df404ee1ba7ddc108414f81770394281
mdeangelo272/deep-learning-tutorial
/multi-layer-network/numpy_linear_model_uniform.py
3,780
4.15625
4
# Example of three-layer network using only numpy import numpy as np # Specify the size of your batch, data, hidden layers, and labels N = 128 # Batch size: How many data points you feed in at a time data_dim = 1000 # Dimension of data vector, remember one data point is one dimensional H_1 = 100 # Dimension of firs...
cf63db471fcb930abc32ba75da73768f711c8fac
sendurr/spring-grading
/submission - Homework3/set2/JESSICA ROSE ROTHEISER_11097_assignsubmission_file_Homework3/Homework3/HW3.Q2.py
148
3.765625
4
def sumoddnumber(numbers): total = 0; for x in numbers: if x % 2 == 1: total += x return total print ("sum=",sumoddnumber([2,5,7,4,8,3,5]))
12e7650d7e8e58eac2f1c0e72804c8b380f55714
pyeprog/graph-algorithm
/bfs_shortest_paths.py
5,899
4
4
# This script is a minimum bfs module # Author by lwl __all__ = ["is_on_board", "move", "create_board_like", "vset", "vget", "shortest_paths"] from typing import List, Tuple, Set, Any from collections import deque def is_on_board(board: List[List[int]], point: Tuple[int, int]) -> bool: """ check if certain ...
bf662434ca2b925231770dd8371d106cea16fc3c
Mrliuyuchao/Interview
/面试题整合/分离指针/两个数组的交集.py
443
3.78125
4
def intersection(nums1,nums2): nums1.sort() nums2.sort() i,j = 0,0 nums_set = set() while i < len(nums1) and j < len(nums2): if nums1[i] > nums2[j]: j += 1 elif nums1[i] < nums2[j]: i += 1 else: nums_set.add(nums1[i]) j += 1 ...
1ffd5ddda1cc0a25b9d5d49e47806141a98241b5
findhappyman/website
/old/042_1.py
278
3.59375
4
class Nstr(str): def __init__(self,x): self.x = x def __lshift__(self, other): return self.x[other:] +self.x[:other] def __rshift__(self, other): return self.x[:other]+self.x[other:] a = Nstr('I love FishC.com!') print(a << 3) print(a >> 3)
49fb26cf8c686f73b16cda458d5045601b85ed16
walkccc/LeetCode
/solutions/0755. Pour Water/0755.py
402
3.59375
4
class Solution: def pourWater(self, heights: List[int], volume: int, k: int) -> List[int]: i = k while volume > 0: volume -= 1 while i > 0 and heights[i] >= heights[i - 1]: i -= 1 while i + 1 < len(heights) and heights[i] >= heights[i + 1]: i += 1 while i > k and heigh...
d72e96f8b26e871dea2a5d8fca0c48e18f87c351
carlos-sales/exercicios-python
/ex077.py
279
3.671875
4
palavras = ('Laptop', 'Mouse', 'Celular', 'Mochila', 'Melatonina') for i in palavras: print(f'\nNa palavra {i.upper()} temos ', end='') for letra in i: if letra.lower() in 'aeiou': print(letra, end=' ')
4c156b5bd3839d3cf389f197656bcff880fed716
traveling-soul/python
/design_pattern/create_pattern/abstract_factory_v1.py
1,381
3.546875
4
class User: _id = 0 _name = '' def set_id(self, id): self._id = id def get_id(self): return self._id def set_name(self, name): self._name = name def get_name(self): return self._name class IUser: def insert(self, user): pass ...
312444627bd8543311c295bab9e6f618a2b656a0
praveen5658/cspp1
/cspp1_practise/m3/sum_1_end.py
78
3.8125
4
n=int(input("Enter value n:")) sum=0 i=1 while(i<=n): sum+=i i+=1 print(sum)
1798a36eef25bb2fb1919d4e359941855774c6e8
vcu-threattdm/spiral
/spiral/homework.py
252
3.796875
4
def spiralize(number): number*=number start=1 inc=2 return_value=1 while start<number: for i in range(4): start+=inc return_value+=start inc+=2 return return_value print ( spiralize(501))
cf2dc954af9988793b57dff2ef5d6bf712e44ba2
mengshun/Leetcode
/problems/64.py
560
3.671875
4
""" 64. 最小路径和 """ import collections def minPathSum(grid): if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [[0] * n for _ in range(m)] dp[0][0] = grid[0][0] for i in range(1, m): dp[i][0] = dp[i-1][0] + grid[i][0] for i in range(1, n): dp[0]...
9cc01b6175d6b9df943e23218d56cd774bc0827b
rohanraval/interview-prep-2017
/CTCI3_StacksQueues/queueViaStacks.py
1,078
4.40625
4
''' Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks. IDEAS: - Front and back-facing stacks <===|===> Only push to the front one, only pop from the back one. Not gonna work because of obvious reasons! - If we want to pop the oldest element, we have to pop the rest of ...
35fb10ba380c30f0c5918237d8e3330b5496822e
STEMEduX/2020-2021Semester2
/Saturday/20210430/5_sets.py
302
3.953125
4
## Loop Items thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) ## Common mistake: RuntimeError: Set changed size during iteration thisset = {"apple", "banana", "cherry"} for x in thisset: # keep collection unchanged in size thisset.add(x + 'a') # or thisset.remove(x) print(x)
e76ba484caf71714966f6eb684acee01194c5ebe
uonele/Algorithm
/python/哈希表.py
769
4.09375
4
#! /usr/bin/env python #coding=utf-8 # python实现的哈希表 # 处理冲突的方法是开放地址法,冲突表达式为Hi=(H(key)+1)mod m,m为表长 # 实现哈希表(线性地址再散列) def ChangeKey(key,m,di): newkey = (key + di) % m return newkey a = raw_input("Please entry the numbers:\n").split() m = len(a) dict = {} for i in a: key = int(i) % m ...
2713f1ecd666832bf811d4c9618d17fb0314f4ea
salimmalik07/guvi
/prime.py
119
3.703125
4
numbe=int(raw_input()) for i in range(2, numbe): if numbe%i == 0: print( "no") break else: print( "yes")
108a63055413dc8080c2a650d6b5ff6bda6b2e24
borko81/python_scripts
/dictionary/file_two.py
312
3.90625
4
from collections import Counter # remove duplicates a = [7, 2, 1, 9, 1, 7, 11, 1] def found_duplicate(items): seen = set() for item in items: if item not in seen: yield item seen.add(item) print(list(found_duplicate(a))) print(Counter(a).most_common(2))
3c093a08019d68316dc52febb42dabe79d88150b
palandesupriya/python
/regular expression/countoccurence_regexp.py
608
4.15625
4
''' WAP to accept pattern and string from user and count occurences of pattern in string using search method ''' import re def countalloccurence(pattern, st): lst = [] x = re.search(pattern, st) iStart = 0 iCnt = 0 while x != None: if pattern == st[x.start() + iStart: x.end() + iStart]: iCnt += 1 iStart += ...
d83eee7d444362d04b5172b354c18758470fc3f5
morteza404/code_wars
/string_incrementer.py
707
4.0625
4
""" https://www.codewars.com/kata/54a91a4883a7de5d7800009c/train/python 5 kyu Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number. the numb...
c04328bd09a65efc6996d15f9aa9d2cd161e34ec
CesJauregui/python
/Bases_de_Datos/ejemplo2_bd.py
564
3.625
4
import sqlite3 conexion=sqlite3.connect("GestionProductos") cursor=conexion.cursor() cursor.execute(''' CREATE TABLE productos( ID INTEGER PRIMARY KEY AUTOINCREMENT, NOMBRE_ARTICULO VARCHAR(50) UNIQUE, PRECIO INTEGER, SECCION VARCHAR(20) ) ''') productos=[ ("pelota", 20, ...
800b861f56c026e62bccddb3b3e2de08ba9c385a
eichelb4rt/SAT-LAB
/global_libs/measurements.py
3,393
3.84375
4
from abc import ABC, abstractmethod from typing import Optional import time, tracemalloc class Measurement(ABC): """Class for measuring stuff. """ @abstractmethod def start(self): """Start the measurement. """ pass @abstractmethod def stop(self): """Stop the me...
36c8de17d8886d52c8e04bbf1e513d729a292f41
Khushali-Upadhyay/Udemy_python
/Loops_exercise_c2.py
3,010
3.984375
4
#Task-1 Convert for loop into a while loop # In[1]: numbers=list(range(0,110,10)) numbers=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] first = [] for num in numbers: s = num * 2.5 if s % 2 == 0: first.append(int(s)) first [0, 50, 100, 150, 200, 250] # In[2]: second=[] x = 0 while x < le...
93ee25fd96a60548021e6eb7db670cba6447512d
Poonam-Lunawat/c97
/countingWords.py
303
4.21875
4
introstring = input("Enter any string : ") charcounter = 0 wordcount=1 for i in introstring: charcounter=charcounter+1 if(i==" "): wordcount=wordcount+1 print("Number of words in the string : ") print(wordcount) print("Number of characters in the string : ") print(charcounter)
b198a80986df9a981e95391e81e5de64d329dd76
chiranjeevee5/demoPyGIT
/Primenumberiden.py
399
3.796875
4
"""num = int(input("Enter the number - ")) for i in range(2,num): if num % i == 0: print("Not Prime") break else: print("Prime") break""" prime =[] for i in range(1,101): x=2 y=0 while x<=i: if i%x==0: y+=1 x+=1 if y<=1: if i=...