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 |
|---|---|---|---|---|---|---|
d5003983716fb6640b9b34eed0f8ad1fee260967 | q13245632/CodeWars | /Booleanlogic.py | 918 | 3.59375 | 4 | # -*-coding:utf8-*-
# 自己的解法
def func_or(a,b):
if a:
return True
else:
if b:
return True
return False
def func_xor(a,b):
if a:
if not b:
return True
else:
if b:
return True
return False
# Test.describe("Basic tests")
# Test.ass... |
35276bd8d0bde54d510607b3bddc516175edabdd | q13245632/CodeWars | /Characterwithlongestrepetition.py | 1,002 | 3.859375 | 4 | # -*-coding:utf8 -*-
# 自己的解法
def longest_repetition(chars):
if chars is None or len(chars) == 0:
return ("",0)
pattern = chars[0]
char = ""
c_max = 0
count = 1
for s in xrange(1,len(chars)):
print chars[s]
if chars[s] == pattern:
count += 1
else:
... |
e8f3a4b8488bc263cf35d953261b0faf8fb4669a | q13245632/CodeWars | /Directions Reduction.py | 1,709 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-14
def dirReduc(arr):
lst = []
for i in arr:
if len(lst) <= 0:
lst.append(i)
continue
if i == 'NORTH':
if lst[-1:][0] == 'SOUTH':
lst.pop()
else:
lst.append(i... |
cec3d32d73c63985e62eb3bd2a7f32a38f074037 | q13245632/CodeWars | /First non-repeating letter.py | 1,548 | 3.84375 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-27
from collections import Counter
def first_non_repeating_letter(string):
string_copy = string.lower()
counter = Counter(string_copy)
index = len(string)
ch = ""
for k,v in counter.items():
if v == 1 and string_copy.index(k) < index:
... |
29f08f68b75f30dc980f8529d1ab5ee555787747 | q13245632/CodeWars | /Formattothe2nd.py | 723 | 3.90625 | 4 | # -*-coding:utf8-*-
# 自己的解法
def print_nums(*args):
max_len = 0
if len(args) <= 0:
return ''
else:
for i in args:
if max_len < len(str(i)):
max_len = len(str(i))
string = '{:0>' + str(max_len) + '}'
return "\n".join([string.format(str(i)) for i in a... |
b9b8c049ca9962375210716f57ecfdd7b9af6472 | q13245632/CodeWars | /WhatTheBiggestSearchKeys.py | 1,909 | 3.765625 | 4 | # -*-coding:utf8 -*-
# author: yushan
# date: 2017-02-26
# 自己的解法
def the_biggest_search_keys(*args):
if len(args) == 0:
return "''"
lst = []
maxlen = 0
for i in args:
if len(i) == maxlen:
lst.append("'"+i+"'")
elif len(i) > maxlen:
maxlen = len(i)
... |
c2db75efb101720de872fbd9d22b16b7fa4e0af4 | q13245632/CodeWars | /Permutations.py | 326 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-23
import itertools
def permutations(string):
lst = itertools.permutations(string)
lst = list(set(["".join(i) for i in lst]))
return lst
import itertools
def permutations(string):
return list("".join(p) for p in set(itertools.permutations(str... |
b382a3fab0bf42f3309b54065556330e3054b3d7 | huajh/python_start | /image_denoising/anisotropic_diff.py | 3,178 | 3.515625 | 4 | import numpy as np
import warnings
from matplotlib import pyplot as plt
def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.), option=1):
"""
Anisotropic diffusion.
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter ... |
a02d06dd30aef52d2d19d7d3f6c1dbbf20b112fa | ogsf/Python-Exercises | /Python Exercises/src/Ch3_Examples.py | 1,243 | 4.03125 | 4 | '''
Created on May 25, 2013
@author: Kevin
'''
filler = ("String", "filled", "by", "a tuple")
print "A %s %s %s %s" % filler
a = ("first", "second", "third")
print "The first element of the tuple is %s" % (a[0])
print "The second element of the tuple is %s" % (a[1])
print "The third element of the tuple is... |
3e93376c30710a336310de2da0d89be71e1f782b | freerangehen/AoC2019 | /day4.py | 668 | 3.859375 | 4 |
def is_valid(number):
number = str(number)
prev_digit = None
have_double = False
for each_digit in number:
if prev_digit:
if each_digit == prev_digit:
have_double = True
if each_digit < prev_digit:
return False
else:
... |
dd60ca87e05fa1755e80fd0a1711a97bb84c0767 | Guilherme-Artigas/Python-intermediario | /Aula 15.5 - Exercício 70 - Estatísticas em produtos/ex070_.py | 1,132 | 3.625 | 4 | from time import sleep
controle = True
total = Produto = menor_preco = 0
print('*-' * 13)
print(' * LOJA SUPER BARATEZA * ')
print('*-' * 13)
print()
while controle == True:
nome = str(input('Nome do Produto: '))
preco = float(input('Preço: R$ '))
total += preco
if preco > 1000:
Produto +=... |
a720bebe341646da8e5d7c76f21a25bb617a5a22 | Guilherme-Artigas/Python-intermediario | /Aula 14.1 - Exercício 57 - Validação de Dados/ex057_.py | 675 | 3.859375 | 4 | """
Minha solução...
r = 's'
while r == 's':
sexo = str(input('Sexo [M/F]: ')).strip().upper()[0]
if (sexo == 'M'):
r = 'n'
print('Dado registrado com sucesso, SEXO: M (Masculino)')
elif (sexo == 'F'):
r = 'n'
print('Dado registrado com sucesso, SEXO: F (Feminino)')
else... |
aef6e912e8e89b1edaeb56492c51ca1a2d52dda7 | Guilherme-Artigas/Python-intermediario | /Aula 13.9 - Exercício 54 - Grupo da Maioridade/ex054_.py | 237 | 3.640625 | 4 | q = 0
for c in range(1, 8):
anoN = int(input('Digite o ano de nascicmento da {}º pessoa: '.format(c)))
idade = 2020 - anoN
if (idade < 21):
q += 1
print('Quantidade de pessoas menores de idade:{} pessoas'.format(q))
|
ac9ed5d3670dc1612bd3f0bf6a8e7e28146739c1 | Guilherme-Artigas/Python-intermediario | /Aula 12.4 - Exercício 39 - Alistamento Militar/ex039_.py | 1,589 | 4.09375 | 4 | from datetime import date
ano_atual = date.today().year
sexo = str(input('Digite seu Sexo [Homem / mulher]: '))
if (sexo == 'Homem') or (sexo == 'homem') or (sexo == 'H') or (sexo == 'h'):
ano_N = int(input('Digite o ano do seu nascimento: '))
idade = ano_atual - ano_N
print()
print('Quem nasceu e... |
cc7a4308797597975dcf0029e34c707aabdfda38 | Guilherme-Artigas/Python-intermediario | /Aula 13.5 - Exercício 50 - Soma dos pares/ex050_.py | 173 | 3.875 | 4 | somaP = 0
for c in range(1, 6):
n = int(input('Digite um valor: '))
if (n % 2 == 0):
somaP += n
print('Soma dos valores pares digitados = {}'.format(somaP))
|
5d499ce12bdb550033ce907c61bbd5c44debbbb7 | gmastorg/CTI110 | /M2T1_SalesPrediction_Canjura.py | 217 | 3.6875 | 4 | #CTI 110
#M2T1 - Sales Prediction
#Gabriela Canjura
#08/30/2017
#calculate profit margin
totalSales= int(input('Enter total sales: '))
annualProfit = float(totalSales*.23)
print ('Annual sales = ',annualProfit,'.')
|
2044a3f44b9af55830532e836ddd2505dd5346b3 | gmastorg/CTI110 | /M6T2_FeetToInchesConverter_Canjura.py | 500 | 4.25 | 4 | #Gabriela Canjura
#CTI110
#10/30/2017
#M6T2: feet to inches converter
def main():
#calls a funtions that converts feet to inches and prints answer
feet = float(0)
inches = float(0)
feet = float(input("Enter a distance in feet: "))
print('\t')
inches = feet_to_inches(f... |
1098b2cb56836f9ef77cb4a563a62b5bc02d432e | hypatiad/codefigthtstests | /checkPalindrome.py | 494 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Given the string, check if it is a palindrome.
For inputString = "ana", the output should be
checkPalindrome(inputString) = true;
For inputString = "tata", the output should be
checkPalindrome(inputString) = false;
For inputString = "a", the output should be
checkPalindrome(inputString) = t... |
7d2b7c33e756b60003d97b54bb495aebb2c8cf31 | bitf14m513/schedulingalgo | /Preorityscheduling.py | 4,349 | 4 | 4 | print("------------------------Priority Scheduling Non Preempting-------------------")
t_count = int(input("Enter Total Number of Process : -> "))
jobs = []
def take_input():
for process in range(0, t_count):
at = 0
bt = 0
job_attr = {"process_name": "None", "AT": 0, "BT": 0, "ST"... |
7b549d7fad13846b90a4f439379c9dbfa7017207 | alimovAN19/1-3-9Test | /1-3-9NameGame.py | 1,493 | 3.890625 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
'''Alter the code to produce a different output if your name is entered. As always, start a log file
test your code. When it works, upload the code without changing the file name. Upload the log file to
the classroom alonf with your code'''
def w... |
ff96730fd2863c392f87d93e3dbd842ad063e88d | jhd/nntest | /sigmoid.py | 981 | 3.609375 | 4 | import itertools
import math
class Sigmoid():
weights = []
bias = []
weighedInput = None
activation = None
activationPrime = None
error = None
def __init__(self, startWeights=None, startBias=None):
self.weights = startWeights
self.bias = startBias
def sig(self,... |
8fbfdaca1191359762e5b2cb142b19de0ceb7a9a | noobcoderr/python_spider | /alien_invasion/bullet.py | 1,057 | 3.984375 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""a class that manage how a ship fire"""
def __init__(self,ai_settings,screen,ship):
"""create a bullet where ship at"""
super(Bullet,self).__init__()
self.screen = screen
#creat a bullet rectangle at (0,0) t... |
5b7ddd980eef5d63cc7cda3da0a9504a4a969a76 | MateusdeOliveira15/IFCE-PYTHON | /Lista/q9.py | 421 | 3.96875 | 4 | #Faça um programa que receba do usuário uma string e imprima a string sem suas vogais.
string = input('Digite uma string: ')
lista = list(string)
string_nova = []
for i in range(len(lista)):
if lista[i] != 'a' and lista[i] != 'e' and lista[i] != 'i' and lista[i] != 'o' and lista[i] != 'u':
string_nova.append(lis... |
034d4f75912f5e1a3e85ea3d83c28938d5fdaa2d | MateusdeOliveira15/IFCE-PYTHON | /Lista/q10.py | 451 | 4 | 4 | #Faça um programa em que troque todas as ocorrências de uma letra L1 pela letra L2 em
#uma string. A string e as letras L1 e L2 devem ser fornecidas pelo usuário.
string = input('Digite uma string: ')
letra1 = input('Digite uma letra: ')
letra2 = input('Digite outra letra: ')
string = list(string)
for i in range(l... |
98cf462c49a5227c9af6638e2589de8202bd961a | ajorve/pdxcodeguild | /objects/valet/valet.py | 857 | 3.875 | 4 | """
Create a car for color, plate # and doors.
Create a parking lot that will only fit to its capacity the cars created.
"""
class Vehicle:
def __init__(self, color, plate, doors):
self.color = color
self.plate = plate
self.doors = doors
def __str__(self):
ret... |
28192ec1a2ff45eab9f27fe8b1227a910adaba93 | ajorve/pdxcodeguild | /warm-ups/string_masking.py | 1,364 | 3.953125 | 4 | """
# String Masking
Write a function, than given an input string, 'mask' all of the characters with a '#' except for the last four characters.
```
In: '1234' => Out: '1234'
In: '123456789' => Out: '#####6789'
"""
# def string_masking(nums_list):
# """
# >>> string_masking([1, 2, 3, 4, 5, 6, 7, 8... |
f81cd655babcadec3b45696091a852a56b8ccd92 | ajorve/pdxcodeguild | /warm-ups/wall-painting.py | 564 | 4 | 4 | """
This is a Multiline Comment. THis is the first thing in the file.
AKA 'Module' Docstring.
"""
def wall_painting():
wall_width = int(input("What is the width of the wall?"))
wall_height = int(input("What is the height of the wall?"))
gallon_cost = int(input("What is the cost of the gallon"))
... |
dfd38f505944aeb4fee6fa57bda110fa84952084 | ajorve/pdxcodeguild | /json-reader/main.py | 1,131 | 4.5 | 4 | """
Objective
Write a simple program that reads in a file containing some JSON and prints out some of the data.
1. Create a new directory called json-reader
2. In your new directory, create a new file called main.py
The output to the screen when the program is run should be the following:
The Latitude/Longi... |
dbfe81b01a012a936086b78b5344682238e88ea5 | ajorve/pdxcodeguild | /puzzles/fizzbuzz.py | 1,145 | 4.375 | 4 | """
Here are the rules for the FizzBuzz problem:
Given the length of the output of numbers from 1 - n:
If a number is divisible by 3, append "Fizz" to a list.
If a number is divisible by 5, append "Buzz" to that same list.
If a number is divisible by both 3 and 5, append "FizzBuzz" to the list.
If a number meets none ... |
cbb5dfcd92d734e476075cc01b063ce611826b92 | ajorve/pdxcodeguild | /warm-ups/sum_times.py | 1,245 | 3.890625 | 4 | """
Weekly warmup
Given a list of 3 int values, return their sum.
However, if one of the values is 13 then it does not count towards the sum and values to its right do not count.
If 13 is the first number, return 0.
In: 1, 2, 3 => Out: 6
In: 5, 13, 6 => Out: 5
In: 1, 13, 9 => Out: 1
"""
import time
de... |
5733f941bb23cec0470a41d4bb6ab1f78d86bd73 | ajorve/pdxcodeguild | /warm-ups/pop_sim.py | 2,021 | 4.375 | 4 | """
Population Sim
In a small town the population is 1000 at the beginning of a year.
The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town.
How many years does the town need to see its population greater or equal to 1200 inhabitants?
Write a fun... |
df1f704b954ec8d3d0680b2776a7afaf3ba4357f | redashu/augmenu2018 | /day2.py | 351 | 4 | 4 |
import time
print "Hello world "
x=10
y=20
time.sleep(2)
print x+y
# taking input from user in python 2
n1=raw_input("type any number1 : ")
n2=raw_input("type any number2 : ")
z=int(n1)+int(n2)
time.sleep(2)
print "sum of given two numbers is : ",z
'''
take 5 input from user and make a tuple with o... |
a8ae1110868b0bd4845ac1ee59fc4b3c27ccbc1e | Lite-Java/KNN | /KNN.py | 789 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 21:46:15 2018
@author: 刘欢
"""
import numpy as np
class NearestNeighbor:
def _init_(self):
pass
def train(self,X,y):
"""X is N X D where each row is an example.y is 1-dimension of size N"""
self.Xtr=X
self.ytr=y
def predict(se... |
d13b5bdd1b380482a8ee433c8b513a830a01bb4d | tangmingsheng/Python_Learn | /20190611_语言元素.py | 435 | 3.859375 | 4 | # f=float(input("请输入华氏温度"))
# c=(f-32)/1.8
# print("%.1f华氏温度 = %.1f摄氏度"% (f,c))
# import math
# radius = float(input("请输入圆周半径:"))
# perimeter = 2 * math.pi * radius
# area = math.pi * radius * radius
# print("周长:%.2f" % perimeter)
# print("面积:%.2f" % area)
year = int(input("请输入年份:"))
is_leap = (year % 4 == 0 and ye... |
fd2a8b080bd4435fc8229279b5bbce26f782c677 | lahwaacz/Scripts | /pythonscripts/misc.py | 2,184 | 3.71875 | 4 | #! /usr/bin/env python
"""
Human-readable file size. Algorithm does not use a for-loop. It has constant
complexity, O(1), and is in theory more efficient than algorithms using a for-loop.
Original source code from:
http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
... |
1058223566e7c3af49e5df00ff6d6754b4d9088c | onwayWalk/aaa | /day02/xiaoyouxi.py | 294 | 3.796875 | 4 | import random
print("请输入一个数")
a=int(input())
b=random.randint(0,10)
while a!=b:
if a>b:
print("猜大了噢,再猜一次吧")
a=int(input())
else:
print ("猜小了哦,再猜一次吧")
a=int(input())
print ("太棒了,猜对了!")
|
5ec0e7fec324bb65eeb8484c83c50180db82d595 | onwayWalk/aaa | /day02/test06.py | 473 | 3.796875 | 4 | # 实现登陆系统的三次密码输入错误锁定功能(用户名:root,密码:admin)
print("qing shu ru zhang hao mi ma")
a,b=input().split()
i=1
username="root"
password="admin"
while 1:
if username==a and password==b:
print("deng lu cheng gong ")
break
elif i==3:
print("yong hu suo ding !")
break
else:
print(... |
b5f8bc0b3e61470c6bc6d779e470244f5a52a508 | onwayWalk/aaa | /day10_thread/test03.py | 1,459 | 3.6875 | 4 | from threading import Thread
import time
box=500
boxN=0
cus=6
class cook(Thread):
name=''
def run(self) -> None:
while True:
global box,boxN,cus
if boxN<box:
boxN+=1
print("%s做了一个蛋挞!,现在有%s个"%(self.name,boxN))
else:
if... |
4d6ce6a41f6ba8d94f67fc4e63a0d2b09cfd6eb7 | AyngaranKrishnamurthy/Python-Simple-Programs | /Single swap.py | 668 | 4.0625 | 4 | def swapstr(str1, str2):
len1 = len(str1)
len2 = len(str2)
if (len1 != len2): #Checks for if both the strings are of same length
return False
prev = -1
curr = -1
count = 0
i = 0
while i<len1: #Compares string for resemblence of elements
if (str1[i] != str2[i]): #Count... |
8b4fcea87d0a7ac318a2f9c0b0ae019175d7e291 | juan6630/MTIC-Practice | /Python/clase11.py | 1,273 | 4.15625 | 4 | def dos_numeros():
num1 = float(input('Ingrese el primer número'))
num2 = float(input('Ingrese el segundo número'))
if num1 == num2:
print(num1 * num2)
elif num1 > num2:
print(num1 - num2)
else:
print(num1 + num2)
def tres_numeros():
num1 = float(input('Ingrese el prime... |
b46ee7847c7fc4045af1a79fd52efc0616f8a616 | YoungWoongJoo/Learning-Python | /list/list1.py | 666 | 3.875 | 4 | """
리스트 rainbow의 첫번째 값을 이용해서 무지개의 첫번째 색을 출력하는 코드입니다. 3번째줄이 first_color에 무지개의 첫번째 값을 저장하도록 수정해 보세요.
rainbow=['빨강','주황','노랑','초록','파랑','남색','보라']
#rainbow를 이용해서 first_color에 값을 저장하세요
first_color =
print('무지개의 첫번째 색은 {}이다'.format(first_color) )
"""
rainbow=['빨강','주황','노랑','초록','파랑','남색','보라']
#rainbow를 이용해서 first_color... |
24442d594ecf27a0df3058aff922011d6953e8dc | YoungWoongJoo/Learning-Python | /bool/bool2.py | 733 | 4.46875 | 4 | """
or연산의 결과는 앞의 값이 True이면 앞의 값을, 앞의 값이 False이면 뒤의 값을 따릅니다. 다음 코드를 실행해서 각각 a와 b에 어떤 값이 들어가는지 확인해 보세요.
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format(a, b))
"""
a = 1 or 10 # 1의 bool 값은 True입니다.
b = 0 or 10 # 0의 bool 값은 False입니다.
print("a:{}, b:{}".format... |
55757b84c56e85cee15ca08b313294a7919b8564 | YoungWoongJoo/Learning-Python | /random/random1.py | 474 | 4 | 4 | """
https://docs.python.org/3.5/library/random.html#random.choice 에서 random.choice의 활용법을 확인하고, 3번째 줄에 코드를 추가해서 random_element가 list의 element중 하나를 가지도록 만들어 보세요.
import random
list = ["빨","주","노","초","파","남","보"]
random_element =
print(random_element)
"""
import random
list = ["빨","주","노","초","파","남","보"]
random_ele... |
f7b72f1287d5a2b3c61390235c41b2fd81681a5b | YoungWoongJoo/Learning-Python | /function/function2.py | 705 | 4.3125 | 4 | """
함수 add는 매개변수로 a와 b를 받고 있습니다. 코드의 3번째 줄을 수정해서 result에 a와 b를 더한 값을 저장하고 출력되도록 만들어 보세요.
def add(a,b):
#함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 result에 저장하고 출력하도록 만들어 보세요.
result =
print( "{} + {} = {}".format(a,b,result) )#print문은 수정하지 마세요.
add(10,5)
"""
def add(a,b):
#함수 add에서 a와 b를 입력받아서 두 값을 더한 값을 resul... |
cc2af962b0a91dfe357a9cee79571bff2e7449a6 | YoungWoongJoo/Learning-Python | /bool/bool1.py | 716 | 3.984375 | 4 | """
다음 코드를 실행해서 어느 경우 if문 안의 코드가 실행되는지 확인해 보세요.
if []:
print("[]은 True입니다.")
if [1, 2, 3]:
print("[1,2,3]은/는 True입니다.")
if {}:
print("{}은 True입니다.")
if {'abc': 1}:
print("{'abc':1}은 True입니다.")
if 0:
print("0은/는 True입니다.")
if 1:
print("1은 True입니다.")
"""
if []: #false
print("[]은 True입니다... |
b4f5e679116a4a68c30846b2128890f0bc53d8f5 | leeonlee/misc | /euler/5.py | 152 | 3.953125 | 4 | def isDivisible(number):
for i in range(20,1,-1):
if number % i != 0:
return False
return True
i = 2
while not isDivisible(i):
i += 2
print i
|
b5a4db5c966000f3b3126d5a75e4e33eba5793b8 | leeonlee/misc | /euler/4.py | 299 | 3.765625 | 4 | def palindrome(number):
return str(number)[::-1] == str(number)
def largest():
i = 999 * 999
j = 999
while i >= 100000:
if palindrome(i):
while j >= 100:
if i % j == 0 and len(str(j)) == 3 and len(str(int(i/j))) == 3:
print i
return
j -= 1
j = 999
i -= 1
largest()
|
7dfacf5c92af0747086f799b21abe106acd9b185 | 0x464e/comp-cs-100 | /8/pistekirjanpito_a.py | 988 | 3.765625 | 4 | """
COMP.CS.100 pistekirjanpito_a.
Tekijä: Otto
Opiskelijanumero:
"""
def main():
counted_scores = {}
try:
file = open(input("Enter the name of the score file: "), "r")
except OSError:
print("There was an error in reading the file.")
return
scores = []
for line in file:... |
2036aac98dd7e9ff312100e3625ce12d35b44bb6 | 0x464e/comp-cs-100 | /3/tulitikkupeli.py | 1,129 | 3.59375 | 4 | """
COMP.CS.100 tulitikkupeli.
Tekijä: Otto
Opiskelijanumero:
"""
def main():
total_sticks = 21
player = 0
# oli vissii ok olettaa et sielt
# tulee inputtina aina intti
sticks = int(input("Game of sticks\n"
"Player 1 enter how many sticks to remove: "))
while True:
... |
281d096877dfa31bad260fab583c547d4c70ca68 | 0x464e/comp-cs-100 | /3/yogi_bear.py | 702 | 3.90625 | 4 | """
COMP.CS.100 Old MacDonald Had a Farm -laulu.
Tekijä: Otto
Opiskelijanumero:
"""
# en usko et tätä joku manuaalisesti kattoo, mut
# jos kattoo, nii meni moti variablejen nimeämisen
# kaa, ne nyt on mitä sattuu :'_D
def repeat_name(name, count):
for _ in range(1, count+1):
print(f"{name}, {name} Bear... |
1e07d223937d4701534d7e5d0ead745167344c62 | 0x464e/comp-cs-100 | /6/tekstintasaus.py | 3,798 | 3.875 | 4 | """
COMP.CS.100 tekstintasaus.
Tekijä: Otto
Opiskelijanumero:
"""
def main():
print("Enter text rows. Quit by entering an empty row.")
inp = read_message() # "moro mitä kuuluu :D:D :'_D :-D"
max_length = int(input("Enter the number of characters per line: ")) # 12
# "list comprehension"
# l... |
80318b9873859647862039df26e805d293d16d18 | 0x464e/comp-cs-100 | /11/murtolukulista.py | 4,737 | 3.96875 | 4 | """
COMP.CS.100 murtolukulista.
Tekijä: Otto
Opiskelijanumero:
"""
class Fraction:
"""
This class represents one single fraction that consists of
numerator (osoittaja) and denominator (nimittäjä).
"""
def __init__(self, numerator, denominator):
"""
Constructor. Checks that the n... |
d749af202a4ee42fa4f5f79548febcab1b46e95e | vvvaish/Book-My-Movie | /mod1.py | 4,234 | 3.8125 | 4 | class operations:
def __init__(self,row,col):
self.row = row
self.col = col
self.cinema = []
for i in range(self.row + 1):
x = []
for j in range(self.col + 1):
if i == 0:
if j == 0 and j == 0:
... |
41ffebc58f2c3f35520955e2bdec311c4f103bf0 | NazguaL/UFOs | /game_functions/create_fleet.py | 1,744 | 3.734375 | 4 | from alien import Alien
def get_number_rows(ai_settings, ship_height, alien_height):
"""Определяет количество рядов, помещающихся на экране."""
available_space_y = (ai_settings.screen_height - (5 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return number_row... |
902271740940425156907021aecdd1d4c8b05d9e | visajkapadia/huffman-coding-python | /huffman.py | 2,951 | 3.671875 | 4 | start = None
class Node:
def __init__(self, letter, probability):
self.letter = letter
self.probability = probability
self.next = None
class LinkedList:
LENGTH = 0
def insertAtEnd(self, letter, probability):
node = Node(letter, probability)
global start
... |
8523f0d7a6dd5773e2b947e5302906f1f385187d | kevinwei666/python-projects | /hw1/solution1/Q4.py | 634 | 4.625 | 5 | """
Asks the user to input an integer. The program checks if the user entered an integer,
then checks to see if the integer is within 10 (10 is included) of 100 or 200.
If that is the case, prints ‘Yes’, else prints ‘No’.
Examples:
90 should print 'Yes'
209 should also print 'Yes'
189 should print 'No'
"""
#Get use... |
ec555598b456c810f86a0948aff0073e49bb2077 | kevinwei666/python-projects | /hw1/Q10-3.py | 387 | 3.84375 | 4 | #Given the following coefficients: 1, 3, 1
#Solve the quadratic equation: ax^2 + bx + c
#Here's a reminder of the quadratic equation formula
#https://en.wikipedia.org/wiki/Quadratic_formula
d = b^2 - 4ac
if d < 0:
print('no solution')
elif d = 0:
print(-b/2*a)
else:
solution1 = -b + d^0.5 / 2*a
solution... |
768be2ffc01f8e2e3dc1fd9e6971f63258d4e17d | ZombiMigz/Adventure-Rooms- | /startup.py | 1,273 | 3.78125 | 4 |
#player framework
class player:
def __init__(self):
pass
player = player()
player.maxhealth = 100
player.health = 100
#startup
def startup():
import framework
import main
framework.printunknown("Hello, what's your name?")
framework.guide('Type your name, then hit ENTER')
player.name... |
146b320e4fd906f1e9a40f63512007ccb6cbd836 | jemtca/Python-Development | /Scripting/email_sender/email_sender_static.py | 595 | 3.515625 | 4 | import smtplib # to create a SMTP server
from email.message import EmailMessage
email = EmailMessage()
email['from'] = '' # email (from)
email['to'] = [''] # email/emails (to)
email['subject'] = '' # email subject
email.set_content('') # email message
with smtplib.SMTP(host = '', port = 587) as smtp: # param1: SMTP ... |
cd4362ab4eb9b4521ffcd45b4355837d80ff6683 | HaaaToka/HUPROG19 | /final/Jenga/solveOkan.py | 1,090 | 3.5625 | 4 |
"""
1 <= Q <= 10
1< N <= 10^7
"""
q=int(input().strip())
# if not 1 <= q <= 10:
# print("1Constraints")
for _ in range(q):
n=int(input().strip())
# if not 1 < n <= 10**7:
# print("2Constraints")
txt=[]
tam,yarim=0,0
"""
yarim -> *-- , --*
tam -> -*-
"""
for __ in ra... |
56b8dad133fe4f9c472136e6a35dbd903625710c | creator-123/Sorting-Algorithm | /sort.py | 13,125 | 4.28125 | 4 | # -*- encoding: UTF-8 -*-
# 冒泡排序
def bubbleSort(nums):
"""
冒泡排序:每次与相邻的元素组成二元组进行大小对比,将较大的元素排到右边,小的元素排到左边,直至迭代完数组。
备注:将排好序的元素,放到最后面
"""
for i in range(len(nums) - 1): # 遍历 len(nums)-1 次
for j in range(len(nums) - i - 1): # 已排好序的部分不用再次遍历
... |
dd6c1d03c8a15228d5892ef94e20636941f989f8 | cjd1884/pyLectureMultiModalAnalysis | /classification/preprocessing.py | 1,674 | 3.578125 | 4 | from sklearn import preprocessing as pp
import pandas as pd
def do_preprocessing(df, categorical_columns=None):
df = standardize(df)
if categorical_columns is not None:
df = categorical_2_numeric(df, categorical_columns)
return df
def standardize(df):
'''
Standardizes the provided data... |
276a75d07f610dfad18575d23dcc26ba843be9aa | cjd1884/pyLectureMultiModalAnalysis | /old/av_merge.py | 1,958 | 3.59375 | 4 | '''
Short description: Script for merging associated video and audio files into a single medium using FFMPEG.
It expects that audio files are stored as `in_dir/audio/audio_k.mp4`
(and similarly for video) and stores the newly created file as `out_dir/media/medium_k.mp4`
'''
import ffmpy
import os
def main(in_dir='.... |
e61e9a0dd1533eca20ca131949e683b0d87aba71 | krisgrav/IN1000 | /3. oblig/lister.py | 2,125 | 3.9375 | 4 | #1
'''Programmet lager en liste med tre verdier. Deretter blir en fjerde verdi lagt til
i programmet. Til slutt printes den første og tredje verdien i listen.'''
liste1 = [1, 5, 9]
liste1.append(11)
print(liste1[0], liste1[2])
#2
'''Programmet lager en tom liste. Deretter brukes .append og en input-funksjon
til å sam... |
cc94647d2b34d67d0feea3bc0dca72a928b2fd61 | tsg-ut/esolang-battle-archive | /komabasai2018-day1/python3.py | 79 | 3.65625 | 4 | y=int(input())-2
x=int(input())
print("*"*x+("\n*"+" "*(x-2)+"*")*y+"\n"+"*"*x) |
21d842412724f3144975448a20ce0dc91e92d2fa | LuckyQingke/myrepository | /pythontest/test.py | 418 | 3.71875 | 4 | #dict
d={'cc':22,'bb':11,'mm':'00'}
if('cc' in d):
print(d['cc'])
print(d)
d['dd'] = 90
print(d)
d.pop('mm')
print(d)
def appendL(d):
d['ee']=99
appendL(d)
print(d)
#python迭代对象
for x in 'asdfg':
print(x)
for value in enumerate([1,2,3]):
print(value)
for i,value in enumerate([1,2,3]):
print(i,value)
L1 = ['Hel... |
cfa8167b3df46123ee695b344e9025d91dad2673 | kaido89/General | /tools_API/ldap/ldap_api.py | 1,186 | 3.515625 | 4 | #!/usr/bin/env python3
from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES
def main():
ldap_server = input('LDAP SERVER url (eg. example.com): ')
# it should be the ldap_server
server = Server(ldap_server, get_info=ALL)
# it should have the login user
ldap_user = ... |
9cc7bbd72c1e4a79e101815dd46b4964c2d7306d | wflosin/Code-Portfolio | /Python/combatgame.py | 18,018 | 3.953125 | 4 | import time
import random
def main():
#[a,b,c, d]
#[0] is the monster's health,
#[1] is its speed,
#[2] is its damage,
#[3] is its armour class
goblin = [8, 2, 4, 2]
spider = [12, 5, 6, 4]
dragon = [30, 7, 10, 7]
smiley = [21, 6 , 8, 1]
weapon = None
print("This is a combat simulator")
time.sleep(1)
... |
291afaa5eb6a3a5e8a87f945826cf9b93d872d7e | jgjefersonluis/python-pbp | /secao02-basico/aula27-lacorepeticao/main.py | 188 | 3.84375 | 4 | # Faça um laço de repetição usando o comando while começando com o valor 50
# até 100
a = 50 # variavel
while a <= 100: # condição
print(a) # instrução
a = a + 1
|
7a4ce4b010222efd9670600554c384f40fc040fc | jgjefersonluis/python-pbp | /secao01-introducao/variaveis/main15-time.py | 387 | 3.640625 | 4 | import time
#declarando as variaveis
num = 2
num1 = 3
data_hota_atual = time.asctime()
num2num = 5
#Usando os valores das variaveis para produzir texto
print("variavel com apenas letras %i" %num)
print("variavel com letras e numero no final %i" %num1)
print("variavel com caractere especial uderline ", data_hota_atual... |
ace87f462bb896fa3a87a0a89c71569ef676e01f | jgjefersonluis/python-pbp | /secao02-basico/aula02-variaveis-comandos/float.py | 82 | 3.53125 | 4 | # Float
# Ponto Flutuante
a = float(input('Digite um valor decimal: '))
print(a) |
d37b7a9f7bbfbc9b2a247ccb2988c220d802bf95 | jgjefersonluis/python-pbp | /secao01-introducao/operadoreslogicobooleanos/main.py | 222 | 3.828125 | 4 | # AND = Dois valores verdades
# OR = Um valor verdade // Dois falsos
# NOT = Inverte o valor
a = 10
b = 5
sub = a - b
print(a != b and sub == b)
print(a == b and sub == b)
print(a == b or sub == b)
print(not sub == a)
|
5dfecf790c2ed3a9623301cdf7c1d112e76cbc25 | jgjefersonluis/python-pbp | /secao02-basico/aula23-aumentosalarial/main.py | 444 | 3.78125 | 4 | # Escreva um programa para calcular aumento salarial, se o valor do salario for maior que R$ 1200,00
# o percentual de aumento será de 10% senao sera de 15%.
salario = float(input('Digite o seu salario: '))
# condições
if salario > 1200:
pc_aumento = 0.10
aumento = salario * pc_aumento
if salario <= 1200:
... |
6002c33a5aa29c39155830b6b9f066f5d21c0a1b | AbhilashMathews/gp_extras | /examples/plot_gpr_manifold.py | 4,013 | 3.75 | 4 | # Authors: Jan Hendrik Metzen <janmetzen@mailbox.org>
#
# License: BSD 3 clause
"""
==============================================================================
Illustration how ManifoldKernel can exploit data on lower-dimensional manifold
==============================================================================... |
572a81171d108cd73f3ea478253c06b442eeef51 | kyhuudong/Learn-Algorithm | /MatrixKeanuReeves/MatrixCheckTriangleTopAndBot.py | 478 | 3.53125 | 4 | M1 = [
[2,3,4],
[0,5,7],
[0,0,7]]
M2 = [[7,0,0],
[7,5,0],
[4,3,2]]
def TriangleTopMatrix(M):
for i in range(1,len(M)):
for j in range(i):
if(M[i][j] != 0):
return False
return True
def TriangleBotMatrix(M):
for i in range(len(M)):
for j... |
c4003359c66806d171bc8d22855e75c40bb854a1 | isotomurillo/Programacion | /Python/Pila/forma lista parcial.py | 304 | 3.75 | 4 | def formarList(num):
if isinstance (num,int) and (num>0):
return pares(num)
else:
return "Número Incorrecto"
def pares(num):
if num==0:
return[]
elif (num%10)%2==0:
return Lista[num%10]+pares(num//10)
else:
return pares(num//10)
|
e19fc7953dc495fef5987d49d2a6febb41042ef5 | igorsobreira/playground | /problems/notifications.py | 1,151 | 4.1875 | 4 | '''
Eu tenho um objeto da classe A que muda muito de estado e objetos das classes
B e C que devem ser notificados quando o objeto da classe A muda de estado.
Como devo projetar essas classes?
'''
class Publisher(object):
def __init__(self):
self.status = "FOO"
self._subscribers = []
... |
474203b4cfbb1ebb634431a2eed392f539a98f6e | igorsobreira/playground | /problems/project_euler/20.py | 258 | 3.90625 | 4 | #-*- coding: utf-8 -*-
'''
n! means n × (n − 1) × ... × 3 × 2 × 1
Find the sum of the digits in the number 100!
'''
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print sum( [ int(n) for n in str(factorial(100)) ] )
|
d4f45f0640ce0cd0e066ce92db1c3be386570eed | jmorton89/Portfolio | /Code Golf- Fizzbuzz.py | 111 | 3.71875 | 4 | for i in range(1,101):
if i%3==0 and i%5==0:i='FizzBuzz'
elif i%3==0:i='Fizz'
elif i%5==0:i='Buzz'
print(i) |
e095d54de54855fbf5c006b6fe47ee93e51fd5ba | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/11.Top View of Binary Tree .py | 1,394 | 4.28125 | 4 | """
Top View of Binary Tree
Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 ... |
feedbf88435af6b186da9dcd85041587edcee515 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/6.Inorder Tree Traversal – Iterative and Recursive.py | 1,406 | 3.921875 | 4 | """
Inorder Tree Traversal – Iterative and Recursive
Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
output = 4 2 1 7 5 8 3 6
... |
7629f38b20e5dd43ceda19cceb9e68a7386adee0 | DinakarBijili/Data-structures-and-Algorithms | /SORTING AND SEARCHING/18.K-th element of two sorted Arrays.py | 1,027 | 4.25 | 4 | """
K-th element of two sorted Arrays
Given two sorted arrays arr1 and arr2 of size M and N respectively and an element K. The task is to find the element that would be at the k’th position of the final sorted array.
Example 1:
Input:
arr1[] = {2, 3, 6, 7, 9}
arr2[] = {1, 4, 8, 10}
k = 5
Output:
6
Explanation:
The... |
90c36140e441af6d4d68bc6b4199e42038ae31d2 | DinakarBijili/Data-structures-and-Algorithms | /Algorithms/Sorting_Algorithms/5.Quick_sort.py | 930 | 4.0625 | 4 | # Quick Sort using Python
# Best = Average = O(nlog(n)); Worst = O(n^2)
#Quick sort is divide-and-conquer algorithm. it works by a selecting a pivot element from an array and partitionong the other elements into two sub-array.
# according to wheather their are less that or greaterthan the pivot. the sub-arrays are t... |
6d66d78b7774086fa047257b28fd2d3d83c7d7ca | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/10.min_no._of_jumps_to_reach_end_of_arr.py | 1,639 | 4.1875 | 4 | """
Minimum number of jumps
Given an array of integers where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
Exa... |
ecc51e9f138f6e8d3cfeeb04fab9a9c45edc2ce8 | DinakarBijili/Data-structures-and-Algorithms | /STACK AND QUEUE/2.Queue(FIFO).py | 2,870 | 3.9375 | 4 | """
Queue (First<-In First->Out )
Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.
The difference... |
4bd049da90d733d69710804afaa9b5352667caf3 | DinakarBijili/Data-structures-and-Algorithms | /SORTING AND SEARCHING/7.Majority Element.py | 900 | 4.40625 | 4 | """
Majority Element
Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
Example 1:
Input:
N = 3
A[] = {1,2,3}
Output:
-1
Explanation:
Since, each element in
{1,2,3} appears only once so t... |
07c39032e44ce00d6df3d3b1306ebb5e0fbb0ce5 | DinakarBijili/Data-structures-and-Algorithms | /STRING/Edit Distance.py | 1,182 | 4.0625 | 4 | """
Edit Distance
Given two strings s and t. Find the minimum number of operations that need to be performed on str1 to convert it to str2. The possible operations are:
Insert
Remove
Replace
Example 1:
Input:
s = "geek", t = "gesek"
Output: 1
Explanation: One operation is required
inserting 's' between two 'e'... |
a6b70b95e2abd954adf5c0ef7884792630fc1e5e | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Rotate Doubly linked list by N nodes.py | 2,692 | 4.1875 | 4 | """
Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list.
N = 2
Rotated List:
Examples:
Input : a b c d e N = 2
Output : c d e a b
Input : a b c ... |
6fc2e1d949f0bfaa8b60947c38faf8e435a41a73 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/1.Level order traversal.py | 1,352 | 4.125 | 4 | """
Level order traversal
Given a binary tree, find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree.
Example 1:
Input:
1
/ \
3 2
Output:1 3 2
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output:10 20 30 40 60 N N
"""
c... |
1c32e5e226de7d4f2d1e3711911554730b406f9a | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Check if Linked List is Palindrome.py | 2,064 | 4.21875 | 4 | """
Check if Linked List is Palindrome
Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not.
Example 1:
Input:
N = 3
value[] = {1,2,1}
Output: 1
Explanation: The given linked list is
1 2 1 , which is a palindrome and
Hence, the output is 1.
Example 2:
... |
af1eae902cacf9c3bbf7f609e763f01dc286edf0 | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/8.Postorder Tree Traversal – Iterative and Recursive.py | 3,014 | 4.0625 | 4 | """
Postorder Tree Traversal – Iterative and Recursive
Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
output:4 2 7 8 5 6 3 1
... |
dcd5db7c301734d0b7406153043d6e89ece94997 | DinakarBijili/Data-structures-and-Algorithms | /LINKED_LIST/Reverse a Linked List in groups of given size.py | 2,665 | 4.3125 | 4 | """
Reverse a Linked List in groups of given size
Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list.
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
K = 4
Output: 4 2 2 1 8 7 6 5
Explanation:
The first 4 elements 1,2,2,4 are reversed f... |
34da084f0c7ec038a9502cf05bfeb9d56baca684 | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/Palindromic Array.py | 431 | 3.75 | 4 | """
Example:
Input:
2
5
111 222 333 444 555
3
121 131 20
Output:
1
0
"""
def palindromic(arr, n):
rev = (arr[::-1])
if rev == arr:
return True
else:
return False
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int,inpu... |
da2f6f83dca1a4776eba5777e39cb41676e29f2a | DinakarBijili/Data-structures-and-Algorithms | /ARRAY/4.Sort_arr-of_0s,1s,and,2s.without_using_any_sortMethod.py | 971 | 4.375 | 4 | # Sort an array of 0s, 1s and 2s
# Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.
# Example 1:
# Input:
# N = 5
# arr[]= {0 2 1 2 0}
# Output:
# 0 0 1 2 2
# Explanation:
# 0s 1s and 2s are segregated
# into ascending order.
# Example 2:
# Input:
# N = 3
# arr[] = {... |
11960b0f8caeafeda8c4cffcfa4d90bf087ad4bd | DinakarBijili/Data-structures-and-Algorithms | /BINARY TREE/5.Create a mirror tree from the given binary tree.py | 1,605 | 4.375 | 4 | """
Create a mirror tree from the given binary tree
Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree.
Examples:
Input:
5
/ \
3 6
/ \
2 4
Output:
Inorder of original tree: 2 3 4 5 6
Inorder of mirror tree: 6 5 4 3 2
Mirro... |
1c01d4fdc49e7addb4a02b1e32959abfb4df5377 | GBXXI/LucidProgramming | /Algorithms/Look_n_Say_Sequence.py | 1,326 | 3.90625 | 4 |
# %% [markdown]
# ## String Processing: Look and Say Sequence.<br>
# The sequence starts with the number 1:<br>
# 1<br>
# We then say how many of each integer exists in the sequence to
# generate the next term.<br>
# For instance, there is "one 1". This gives the next term:<br>
# ... |
fc8c3b2a5970f408d17c0f2b89be8add746f63f4 | pronyushkin/learn1 | /l1l2/test2.py | 2,328 | 3.90625 | 4 | '''Еще набор тестовых заданий с интенсива.'''
from math import sqrt
def do_nothing():
'''Делаем ничего, возвращаем ничто.'''
return None
def test_info():
'''Тест работа со словарем.'''
user_info = {'first_name':'fn', 'last_name':'ln'}
print(user_info['first_name'], user_info['last_name'])
pr... |
1665a5752794a64a0de7e505e172a814c9b32e8f | andrewsanc/pythonFunctionalProgramming | /exerciseLambda.py | 282 | 4.15625 | 4 | '''
Python Jupyter - Exercise: Lambda expressions.
'''
# Using Lambda, return squared numbers.
#%%
nums = [5,4,3]
print(list(map(lambda num: num**2, nums)))
# List sorting. Sort by the second element.
#%%
a = [(0,2), (4,3), (9,9), (10,-1)]
a.sort(key=lambda x: x[1])
print(a)
#%%
|
3ee8c523fd80d72e388a4fe972ea834745909b28 | andrewsanc/pythonFunctionalProgramming | /lambda.py | 427 | 3.875 | 4 | '''
Python Jupyter - Lambda. Lambda expressions are one time anonymous functions.
lambda param: action(param)
'''
#%%
myList = [1,2,3,4]
print(list(map(lambda item: item*2, myList)))
print(myList)
#%%
words = ['alcazar', 'luci', 'duncan', 'sam']
print(list(map(lambda name: name.title(), words)))
#... |
4717d68b14a296bc895da87ff083cb2db711e551 | vik407/holbertonschool-interview | /0x10-rain/0-rain.py | 538 | 3.625 | 4 | #!/usr/bin/python3
""" 0_rain.py
"""
def rain(walls):
""" Return rainwater trapped with array of wall heights.
"""
i, j = 0, len(walls) - 1
lmax = rmax = res = 0
while i < j:
if walls[j] > walls[i]:
if walls[i] > lmax:
lmax = walls[i]
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.