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 |
|---|---|---|---|---|---|---|
c4cc36bdff6336fb22350f9eeeabef7454c9e065 | freebz/Learning-Python | /ch17/ex17-16.py | 627 | 3.671875 | 4 | # 실제 동작하는 nonlocal
# c:\python36\python
def tester(start):
state = start # 일반적으로 비지역 변수의 참조는 가능함
def nested(label):
print(label, state) # 바깥쪽 범위의 상태를 기억함
return nested
F = tester(0)
F('spam')
# spam 0
F('ham')
# ham 0
def tester(start):
state = start
def nested(label):... |
e4ef854e66387c2c8e30cdba0d44e8a366845f95 | freebz/Learning-Python | /ch28/ex28-3.py | 594 | 3.859375 | 4 | # 진행하면서 테스트하기
# 증가하는 셀프 테스트 코드 추가하기
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
bob = Person('Bob Smith') # 클래스를 테스트
sue = Person('Sue Jones', job='dev', pay=100000) # __init__ 이 자동으로 수행
print(bob.n... |
fd80eb2afffe8a6547b77be276ad0ea50c33241e | freebz/Learning-Python | /ch32/ex32-24.py | 1,032 | 3.921875 | 4 | # 정적 메서드의 대안
def printNumInstances():
print("Number of instances created: %s" % Spam.numInstances)
class Spam:
numInstances = 0
def __init__(self):
Spam.numInstances = Spam.numInstances + 1
# py -3
import spam
a = spam.Spam()
b = spam.Spam()
c = spam.Spam()
spam.printNumInstances() # 하... |
f42ad89022293a7232c39238a259419a56a7e03f | freebz/Learning-Python | /ch09/ex9-4.py | 2,094 | 3.625 | 4 | # 왜 리스트와 튜플이 존재하는가?
# 레코드 다시보기: 명명된 튜플
bob = ('Bob', 40.5, ['dev', 'mgr']) # 튜플 레코드
bob
# ('Bob', 40.5, ['dev', 'mgr'])
bob[0], bob[2] # 위치에 의한 접근
# ('Bob', ['dev', 'mgr'])
bob = dict(name='Bob', age=40.5, jobs=['dev', 'mgr']) # 딕셔너리 레코드
bob
# {'name': 'Bob', 'age': 40.5, 'jobs': ['dev',... |
c7965587326ebee26dd416a55bd4a94bbc27d68f | freebz/Learning-Python | /ch20/ex20-7.py | 654 | 3.796875 | 4 | # 왜 제너레이터 함수인가?
def buildsquares(n):
res = []
for i in range(n): res.append(i ** 2)
return res
for x in buildsquares(5): print(x, end=' : ')
# 0 : 1 : 4 : 9 : 16 :
for x in [n ** 2 for n in range(5)]:
print(x, end=' : ')
# 0 : 1 : 4 : 9 : 16 :
for x in map((lambda n: n ** 2), range(5)):
print... |
4120e57b84cffa7815e26edd73c073795c2f63cb | KostasAngel/Visualization-of-Path-finding-Algorithms | /path_finding_algorithms/utils.py | 11,195 | 3.546875 | 4 | import itertools
import random
from collections import deque
from heapq import heappop, heappush
from time import sleep
import numpy as np
from asciimatics.screen import ManagedScreen
class Grid(object):
EMPTY, WALL = 0, 1
def __init__(self, custom_grid: np.ndarray = None, size: int = 64, create_maze: bool ... |
834460ddbe1880e8f4e9f195404274ae3cbae0a8 | mjlabe/python-atlassian-server-api | /atlassian_server_api/jira.py | 6,655 | 3.5 | 4 | import requests
import json
import ntpath
class Jira:
"""Common JIRA API methods.
JIRA's REST APIs provide access to resources (data entities) via URI paths. To use a REST API, your application will
make an HTTP request and parse the response. The JIRA REST API uses JSON as its communication format, and ... |
aa478143bf9f657b6938650e8d174dcb016d5f39 | Yvonnekatama/control-flow | /conditionals.py | 875 | 4.125 | 4 | # if else
age=25
if age >= 30:
print('pass')
else:
print('still young')
# ternary operator
temperature=30
read="It's warm today" if temperature >= 35 else "Wear light clothes"
print(read)
# if elif else
name='Katama'
if name=='Yvonne':
print('my name')
elif name=='Katama':
print("That's my sur name")
el... |
ba879f9267030e8bca105ef5c6703e037035235f | Imraneouelfaquir98/ML-Project-Regression | /regression.py | 6,513 | 3.546875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv
# Loading Dataset
url = "Part1_data12.csv"
dataset = pd.read_csv(url)
#Shape : Dimensions of the dataset
print("Dimension = {0:d}*{1:d}".format(dataset.shape[0],dataset.shape[1]))
dataframe = pd.DataFrame(dataset)
dataframe_mixed = dat... |
348f4839b932413385008e87f510a0d688f8a241 | holounic/university | /linear-algebra/labs/ray-tracing.py | 4,517 | 3.5625 | 4 | input_file = 'input.txt'
output_file = 'output.txt'
class Form():
def __init__(self, A, B, C):
self.A = (B.y - A.y) * (C.z - A.z) - (C.y - A.y) * (B.z - A.z)
self.B = -((B.x - A.x) * (C.z - A.z) - (C.x - A.x) * (B.z - A.z))
self.C = (B.x - A.x) * (C.y - A.y) - (C.x - A.x) * (B.y - ... |
ee9e2becf70d3d9fc94ee4b6121913fa3cffd1ce | maloMal/Spirograph | /drawCircle.py | 345 | 4.28125 | 4 | import math
import turtle
#Draw the circle using turtle.
def drawCircleTurtle(x, y, r):
#move to the start of circle
turtle.up()
turtle.setpos(x + r, y)
turtle.down()
#Draw the circle
for i in range(0, 365, 6):
a = math.radians(i)
turtle.setpos(x + r*math.cos(a), y + r*math.sin(a))
drawCircleTurtle(100, 1... |
38cbb8118d90637c886f35ca1b2c7da1b4f04f42 | u200915986/estimagic | /estimagic/differentiation/first_order_auxiliary.py | 2,657 | 3.53125 | 4 | """
This module contains auxiliary functions for a one step differentiation.
"""
def central(func, f_x0, params_sr, var, h, *func_args, **func_kwargs):
"""
Calculate the central difference.
Args:
func (fucntion): A function that maps params_sr into a float.
f_x0 (func output): The function... |
77e32f39b9d01657b7e37d45d4d49b3ed23516ae | hakudaku/hakudaku | /search_replace_file_input.py | 731 | 3.84375 | 4 | #!/usr/bin/python -tt
##If need to replace string with a different string for a bunch of files##
##Create a file and list all the filenames which need the search and replace of a string##
##The path variable will define the location of said filenames##
##The files list will have all the file names which need the sear... |
cea714964e2c72f0a842ed1c9d9252de459bea5a | jinbao-x/python | /pycharm/39--函数的可变参数.py | 299 | 4.03125 | 4 | # 可变参数或不定长参数(*args,**kwargs)
def add(x, y, *args, **kwargs):
print(x)
print(y)
print(*args) # 拆包
print(args) # 未拆包,返回元组
print(kwargs) # 字典
# print(**kwargs)
add(1, 2, 3, 4, 5, 6, 7, 8)
add(1, 2, 3, 4, 5, 6, 7, 8, 9, a=1, b=2)
|
86f9702d32f5c1bac3994b1611606a5cd7484e00 | jinbao-x/python | /pycharm/27--字典的增删改查.py | 1,171 | 3.5 | 4 | # 字典的增删改查
d = {}
d['id'] = 1
d['name'] = 'tom'
d['性别'] = '男'
d['性别'] = '女' # 用这种方式添加键值对,如果键已经存在,则会进行更新
d['爱好'] = '看书'
print(d)
# 字典的添加
d['手机'] = 13456778988
d.setdefault('婚姻状况', '已婚') # 用这个也能添加,不过和上边区别在于,这个不会更新已经存在的键,如果键已经存在,则不作处理
d.setdefault('婚姻状况', '未婚')
print(d)
# 字典的删除操作,根据键删除
d.pop('爱好')
print(d)
# d.popitem(... |
e003232f099f87dd09007dda11ea6463b9771320 | jinbao-x/python | /pycharm/11--打印前100的整数和.py | 95 | 3.59375 | 4 | # 计算前100个整数的和
i = 1
Sum = 0
while i <= 100:
i += 1
Sum += i
print(Sum)
|
b98865fd4ac55066d3d455240c57b937c1474705 | jinbao-x/python | /pycharm/19--for循环嵌套.py | 157 | 3.765625 | 4 | # 用for循环打印乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print('{} * {} = {} '.format(j, i, j * i), end='')
print()
|
b2dd5edca74bbaf3b84d66d2ab951c470e839ba7 | jinbao-x/python | /pycharm/54--类属性.py | 936 | 4 | 4 | class Dog():
def __init__(self, name): # 这种是实例属性
self.name = name
hashiqi = Dog('哈士奇')
print(hashiqi.name)
# 现在想实现一个功能:想知道总共有多少个对象是这个类里的,也就是这个类有多少个实例
class Person():
count = 0 # 这里是类属性,相当于函数版的全局变量,用于统计实例数量
def __init__(self, name): # 这种是实例属性
self.name = name
Person.count += ... |
f3565f9de9d93808343b03403be9f81b6b0c4aef | jinbao-x/python | /pycharm/80--三大式之列表推导式.py | 2,069 | 3.921875 | 4 | # 列表推导式:生成列表
ls = []
for i in range(10):
ls.append(i)
print(ls)
# 上面生成列表的方式还是有点复杂,下面使用列表推导式,简单地生成列表
ls1 = [i for i in range(10)] # 这样把i写在最前面,然后后面跟上for结构,循环后的结果会自动添加到列表里
print(ls1)
# 如果要把10里的偶数这样的判断也放到列表推导式里呢?
ls2 = [i for i in range(10) if i % 2 == 0] # 其实无非就是把几个简单的结构放到一个列表里,最前面写上结果
ls3 = [i for i in range(5) ... |
da2271d95f988d13eedc85984240ca2a8e5c676b | jinbao-x/python | /pycharm/35--常用的字符串处理函数.py | 857 | 3.796875 | 4 | # 统计字符出现次数
s = 'zhangsan'
print(s.count('a'))
# 替换字符
print(s.replace('a', 'f', 1)) # 第三位是替换次数
# split分割字符串
print(s.split('a'))
# 判断是否以某字母开头
print(s.startswith('z'))
# 去掉左右两侧的空格以及换行
s = ' wangwu\n'
print(s)
print(s.strip()) # 去掉两边的空格或换行
print(s.rstrip()) # 去掉右边的...
print(s.lstrip()) # 去掉左边的...
# 拼接字符串
s1 = 'lis... |
e182b7f6af1f92f21702648eb19b6729d8487aeb | jinbao-x/python | /pycharm/40--用组合参数函数计算所有参数和.py | 279 | 3.78125 | 4 | def add(x, y, z=3, *args, **kwargs):
isum = 0
isum = x + y + z
for i in args:
isum += i
for j in kwargs.values(): # .values是获取字典的所有值
isum += j
print(isum)
add(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 11, 12, 13, a=1, b=45, c=89)
|
1068365b0c4c2f1c7a03122f93a968761f2b3372 | jinbao-x/python | /pycharm/53--私有方法.py | 1,115 | 3.75 | 4 | class Software_test():
def buy(self):
return '购买成功'
def check_money(self, money): # 看一下钱够不够
if money < 100: # 钱小于100买不了
print('钱不够')
else:
return self.buy() # 不加return仅仅只是调用,会导致在print这个check_money这个方法的时候会打印出来None,因此需要将这个调用方法返回
tianmao = Software_test()
print... |
92e1b86baec080df064de8a0a0dc631d8c437a42 | jinbao-x/python | /pycharm/45--匿名函数.py | 406 | 3.859375 | 4 | # 匿名函数的用法:
fun = lambda a, b: a + b # fun在这里是引用lambda,引用完之后就可以当作函数使用了
# 也就是:自定义函数名 = lambda 参数1, 参数2, 参数3: 表达式
result = fun(1, 2)
print(result)
# 匿名函数就是没有名字的函数,匿名函数只能有一个式子
# 匿名函数常用在比较简单的操作,复杂的还是需要使用def定义
|
6ce25f4538e064c95e5d13e1b7e7ac56825026b9 | jinbao-x/python | /pycharm/05--判断输入的年份是否是闰年.py | 435 | 3.96875 | 4 | # /除法运算除出来结果是啥就是啥,有小数时把小数也保留
# %取模,只保留余数
# //取整,只保留整数
year = int(input('请输入年份'))
# 一般地,能被4整除的年是闰年,但是如果是世纪年也就是整百年,必须要被400整除
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print('您输入的年份是闰年')
else:
print('您输入的年份是平年')
|
d082c145506d6277aedad99a9a983b82aef7e3a5 | rsowmyasowmi/python-programming | /Exno29.py | 162 | 4.09375 | 4 | time = float(input("Input time in minutes: "))
hour = time // 3600
time %= 3600
minutes = time // 60
time %= 60
print("d:h:m:s-> %d:%d:%d:%d" % (hour, minutes))
|
d7ed7dcfe46abd55dac2e284cda7fecaab4b51b1 | johnnylijr/Rocket_Elevators_Controllers | /Residential_Controllers.py | 5,239 | 3.53125 | 4 | import random
import time
class Elevator:
number_of_floors = 0
register_list = []
elevator_current_floor = 1
up = 1
down = -1
def __init__(self, number_of_floors, register_list):
self.number_of_floors = number_of_floors
self.register_list = register_list
def move(self):
... |
817f708d6806a8f5c718998913db0f4d1034ecd0 | safaa125/SpacedPractice | /economics.py | 2,339 | 3.9375 | 4 | from textwrap import dedent
print("hello there, made a change")
print("Will it commit?")
print("Merged success, how bout now when the branch does not exist on server?")
class ecoQuestions():
global score
score = 0
def questionOne():
qOne = str(input("True or False: One way inflation occurs when the... |
9810848ae1655cc2b1cd1106683e0b81000c3e8f | rostykusvasyl/StartDragon-m4_lesson3 | /name_in_bytes.py | 396 | 3.90625 | 4 | #! /usr/bin/python3
def name_in_bytes(name):
'''Програма виводить ім'я в байтах'''
print(f"Ваше ім'я в байтах - {name.encode('utf-8')}")
print("Натисніть 'Enter' для виходу з програми.")
while True:
name = input("Введіть ваше ім'я: ")
if name:
name_in_bytes(name)
else:
break
|
50dfd8950d1553b81148093ae115e03436f03e61 | jonathangjertsen/plappy | /io_connection_syntax.py | 2,162 | 3.515625 | 4 | from plappy.exceptions import ConnectionError
from plappy.io import Input, Output
### Creating inputs and outputs
i1 = Input('input-1')
i2 = Input('input-2')
o1 = Output('output-1')
o2 = Output('output-2')
# Here we will connect Input 1 to Output 1 and Input 2 to Output 2.
### Connections with dash or asterix synta... |
a4509cc29dfe24626d1f60e8c067b8078d039f75 | syurskyi/Math_by_Coding | /Programming Numerical Methods in Python/2. Roots of High-Degree Equations/2.1 PNMP_2_01.py.py | 287 | 4.15625 | 4 | '''
Method: Simple Iterations (for-loop)
'''
x = 0
for iteration in range(1,101):
xnew = (2*x**2 + 3)/5
if abs(xnew - x) < 0.000001:
break
x = xnew
print('The root : %0.5f' % xnew)
print('The number of iterations : %d' % iteration)
|
dbfbe507c21d1da89c6eeec4db7d686dcb0cbf1f | syurskyi/Math_by_Coding | /Programming Numerical Methods in Python/5. Numerical Integration/6.1 PNMP_5_03.py.py | 307 | 3.890625 | 4 | '''
Method: Simpson's 3/8 Rule
'''
from math import sin, pi
f = lambda x: x*sin(x)
a = 0
b = pi/2
n = 6
h = (b - a) / n
S = (f(a) + f(b))
for i in range(1, n, 3):
S += 3*(f(a + i*h) + f(a + (i+1)*h))
for i in range(3, n, 3):
S += 2*f(a + i*h)
Integral = 3*h/8 * S
print('Integral = %f' % Integral)
|
f0428f1204aad2152d4f348eee45ae4e58457b39 | syurskyi/Math_by_Coding | /Programming Numerical Methods in Python/3. Interpolation and Curve Fitting/5.1 PNMP_3_02.py.py | 487 | 3.75 | 4 | '''
Method: Newton Interpolation
'''
import numpy as np
x = [0.0, 1.5, 2.8, 4.4, 6.1, 8.0]
y = [0.0, 0.9, 2.5, 6.6, 7.7, 8.0]
n = len(x) - 1
xp = float(input('Enter x : '))
Dy = np.zeros((n+1,n+1))
Dy[:,0] = y
for j in range(n):
for i in range(j+1, n+1):
Dy[i, j+1] = (Dy[i,j] - Dy[j,j])/(x[i] - x[j])
yp =... |
07f4ac136d51f08d6612cee0b18baede8578023b | syurskyi/Math_by_Coding | /Programming Numerical Methods in Python/5. Numerical Integration/4.1 PNMP_5_02.py.py | 278 | 3.796875 | 4 | '''
Method: Simpson's 1/3 Rule
'''
from math import sin, pi
f = lambda x: x*sin(x)
a = 0
b = pi/2
n = 6
h = (b - a) / n
S = f(a)+f(b)
for i in range(1,n,2):
S += 4*f(a + i*h)
for i in range(2,n,2):
S += 2*f(a + i*h)
Integral = h/3 * S
print('Integral = %f' % Integral)
|
3cd50d9dff9b843211c9381b626a1872ac4a28e5 | soniyaindalkar/MarvellousPython | /Assignment1_2.py | 170 | 3.859375 | 4 | def ChkNum():
print("Enter a number")
no1=input()
if(int(no1)%2)==0:
print("Even Number")
else:
print("Odd Number")
ChkNum();
|
9bf50b6bbc253c77459dca6d106b104639f26a5b | 0LL13/pdf2textbox | /pdf2textbox/pdf2textbox.py | 24,539 | 3.515625 | 4 | '''
pdf2textbox.py
:param url: A URL pointing at a PDF file with max 3 columns and a header
:returns: Returns a dict containing text items that have been extracted from PDF
:raises NameError
:raises UnboundLocalError
:raises PDFTextExtractionNotAllowed
'''
import io
import os
import requests
from pdfminer.pdfinterp i... |
e2e9e67d4df35df1b4fec5b2b13a05f9ea26e11f | antjrodriguezz/Rock-paper-scissors | /roshambolizspock.py | 3,705 | 4.34375 | 4 | #Anthony Rodriguez 00306486
#12/8/20
#Intro to programming final
##
#In this program I will create a game of rock paper scissors lizard spoke, that will create and update a log
#of how many games it has played, who it has played with, and also keep track of how many times a player
#wins, loses or ties with the pr... |
6430372c54675bd5ca17f9c378923de14711e4bf | Anonna-Jannat/Room | /OopPoly.py | 1,551 | 3.796875 | 4 |
#DuckTyping
class pyCharm:
def execute(self):
print("Compiling")
print("Running")
class MyEditor:
def execute(self):
print("spell check")
print("convention check")
print("compiling")
class Laptop:
def code(self,ide):
ide.execute()
ide ... |
cba0545e9898c858e5affe9bfe40c2af59a788e6 | oliverbagos/Conway-s-Game_of_Life | /gameoflife.py | 1,488 | 3.703125 | 4 | #created by:Oliver Bagos
import random
import os, time
import itertools
clear = lambda: os.system('cls')
class GameOfLife(object):
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
life_queue = lambda: [random.randint(0, 1) for n in range(self.columns)]
self.ga... |
fbd6f7f2a0fa1cba4c76d2e8275b8ad1cabe5c3a | FedericoPonzi/TrasportiRomaBot | /bot/state.py | 475 | 3.640625 | 4 | class State:
"""Used to keep state of the conversation."""
FERMATA = 0
LINEA = 1
def __init__(self):
self.statesDict = {}
def getState(self, chat_id):
if chat_id in self.statesDict:
return self.statesDict[chat_id]
return None
def removeState(self, chat_id):... |
18ed24aec40e274ca49ebe7e21823a9c742034fb | Chunzhen/leetcode_python | /problem_46.py | 634 | 3.734375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
import copy
class Solution(object):
def __init__(self):
self.l=[]
def permute(self,nums):
"""
:type nums: List[int]
:rtype: List[List[str]]
"""
self.l=[]
self.find(nums,[],len(nums))
return self.l
def find(self,nums,tmp_l,n):
if len(tmp_l)==n:
self... |
cbbebbc2cf7b7d61be1288f32fdf7bdbd401980f | Chunzhen/leetcode_python | /problem_32.py | 657 | 3.5 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
def longestValidParentheses(self,s):
"""
:type s: str
:rtype: int
"""
stack=[]
longest=0
l=0
temp_l=0
for v in s:
if v=='(':
stack.append('(')
else:
if len(stack)>0 and stack[-1]=='(':
stack[-1]='1'
else:
... |
ecdda4350b5d3b6dcc0db707b558437d4c636c1e | Chunzhen/leetcode_python | /problem_162.py | 1,000 | 3.65625 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
def findPeakElement(self,nums):
"""
:type nums: List[int]
:rtype: int
"""
r=self.find(nums,0,len(nums)-1)
print 'r:',r
if r==0:
if nums[0]>nums[-1]:
return 0
else:
return len(nums)-1
else:
return r
def find(self,n... |
8c4b9109a2bc445164b9410ded9aa70d0a6d7fe2 | Chunzhen/leetcode_python | /problem_79.py | 1,901 | 3.71875 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class Solution1(object):
def exist(self,board,word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for i in range(len(board)):
for j in range(len(board[0])):
if self.find(board,word,i,j,0,set([])):
return True
return False
d... |
fdd5b0619fa76c930141ed4dbf487166a9f2be8b | Chunzhen/leetcode_python | /problem_166.py | 1,021 | 3.84375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
def fractionToDecimal(self,numerator,denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
is_fu=False
if (numerator<0 and denominator>0) or (numerator>0 and denominator<0):
is_fu=True
if numerator<0:
... |
dacd6a1bd24e23abdcb109195573fdf5c32bf82c | Chunzhen/leetcode_python | /problem_24.py | 829 | 3.953125 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def swapPairs(self,head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre=None
current=head
if head and head.next:
head=head.next
else:
return hea... |
232287b0dd123e7d3004ca4999eb30eaa926c6c7 | Chunzhen/leetcode_python | /problem_50.py | 438 | 3.84375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
def myPow(self,x,n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n>0:
if n%2==0:
return self.myPow(x*x,n/2)
else:
return self.myPow(x*x,n/2)*x
elif n==1:
return x
elif n==0:
return 1
else:
return s... |
20c4e259019858093096ce6a75aa8b48fc0a9dd2 | Chunzhen/leetcode_python | /problem_22.py | 713 | 3.84375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
class Solution(object):
def generateParenthesis(self,n):
"""
:type n: int
:rtype: List[str]
"""
if n==0:
return []
s=['(']
for i in range(1,2*n):
temp=[]
for v in s:
if self.is_valid(v+'(',n):
temp.append(v+'(')
if self.is_valid(v+')',n... |
995c5e8d0ebb7a3012580a18c3bc14fcc15b187b | koheron2/pyp-w1-gw-language-detector | /language_detector/main.py | 1,194 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
from collections import Counter
def detect_language(text, languages):
words_appearing = 0
selected_language = None
"""Returns the detected language of given text."""
for language in languages:
words = len([word for word in l... |
844b43cc123285669ff47ea1fea5fa8cc3104d33 | Mayankjh/Python_tkinter_initials | /tkinter.py | 697 | 3.71875 | 4 | from tkinter import*
root = Tk()
#thelabel = Label(root, text="This is our tkinter window")
#thelabel.pack()
#thelabell = Label(root, text="This is second tkinter sentence")
#thelabell.pack()
#topframe
#topframe = Frame(root)
#topframe.pack()
#botFrame = Frame(root)
#botFrame.pack(side=BOTTOM)
... |
2970e898dbf7767dded0fca56e0c7cc30b32c3b9 | bmallia/python_exercise | /source/symetric_difference.py | 890 | 4.125 | 4 | """
O termo matemático Symetric Difference (t ou B) de 2 conjuntos é um conjunto de elementos
no qualquer um dos conjuntos mas não em ambos. Por exemplo: A = {1,2,3} e B = {2,3,4},
A E B = {1,4}
Symetric difference é uma operação binária, isso significa que ela opera em apenas elementos.
Então para... |
daf9277b28facf92d104e938fa85fd69ef79470a | bigdata-icict/COVID-19 | /covid19/utils.py | 3,165 | 4.125 | 4 | from scipy.stats import lognorm, norm
import numpy as np
def make_normal_from_interval(lb, ub, alpha):
''' Creates a normal distribution SciPy object from intervals.
This function is a helper to create SciPy distributions by specifying the
amount of wanted density between a lower and upper bound. For exa... |
56c8303cdb074ce2b22c30848428613a1485ad3b | KBertok/servidorsockets | /dos_servidores/servidor1234/fechas_horario_permitido.py | 2,137 | 3.796875 | 4 | from datetime import datetime
def fechas_horario_permitido():
"""
Funcion: fechas_horario_permitido
descripcion: determina si la fecha y hora actual estan
en las fechas y horario permitidos
Primero se determina si la fecha esta comprendida
en el rango permitido, si no es asi retorna ... |
52be5919521ff4aa6cf0f513fb00e73a615c9ff8 | anasbouzid/Hello-AI | /CostFunction.py | 559 | 3.578125 | 4 | import math
import numpy as np
class CostFunction:
def __init__(self, name, fn, dFn):
self.name = name
self.fn = fn
self.dFn = dFn
CostFunction.quadratic = CostFunction(
name="quadratic",
fn=lambda actual, expected:
(actual - expected)**2,
dFn=lambda actual, expected... |
02108c5c0c81ed5d29db94e80c42de05e4ea957b | raghavddps2/Basic-Blog-Application-in-Flask | /app.py | 10,060 | 3.53125 | 4 | from flask import Flask, flash,redirect,url_for,session,logging,request
# Flask is basically for creating the flask app
#flash is basically for creating the flash messages.
#redirect is basically for redirecting.
#session is basically for logging in and logging out.
#request is basically for creating request.
from fla... |
7286d68878f8da83f0b272cfbc569187e7e0f845 | JsNoNo/Spark-Test-Program | /wordCountTest.py | 5,834 | 3.84375 | 4 | """
测试数据来源 Berkeley大学公开课程wordcount测试数据集
个人实现,仅供交流学习
"""
# 测试RDD
wordsList = ['cat', 'elephant', 'rat', 'rat', 'cat']
wordsRDD = sc.parallelize(wordsList, 4)
# Print out the type of wordsRDD
print type(wordsRDD)
# 记录处理 输入参数类型:string,输出参数类型:string
def makePlural(word):
return word + 's'
print makePlural('c... |
9a6a9c7d298189f7488c444c574ba6455713adaf | am3ience/Processes-vs-Threads | /Thread_Factor.py | 2,378 | 3.5625 | 4 | # -----------------------------------------------------------------------------
# FUNCTION: thread_factoring
#
# DATE: January 09, 2017
#
# DESIGNERS: Paul Cabanez
#
# PROGRAMMERS: Paul Cabanez
#
# NOTES:
#
#
#
#
#
# ----------------------------------------------------------------------------*/
... |
ed9c6d0b1ed6101d3aac0c6c75eaff51152b851d | joecmama/Python_0a | /02.py | 868 | 4.21875 | 4 | #!/usr/bin/env python
# basic math
print(2+3) # addition
print(2*3) # multiplication
print(2**3) # exponentiation
#
# # in python2: / means integer division (truncation) for integers
# # and floating pt division for floating point number
# #
# # in python3: / always means floating point division (like perl)
print(... |
77dec46a9d7fe561822d3ca4507ecbf773c433c0 | joecmama/Python_0a | /03.py | 469 | 4.28125 | 4 | #!/usr/bin/env python
# basic string operations
a = 'hello '
b = 'world'
c = a+b
print(c)
print(a == 'hello')
print(a < 'zebra')
print(a > 'zebra')
print(a < 'aardvark')
print(a != 'hello ')
#
print(c)
print(c.startswith('hello'))
print(c.endswith('world'))
print(len(c)) # length of a string
#
print('lo wo' in c) ... |
ac8a8be05ffba6290bd26af0337ed93ebcfdbcb5 | daily-coding-x-br/daily-coding | /may/10/roberto.py | 847 | 3.96875 | 4 | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def countUnivalTrees(node): # returns unival tree count
return helper(node)[0]
def helper(node): # returns (unival tree count, wether current node is a unival tree)
if node is N... |
013f979fb4665fa70324690d68c5dc8d147b0838 | daily-coding-x-br/daily-coding | /may/11/centa.py | 817 | 3.609375 | 4 | # Use dynamic programming!
#
# Let L[i] be the largest sum of non-adjacent elements on the subarray
# arr[0:i] and I[i] be the largest sum of non-adjacent elements on the
# subarray arr[0:i] including the last element (index i-1). Then:
#
# I[i] = arr[i-1] + L[i-2]
#
# L[i] = max(I[i], L[i-1])
#
# with L[0] = 0 and L[... |
72e813c30d115d50c7e60749133b1b12d57a0a49 | daily-coding-x-br/daily-coding | /may/26/centa.py | 2,005 | 3.984375 | 4 | class Node:
def __init__(self, parent=None, left=None, right=None):
self.parent = parent
self.left = left
self.right = right
self.locked = False
self.num_locked_descendants = 0
def is_locked(self):
return self.locked
def _can_toggle_lock(self):
"""R... |
8edcfec2a41d5f82ea30324844a18313b816c668 | daily-coding-x-br/daily-coding | /october/24/roberto.py | 528 | 3.515625 | 4 | import random
def evaluate(p):
r = random.random()
i = 0
r -= p[i]
while (r > 0 and i < len(p)-1):
i += 1
r -= p[i]
return i
def markov(m, starting_state, num_steps):
n = len(m)
count = [0] * n
t = starting_state
for i in range(num_steps):
p = m[t]
t = evaluate(m[t])
count[t] += 1
return count
st... |
c668cfd60874d398584fa39cf1003782d74cf029 | daily-coding-x-br/daily-coding | /august/31/roberto.py | 364 | 3.671875 | 4 | def canBePalindrome(s, k):
def helper(s, start, end, k):
if (k < 0):
return False
if (start > end):
return k >= 0
if (s[start] == s[end]):
return helper(s, start+1, end-1, k)
else:
return helper(s, start, end-1, k-1) or helper(s, start+1, end, k-1)
return helper(s, 0, len(s)-1, k)
s = input()
k ... |
2a5b4271a08dd11c8fc541898636aded4e9006b9 | daily-coding-x-br/daily-coding | /june/04/roberto.py | 556 | 3.640625 | 4 | def runningMedian(l):
left = maxHeap()
right = minHeap()
right.add(l[0])
median = l[0]
print(median)
even = True
for i in range(1, len(l)):
if (l[i] >= median):
right.add(l[i])
else:
left.add(l[i])
rebalance(left, right)
if (even):
median = left.peek() if len(left) > len(right) else right.peek()... |
b6b1b8be09b3339b8bf2b50a16ee327134b76b70 | daily-coding-x-br/daily-coding | /august/18/roberto.py | 277 | 3.625 | 4 | def canBeShifted(A, B):
return B in 2 * A
def canBeShifted2(A, B):
C = A * 2
for i in range(len(C) - len(B) + 1):
j = 0
while (j < len(B) and B[j] == C[i+j]):
j += 1
if j == len(B):
return True
return False
A = input()
B = input()
print(canBeShifted2(A, B))
|
66c12db2894f93890c16993cc06a421dd5fc6569 | daily-coding-x-br/daily-coding | /august/24/roberto.py | 816 | 3.96875 | 4 | def reverseWord(l, start, end):
for i in range((end - start)//2):
l[start + i], l[end - 1 - i] = l[end - 1 - i], l[start + i]
def reverseDelimiters(l, delimiters):
start, end = 0, len(l) - 1
while (start < end):
while (start < end and l[start] not in delimiters):
start += 1
while (start < end and l[end] no... |
5a285ae6cd603272c5bbad51e3323ec95762fa74 | daily-coding-x-br/daily-coding | /august/07/roberto.py | 1,432 | 3.71875 | 4 | class binaryTree:
def __init__(self, time=None, left=None, right=None):
self.time = time
self.left = left
self.right = right
def add(self, time):
if (time < self.time):
if (self.left):
self.left.add(time)
else:
self.left = binaryTree(time)
elif (time > self.time):
if (self.right):
self... |
1c125f2cc4dbb0b129fec57fe48fcfa87a1a9bd4 | daily-coding-x-br/daily-coding | /june/24/roberto.py | 380 | 3.796875 | 4 | class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, value):
self.stack2.append(value)
def pop(self):
if (len(self.stack1) == 0):
while (len(self.stack2) > 0):
self.stack1.append(self.stack2.pop())
return self.stack1.pop()
q = Queue()
n = int(input())
for i in range(n... |
896326be25a19aa1c90fd8dd3f999d988427cd7f | daily-coding-x-br/daily-coding | /august/17/roberto.py | 468 | 3.984375 | 4 | from collections import deque
class Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def printLevelWise(root):
queue = deque()
queue.append(root)
while (queue):
element = queue.popleft()
print(element.value)
if (element.left):
queue... |
e7cffccf92197b222e2e9ef8b4c4951b715b2e10 | daily-coding-x-br/daily-coding | /june/01/centa.py | 946 | 3.5 | 4 | # Not sure if optimal, I've never seen this one before
# O(n*log n) runtime and O(n) space complexity
import heapq
def trapped_water(walls):
total_water = 0
index_left = {}
height_left = []
water_level = 0
for i, right in enumerate(walls):
if right > water_level:
while heig... |
f5182642d5a99ce3c5ffecc0167f75c032d9a3bb | daily-coding-x-br/daily-coding | /june/06/centa.py | 462 | 3.671875 | 4 | def segregate_rgb(arr):
n = len(arr)
r_count, b_count = 0, 0
i = 0
while i < n - b_count:
if arr[i] == 'B':
arr[n - b_count - 1], arr[i] = arr[i], arr[n - b_count - 1]
b_count += 1
if arr[i] == 'R':
arr[r_count], arr[i] = arr[i], arr[r_count]
... |
9aab1d622d2bd839fbef110a419473ab3ca8cc28 | daily-coding-x-br/daily-coding | /may/30/centa.py | 1,390 | 3.828125 | 4 | # Two-pass algorithm
def justify_text(k, words):
lines = []
line_info = []
#assert(k <= max(list(map(len, words))))
# First pass to determine the number of words on each line
curr = { "words": 0, "chars": 0 }
for word in words:
print(word)
if len(word) + curr["chars"] <= k:
... |
690170d51cd1f93932925e019f01d1f7dd90712e | gladysmae08/project-euler | /problem19.py | 1,430 | 4.375 | 4 | # counting sundays
'''
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twe... |
eab4b877e46b5bcfc6f67b7acab8ca37c109ff2e | gladysmae08/project-euler | /problem4.py | 565 | 4.0625 | 4 | # largest palindrome of product of two 3-digit numbers
from test.test__locale import candidate_locales
max = 999
def palindrome(candidate):
candidate = str(candidate)
first = 0
last = len(candidate)-1
while last > first:
if candidate[first]!=candidate[last]:
return False
... |
5fefd63d816a8fcccac3f820afe84785768f44c5 | shyam10241/Second-Projects | /sorting.py | 352 | 3.921875 | 4 |
def insertion_sort(arr):
print("insertion sort :",arr)
l=len(arr)
for i in range(l-1):
for j in range(i+1,0,-1):
if arr[j]<arr[i]:
temp=arr[i]
arr[i]=arr[j]
arr[j]=temp
i=i-1
return arr
insert=[66,99,4,98,12]
var=in... |
9246512288641a6ca884d5a435fa466c30ba582a | rovansteen/google-foobar | /i-love-lance-janice/solution.py | 669 | 4 | 4 | def solution(input):
decrypted = []
for character in input:
if character.isalpha() and character.islower():
# Get the index of the character in the alphabet.
character_index = ord(character) - ord('a')
# Get the unicode position of the original character character.
... |
f3bb87c57cf4e9df5c4f75f429432c2d1e90136d | vikbi/Test-gapCounter | /code.py | 1,329 | 3.6875 | 4 | # program to count the consecutive zeros between the 1's of any integer binary form
def solution(N):
binaryDone = True
nums = []
# to generate the binary number from integer
while binaryDone:
d = N%2
nums.append(d)
if N > 1:
N = int(N / 2)
else:
b... |
76cd58a19b2d7bb0d13feef0fda247ad12e23d07 | francescomenazza96/birthdays | /main.py | 1,590 | 3.875 | 4 | import argparse
from birthdays_package.birthdays_module import (return_data,
return_index, return_set)
'''Given a name, it returns his/her birth day, death, homwtown an
name of the people born in the same century, according to different
level of verbosity'''
def parse_arguments():
parser = argparse.ArgumentParse... |
c9f7b46835e56102fd280a80f992b6b2a5d76cd3 | shubhamrocks888/linked_list | /create_loop_or_length_loop.py | 1,198 | 4.125 | 4 | class node:
def __init__(self,data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = None
def push(self,data):
new_node = node(data)
new_node.next = self.head
self.head = new_node
# Function to create a loop in the ... |
80b6ff56dcf3af1a144d865f7e826226f3f5862f | shubhamrocks888/linked_list | /print_from_end.py | 922 | 3.921875 | 4 | class node:
def __init__(self,data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = None
def push(self,data):
new_node = node(data)
new_node.next = self.head
self.head = new_node
def length(self):
cur_n... |
af2482476adc1c8fcfd28b1f9089d28d6bfd2c4c | Explorerqxy/review_practice | /043.py | 970 | 3.75 | 4 | def GetUglyNumber(index):
if index <= 0:
return 0
UglyNumbers = [0 for _ in range(index)]
UglyNumbers[0] = 1
nextUglyIndex = 1
Multiply2 = 0
Multiply3 = 0
Multiply5 = 0
while nextUglyIndex < index:
min = Min(UglyNumbers[Multiply2] *2, UglyNumbers[Multiply3] *3, UglyNumb... |
4cf4804428b54137822597b814c90e293b47425b | Explorerqxy/review_practice | /049.py | 397 | 3.625 | 4 | def GetNUmberSameAsIndex(numbers, length):
if numbers == None or length <= 0:
return -1
left = 0
right = length - 1
while left <= right:
middle = left + ((right - left) >> 1)
if numbers[middle] == middle:
return middle
if numbers[middle] > middle:
... |
5e82215b548f332f5f56d1270345d01d38db1c80 | Explorerqxy/review_practice | /025.py | 1,049 | 4.28125 | 4 | def PrintMatrixClockwisely(numbers, columns, rows):
if numbers == None or columns <= 0 or rows <= 0:
return
start = 0
while columns > start * 2 and rows > start * 2:
PrintMatrixInCircle(numbers, columns, rows, start)
start += 1
def PrintMatrixInCircle(numbers, columns, rows, start):... |
63d317023f7896fd0c607c18dd4472ac6817bd24 | Explorerqxy/review_practice | /062.py | 571 | 3.890625 | 4 | def multiply(array1, array2):
length1 = len(array1)
length2 = len(array2)
if length1 == length2 and length2 > 1:
array2[0] = 1
for i in range(1, length1):
array2[i] = array2[i -1] * array1[i -1]
tmp = 1
for i in range(length1 -2, -1,-1):
tmp *= array1... |
f8ab2d9dddbf41eb5d314874c919e75500781967 | TNowalk/thinkful | /pip/lpthw_ex_12.py | 322 | 4 | 4 | #!/usr/bin/python
'''
Learn Python the Hard Way
Exercise 12: Prompting People
@author Trevor Nowalk <tnowalk@thinkful.com>
@date 2014-01-16
'''
age = raw_input("How old are you?")
height = raw_input("How tall are you?")
weight = raw_input("How much do you weigh?")
print "So, you are %r old, %r tall, and %r heavy." %... |
0024d067cc8893f7fd9dca71d372226ad0919a42 | SoufianLa/hackerrankps | /Mini-Max-Sum/listL.py | 1,429 | 3.984375 | 4 | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def countNodes(self):
node = self.head
count = 1
while node.next is not None:
count += 1
node = node.nex... |
e966c4d2164dfa0d87f02147f9032aaacef84830 | SoufianLa/hackerrankps | /task_pairirng/run.py | 921 | 3.6875 | 4 | # !/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'taskOfPairing' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts LONG_INTEGER_ARRAY freq as parameter.
#
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def ... |
d26db6d80d3eeab324d75bdc1a7448f72fa89499 | SoufianLa/hackerrankps | /Mini-Max-Sum/main.py | 501 | 3.609375 | 4 | import math
import os
import random
import re
import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
final = list()
n = len(arr)
for i in range(n):
my = [arr[k] for k in range(n) if k != i]
final.ap... |
0a177979cd18e1ec482a5995404dab41b7a4ac20 | gtumuluri/W261-HW2 | /reducer2_2.py | 288 | 3.671875 | 4 | #!/usr/bin/python
import sys
# Initialize count, read lines from standard input
# and add up all words seen, print word and count
count = 0
for line in sys.stdin:
if count == 0:
words = line.strip()
words = line.split()
count += 1
print '%s\t%s' % words[0], count |
9966c88e72ffe60cffd450828be7b69a6b7db02b | 01Eddie/python_estructura2.0 | /Scripts/tabla.py | 1,643 | 3.953125 | 4 | #2. Crea un script llamado tabla.py que realice las siguientes tareas:
# Debe tomar 2 argumentos, ambos numeros positivos del 1 al 9, sino mostrará un error.
# El primer argumento hará referencia a las filas de una tabla, el segundo a las columnas
# En caso de no reducir uno o ambos argumentos, debe mostrar infor... |
66470d24c996bab0570c98c621a2663960d7e6b4 | PrasadRaoJ/Python-coding-challenges | /otp.py | 836 | 3.671875 | 4 | import random
from random import randint
choice =input('DO you want OTP: (y/n)')
if choice == 'y':
otp = random.randint(10000,99999)
print('Your OTP is: '+str(otp))
inp1 = int(input('Enter your OTP: '))
if otp == inp1:
print('Transaction is successful..!')
else:
i=0
... |
cb15a2789f629e4ee08f5935380bf5fe0763f488 | wengzhenqi/python | /99乘法表.py | 457 | 3.921875 | 4 | # for i in range(1, 10):
# for j in range(1, i+1):
# print('{}x{}={}\t'.format(j, i, i*j), end='')
# print()
# #
# for i in range(3):# i 控制打印几行
# for j in range(3):#内层循环控制一行内打印几次hello
# print('hello', end=' ')#print默认在结尾打印\n, 将结尾修改为空格
# print()
for i in range(1, 10):
for j in range(... |
5c3425d1ea3b7b364e893b2271d83b9dc553ea53 | varaljai/z9j.V-raljai | /while5.py | 228 | 3.640625 | 4 | a = True
while a:
mszam = int(input('Kérlek írj nekem egy páros számot!'))
paros = (mszam % 2 == 0)
paratlan= (mszam % 2 == 1)
if mszam and paros:
print('köszi')
break
elif mszam and paratlan:
print(a) |
47a42cfced82ca19f33265c6d5752766e7163756 | mariocpinto/0009_MOOC_Python_Data_Structures | /Exercises/Week_03/assignment_7_1.py | 502 | 4.6875 | 5 | # 7.1 Write a program that prompts for a file name,
# then opens that file and reads through the file,
# and print the contents of the file in upper case.
# Use the file words.txt to produce the output below.
# You can download the sample data at http://www.pythonlearn.com/code/words.txt
file_name = input('Enter Fi... |
55a730379685d64d717df81c1306430f6c6c5255 | brash99/phys441 | /nmfp/Cpp/cpsc217/area_triangle_sides.py | 775 | 4.25 | 4 | #!/usr/bin/env python
import math
s1 = input('Enter the first side of the triangle: ')
s2 = input('Enter the second side of the triangle: ')
s3 = input('Enter the third side of the triangle: ')
while True:
try:
s1r = float(s1)
s2r = float(s2)
s3r = float(s3)
if s1r<=0 or s2r<=0 or... |
c8216213d129bd12d845771e8a87f7b06eeb11fa | brash99/phys441 | /digits.py | 783 | 4.21875 | 4 | digits = [str(i) for i in range(10)] + [chr(ord('a') + i) for i in range(26)] # List of digits: 0-9, a-f
num_digits = int(input("Enter the number of digits: ")) # User input for the number of digits
possible_numbers = [] # List to store the possible numbers
def generate_numbers(digit_idx, number):
if digit_idx ... |
4ccceec7ce99deb87c2465b14de535a4108100f7 | brash99/phys441 | /JupyterNotebooks/DataScience/linear_regression.py | 1,380 | 4.34375 | 4 | import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# create some data
#
# N.B. In linear regression, there is a SINGLE y-value for each data point, but there
# may be MULTIPLE x-values, corresponding to the multiple factors that might affect the
# experime... |
9ba9a7d03c7e43d4edc5a1918886dab45118940b | kevinidea/Predict_Income | /Main.py | 3,589 | 3.734375 | 4 | from Data_Preparation import Data_Preparation
from Data_Exploration import Data_Exploration
from Data_Modeling import Data_Modeling
from Prediction import Prediction
while True:
whatToDo = raw_input("\n Do you want to \"prepare data\", \"explore data\", \"model data\", \"make prediction\" or \"quit\"?\n")
###... |
ac3b9c8668599e8b056b15df39fa20c2fd3d9f1d | mbarbour0/Practice | /Unpacking Variables/Packing and Unpacking Variables.py | 448 | 3.59375 | 4 | dicts = [
{'name': 'Michelangelo',
'food': 'PIZZA'},
{'name': 'Garfield',
'food': 'lasanga'},
{'name': 'Walter',
'food': 'pancakes'},
{'name': 'Galactus',
'food': 'worlds'}
]
def string_factory(dicts):
array = []
for item in dicts:
array.appen... |
7d803500f4e7f9befa7d9021f2ba30d5ab3febf9 | mbarbour0/Practice | /Lists/Median Value in a list.py | 249 | 3.625 | 4 | def median(lst):
lst = sorted(lst)
if len(lst) % 2 != 0:
index = len(lst) // 2
return lst[index]
elif len(lst) % 2 == 0:
index1 = (len(lst)/2) - 1
index2 = len(lst)/2
mean = (lst[index1] + lst[index2]) / 2.0
return mean |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.