blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
297b94ef7808b2ae2d11bca54d431f1be2120f72 | xxxfly/PythonStudy | /ProjectBaseTest1/算法与数据结构/03-排序/05-快速排序.py | 867 | 3.90625 | 4 | # coding:utf-8
def quickSort(orgList, start, last):
"""快速排序"""
if start >= last:
return
mid_vlaue = orgList[start]
low = start
high = last
while low < high:
# high 左移
while low < high and orgList[high] >= mid_vlaue:
high -= 1
orgList[low] = orgList[high]
# low 右移
while low < high and orgList[low] < mid_vlaue:
low += 1
orgList[high] = orgList[low]
# 循环退出时,low==high
orgList[low] = mid_vlaue
# 递归
# 对low左边的列表进行快速排序
quickSort(orgList, start, low-1)
# 对low右边的列表进行快速排序
quickSort(orgList, low+1, last)
if __name__ == "__main__":
a = [33, 2, 34, 123, 56, 47, 87, 38, 26, 88, 52, 9, 17, 28, 243]
print(a)
quickSort(a, 0, len(a)-1)
print(a)
|
4508f1a2a2db060764a3ccf1fcf01a56704031aa | xxxfly/PythonStudy | /ProjectBaseTest1/算法与数据结构/03-排序/06-归并排序.py | 1,019 | 4.125 | 4 | #encoding:utf-8
def mergeSort(orgList):
"""递归排序"""
n=len(orgList)
if n<=1:
return orgList
middle=n//2
#left_li 采用归并排序后形成新的有序列表
left_li=mergeSort(orgList[:middle])
#right_li 采用归并排序后形成新的有序列表
right_li=mergeSort(orgList[middle:])
#将两个有序的子序列合并成一个整体
# merage(left_li,right_li)
left_pointer,right_pointer=0,0
result=[]
while left_pointer<len(left_li) and right_pointer<len(right_li):
if left_li[left_pointer]<right_li[right_pointer]:
result.append(left_li[left_pointer])
left_pointer+=1
else:
result.append(right_li[right_pointer])
right_pointer+=1
result+=left_li[left_pointer:]
result+=right_li[right_pointer:]
return result
if __name__=="__main__":
a = [33, 2, 34, 123, 56, 47, 87, 38, 26, 88, 52, 9, 17, 28, 243]
print(a)
sortA=mergeSort(a)
print(a)
print(sortA) |
ddc40fd831996a7626f7b6056fb5fd2d2959da5d | xxxfly/PythonStudy | /ProjectBaseTest1/Python基础/dataType.py | 405 | 3.6875 | 4 | # print(1024*768)
#字符型,'' ""
# print("i 'am' ok")
#转义 \
# print('i \'m \"ok\"')
#r'' 不转义
# print(r'i \\\\\m \\\\ \nok')
#'''...''' 多行内容
# print('''lin1
# ...lin2
# ...lin3
# ''')
# print(r'''im \nm
# ok
# ''')
# age=17
# if age>18:
# print('adult')
# else:
# print('teenager')
# a="abc"
# b=a
# a='xyz'
# print(a)
a=123
f=123.456
s1='hello world'
print(f)
|
80b49b99ca21b7925f3d002958aa9d0e6431a26a | xxxfly/PythonStudy | /ProjectBaseTest1/python核心编程/02-高级3-元类/07-调试.py | 533 | 3.859375 | 4 | # coding:utf-8
#pdb调试
#python3 -m pdb xxx.py
#l -->list显示当前的代码
#n -->next向下执行一行代码
#c -->continue继续执行程序
#b -->break 添加断点 b 行数
#clear --> 清除断点 clear 1 (第一个断点)
#s -->step 进入函数
#p --> print 打印一个变量的值 p result
#a --> 查看传入参数
#q --> 退出
#r --> return 快速执行函数的最后一行
def getAverage(a,b):
result=a+b
print('result=%d'%result)
return result
a=100
b=200
c=a+b
ret=getAverage(a,b)
print(ret) |
ee098f39f6fe27a1ccff0ca8ad738c7f9d1d916d | xxxfly/PythonStudy | /ProjectBaseTest1/Python基础/03-高级特性highFeatures.py | 3,000 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import os
from collections import Iterable
from collections import Iterator
L=['Michael','Sarah','Tracy','Bob','Jack']
r=[]
n=3
for i in range(n):
r.append(L[i])
print(r)
print(L[0:3])
print(L[:3])
print(range(3))
print(L[-2:])
print(L[-3:-1])
print(L[-1:])
print((0,1,2,3,4,5,6)[:3])
print((0,1,2,3,4,5,6,7,8,9,10)[:10:2])
print('ABCDEF'[:3])
def trim(str):
if str[0]==' ':
return trim(str[1:])
elif str[-1]==' ':
return trim(str[:-1])
else:
return str
print(trim(' asd asda '))
print(trim('asd asda '))
print(trim(' asd asda'))
for item in L:
print(item)
d={'a':1,'b':2,'c':3}
for key in d:
print(key)
for ch in 'ABCD':
print(ch)
print(isinstance('abc',Iterable))
print(isinstance([123],Iterable))
print(isinstance(123,Iterable))
for i,value in enumerate(['A','b','C']):
print(i,value)
for x,y in[(1,1),(3,4),(5,9)]:
print(x,y)
def findMinAndMax(L):
max=None
min=None
if isinstance(L, Iterable)==False:
return min,max
max=L[0]
min=L[0]
for v in L:
if max<v:
max=v
if min>v:
min=v
return min,max
print(findMinAndMax([3,5,2,8,9]))
print(list(range(1,10)))
print([x*x for x in range(1,11)])
print([x*x for x in range(1,11) if x%2==0])
print([m+n for m in 'ABC' for n in '123'])
print([d for d in os.listdir('.')])
d={'a':'1','b':'2','c':'3'}
for k,v in d.items():
print(k,'=',v)
print([k+'='+v for k,v in d.items()])
L1=['Hello','World',18,'Apple',None]
print([s.lower() for s in L1 if isinstance(s,str)])
g=(x*x for x in range(10))
print(g)
print('n',next(g))
print('n',next(g))
print('n',next(g))
print('n',next(g))
for n in g:
print(n)
def fib(max):
n,a,b=0,0,1
while n<max:
print('1-',b)
a,b=b,a+b
n=n+1
return 'done'
fib(6)
def fib2(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'done'
f=fib2(6)
print(f)
for n in fib2(6):
print(n)
def odd():
print('step 1')
yield 1
print('step 2')
yield 3
print('step 3')
yield 5
o=odd()
print(next(o))
print(next(o))
print(next(o))
while True:
try:
x=next(f)
print('g:',x)
except StopIteration as e:
print('Generator return value:',e.value)
break
def triangles():
l = [1]
while 1:
yield l
l = [1] + [ l[n] + l[n+1] for n in range(len(l)-1) ] + [1]
n = 0
results = []
for t in triangles():
print(t)
results.append(t)
n = n + 1
if n == 10:
break
print(isinstance([],Iterable))
print(isinstance({},Iterable))
print(isinstance('abc',Iterable))
print(isinstance((x for x in range(10)),Iterable))
print(isinstance(100,Iterable))
print(isinstance([],Iterator))
print(isinstance({},Iterator))
print(isinstance('abc',Iterator))
print(isinstance(iter([]),Iterator))
print(isinstance(iter({}),Iterator))
print(isinstance(iter('abc'),Iterator))
|
2d4a74ef569e29442435b75a80524dce7e1a9a9d | afcarl/swedish_chef | /chef_global/accelerate.py | 498 | 3.859375 | 4 | """
Module to provide a means to accelerate slow python code.
"""
import multiprocessing
def acc_map(func, items):
"""
Applies func to each item in items.
@param func: A function of the form f(item)
@param items: The list of items to apply func to
@return: void
"""
p = multiprocessing.Pool(None)
ret = p.map(func, items)
return ret
def f(x):
return x * x
if __name__ == "__main__":
m = acc_map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(str(m))
|
cd05f442d554622b27630f7e47202889efff6f93 | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex086.py | 331 | 4 | 4 | matriz = [
[[], [], []],
[[], [], []],
[[], [], []]
]
for r in range(0, 3):
for c in range(0, 3):
num = int(input(f'Digite o valor da coluna {c + 1} da linha {r + 1}: '))
matriz[r][c].append(num)
for r in range(0, 3):
for c in range(0, 3):
print(matriz[r][c], end=' ')
print('')
|
bdb285b9f5b80f2fd9dac9f176575a5e3a13d278 | SirGuiL/Python | /Mundo 1/Python_Exercicios/ex024.py | 316 | 3.984375 | 4 | cidade = input('Digite o nome de uma cidade: ')
res = (cidade.split()[0].lower().find('santo'))
if(res != -1 and cidade.split()[0].lower() == 'santo'):
print("O nome da cidade começa com 'SANTO'.")
else:
print("O nome da cidade não começa com 'SANTO'.")
cidade = input('Digite o nome de uma cidade: ') |
118d67162a02cae06b471053b643773c91a26c26 | SirGuiL/Python | /Mundo 2/aula_12/aula_12.py | 307 | 3.875 | 4 | nome = input('Digite seu nome: ')
if (len(nome.strip()) == 0):
print('Digite um nome =(')
else:
if(len(nome.strip()) >= 10):
print('Você tem um nome grande.')
elif(len(nome.strip()) <= 4):
print('Você tem um nome pequeno.')
print('Tenha um ótimo dia, {}!'.format(nome))
|
4b5a82fdef8ba7af79277758ccdecba1126a5037 | SirGuiL/Python | /Mundo 1/aula_07/Exercícios/ex001.py | 681 | 4.09375 | 4 | nome = input('Digite seu nome: ')
# Utilizando 20 caracteres para a variavel nome
print('Prazer em conhecê-lo {:20}!'.format(nome))
# Utilizando 20 caracteres para a variavel nome e alinhando a direita
print('Prazer em conhecê-lo {:>20}!'.format(nome))
# Utilizando 20 caracteres para a variavel nome e alinhando a esquerda
print('Prazer em conhecê-lo {:<20}!'.format(nome))
# Utilizando 20 caracteres para a variavel nome e alinhando ao centro
print('Prazer em conhecê-lo {:^20}!'.format(nome))
# Utilizando 20 caracteres para a variavel nome e alinhando ao centro e cercado pelos caracteres escolhidos
print('Prazer em conhecê-lo {:=^20}!'.format(nome))
n = input('a') |
712120fb30ec319a5ee65a43bb9e0cb6ed0ffc20 | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex053.py | 278 | 4.0625 | 4 | phrase = input('Digite uma frase: ')
phrasejoin = ''.join(phrase.strip().split()).lower()
if phrasejoin == phrasejoin[::-1]:
print('{} é um palíndromo'.format(phrase.strip().capitalize()))
else:
print('{} não é um palíndromo'.format(phrase.strip().capitalize()))
|
cf809f23d5dd09ee5e2d7dc5c43ce963fb68a796 | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex058.py | 493 | 4 | 4 | from random import randint
print('Adivinhe o número que estou pensando:\nDica: É um número de 0 a 10\nBoa sorte =)')
num = int(input(''))
count = 0
randomNum = randint(1, 10)
while num != randomNum:
if (num - randomNum < 3 and num - randomNum > -3):
print('Foi por muito pouco!')
else:
print('Você errou.')
num = int(input('Tente novamente!\n'))
count += 1
print('Parabéns, você acertou!! \o/')
print('Foram necessárias {} tentativas'.format(count))
|
b749ecda7fb8899047c715347e6bcc5ebb5dae28 | SirGuiL/Python | /Mundo 1/aula_04/Exercícios/data_formatada.py | 465 | 4 | 4 | dia = input('Digite o dia do seu nascimento: ')
mes = input('Digite o mês do seu nascimento: ')
ano = input('Digite o ano do seu nascimento: ')
print('Você nasceu no dia', dia, 'do', mes, 'de', ano, ', certo? (s para sim e n para não)')
confirm = input('')
if(confirm == 's'):
print('Você nasceu no dia', dia, '/', mes, '/', ano)
elif(confirm == 'n'):
print('Poxa, reinicie o programa e preencha novamente :(')
else:
print('Resposta inválida.')
|
1cc3b57ca48ddedf9187b459761e4c517146fe2a | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex078.py | 490 | 3.953125 | 4 | lista = []
maior = menor = 0
for c in range(0, 5):
lista.append(int(input('Digite um número inteiro: ')))
if c == 0:
maior = menor = lista[c]
else:
if lista[c] > maior:
maior = lista[c]
if lista[c] < menor:
menor = lista[c]
print(f'O maior valor digitado foi o {maior} e o menor foi o {menor}')
print(f'O maior estava localizado na {lista.index(maior) + 1}ª posição e o menor na {lista.index(menor) + 1}ª posição')
|
334afd4599524aca8327c38bcf390da76d0ca0b2 | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex059.py | 961 | 4.03125 | 4 | n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
menu = 0
print('[1] somar\n[2] multiplicar\n[3] maior\n[4] novos números\n[5] sair do programa\n')
while menu != 5:
menu = int(input('Escolha uma opção: '))
if (menu == 1):
print('A soma entre {} e {} é igual a {}'.format(n1, n2, n1 + n2))
elif (menu == 2):
print('A multiplicação entre {} e {} resulta em {}'.format(n1, n2, n1 * n2))
elif (menu == 3):
if (n1 > n2):
print('{} é maior que {}'.format(n1, n2))
else:
print('{} é maior que {}'.format(n2, n1))
elif (menu == 4):
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
print('[1] somar\n[2] multiplicar\n[3] maior\n[4] novos números\n[5] sair do programa\n')
elif (menu == 5):
print('Obrigado por utilizar o programa, até mais =)')
else:
print('Valor inválido.')
|
c59c91add9c2dd28a5f6b1098113dd4d92548d23 | SirGuiL/Python | /Mundo 1/Python_Exercicios/ex025.py | 185 | 4.03125 | 4 | nome = input('Digite seu nome: ')
if(nome.lower().find('silva') != -1):
print('Seu nome tem Silva.')
else:
print('Seu nome não tem Silva.')
nome = input('Digite seu nome: ') |
1514e8aeef456d124a94cf6dfd75c29e9aee8b4b | SirGuiL/Python | /Mundo 2/aula_15/aula_15.py | 175 | 3.875 | 4 | # break and fstring
num = soma = 0
while True:
num = int(input('Digite um número: '))
if num == 999: break
soma += num
print(f'A soma dos valores vale {soma}')
|
8d9e21adba4b96f52c286581e1eaf0b51501f8dd | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex060.py | 180 | 4.03125 | 4 | num = int(input('Digite um número: '))
n = num
count = num
while count != 1:
num *= count - 1
count -= 1
print('{} fatorial é igual a {}'.format(n, num))
a = input('') |
b5f97be3b57ffe3bd6c173e40604e2e3eb8fafc2 | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex081.py | 965 | 3.90625 | 4 | lista = []
números = cinco = 0
opc = str
while True:
if opc == 'N':
break
num = int(input('Digite um número inteiro: '))
if num == 5:
cinco += 1
if num not in lista:
números += 1
lista.append(num)
while True:
opc = input('Deseja continuar? [S/N] ').upper()
if opc in 'SN':
break
if len(lista) == 1:
print('Foi digitado apenas um valor.')
else:
print(f'Foram digitados {len(lista)} valores')
if números == 1:
print('Não houve números diferentes pois apenas um número foi digitado.')
else:
print(f'Foram digitados {números} valores diferentes')
lista.sort(reverse=True)
print(f'A lista ordenada de forma decrescente fica da seguinte forma: {lista}')
if 5 not in lista:
print('O valor 5 não foi digitado.')
else:
if cinco == 1:
print('O valor 5 foi digitado apenas uma vez')
else:
print(f'O valor 5 foi digitado {cinco}x')
|
cca3891d0edf3d2a82eb6d715601677018a41ce2 | SirGuiL/Python | /Mundo 3/aula_19/aula_19.py | 1,048 | 4.03125 | 4 | # Variáveis composta (Dicionários)
# dados = dict()
dados = {
'nome': 'Guilherme',
'idade': 18
}
print(dados['nome']) # Retorna Guilherme
print(dados['idade']) # Retorna 18
dados['sexo'] = 'M' # Adiciona o elemento sexo e adiciona a informação M
print(dados['sexo']) # Retorna M
del dados['idade'] # Deleta o elemento idade
filme = {
'titulo': 'Star Wars',
'ano': 1997,
'diretor': 'George Lucas'
}
print(filme.values()) # Retorna os valores do dicionário
print(filme.keys()) # Retorna as chaves do dicionário
print(filme.items()) # Retorna o dicionário completo
for key, value in filme.items():
print(f'O {key} é {value}')
locadora = list()
locadora.append(filme.copy())
print(locadora)
for cont in range(0, 3):
titulo = input('Digite o nome do filme: ')
ano = int(input('Digite o ano do filme: '))
diretor = input('Digite o nome do diretor: ')
filme['titulo'] = titulo
filme['ano'] = ano
filme['diretor'] = diretor
locadora.append(filme.copy())
print(locadora)
a = input('a') |
b98a6140be3bcfd45582f98f2e832b8c509d2d49 | mikksillaste/aima-python | /ht13_Ex12_ListEnds_ListProperties.py | 244 | 3.828125 | 4 | a = [5, 10, 15, 20, 25]
b = [11, 15, 176, 555, 43]
# funktsioon mis teeb uue listi ainult esimesest ja viimasest arvust antud listis
def newList(list):
newlist = [list[0], list[-1]]
return newlist
print(newList(a))
print(newList(b)) |
2215b7f1de2216e1de2ccaa7f5522ca7b53268ac | mikksillaste/aima-python | /ht13_Ex28_MaxThree.py | 524 | 3.921875 | 4 | # kasutaja sisestab 3 numbrit
number1 = int(input("Sisesta esimene arv: "))
number2 = int(input("Sisesta teine arv: "))
number3 = int(input("Sisesta kolmas arv: "))
# funktsioon, mis tagastab kolmes sisestatud arvust suurima
def largest(number1, number2, number3):
biggest = 0
if number1 > biggest:
biggest = number1
if number2 > number1:
biggest = number2
if number3 > number2 and number3 > number1:
biggest = number3
return biggest
print(largest(number1, number2, number3)) |
c238078f55464429915d9c9f7b8987336966c957 | hcs42/hcs-utils | /bin/Catless | 2,227 | 3.703125 | 4 | #!/usr/bin/python
# Prints the text from the standard input or the given files using `cat` or
# `less` depending on whether the text fits into the terminal
import optparse
import os.path
import subprocess
import sys
def parse_args():
usage = 'Usage: Catless [options] [FILENAME]...'
parser = optparse.OptionParser(usage=usage)
(cmdl_options, args) = parser.parse_args()
return cmdl_options, args
def cmd(args):
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
def main(options, args):
terminal_height = int(cmd(["tput", "lines"]))
text = []
if len(args) == 0:
# Reading stdin
while True:
line = sys.stdin.readline()
if line == '':
break
text.append(line)
else:
filenames = args
# Checking whether all files exist and are regular
all_files_ok = True
for filename in filenames:
if not os.path.exists(filename):
print 'File not found: ', filename
all_files_ok=False
elif not os.path.isfile(filename):
print 'Not a regular file: ', filename
all_files_ok=False
if not all_files_ok:
sys.exit(0)
# Reading the content of all files
for filename in filenames:
f = open(filename, 'r')
while True:
line = f.readline()
if line == '':
break
text.append(line)
f.close()
# If the terminal is taller then the text, we print the text just like
# `cat`
if len(text) < terminal_height:
for line in text:
sys.stdout.write(line)
# Otherwise we use "less" to display it
else:
process = subprocess.Popen(["less"], stdin=subprocess.PIPE)
process.communicate(''.join(text))
if __name__ == '__main__':
try:
main(*parse_args())
except OSError:
# The user probably pressed CTRL-C before `less` could read all data.
# This is not an error.
pass
except KeyboardInterrupt:
# The user probably pressed CTRL-C while Catless was running.
pass
|
50c8515e0b3dc1115ce9d7b3e9aeb1bd7f39672a | mourya1729/algoexport | /arrays algoexpert.py | 6,861 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 12:37:02 2020
@author: mourya
"""
""" two sum"""
def twosum(a,num):
dic={}
for ele in a:
dic[ele]=None
print (dic)
for ele in a:
x=num-ele
if x!=ele and x in dic.keys():
return (ele,x)
return -1
# a=[0, -1, 0, -3, 1]
# s=3
# print (twosum(a, s))
"""is subsequence"""
def issubsequence(str1,str2):
a=list(str1)
b=list(str2)
i=0
for char in b:
if char==a[i]:
i+=1
if i==len(a):
return True
return False
# str1 = "AXY"
# str2 = "ADXCPY"
# print (issubsequence(str1, str2))
"""three sum"""
def threesum(a,num):
if len(a)<3:
return "not possible"
dic={}
for ele in a:
if ele not in dic.keys():
dic[ele]=1
else:
dic[ele]+=1
for i in range(0,len(a)):
for j in range(i+1,len(a)):
s=num-(a[i]+a[j])
if a[i]==a[j]:
if s==a[i]:
if dic[s]>=3:
return (a[i],a[j],s)
else:
if s in dic.keys():
return (a[i],a[j],s)
else:
if s==a[i] or s==a[j]:
if dic[s]>=2:
return (a[i],a[j],s)
else:
if s in dic.keys():
return (a[i],a[j],s)
return -1
""" smallest difference"""
import sys
def smalldiff(a):
if len(a)<2:
return "nt possible"
b=sorted(a)
diff=sys.maxsize
for i in range(0,len(a)-1):
if abs(a[i+1]-a[i]) <diff:
diff=abs(a[i+1]-a[i])
return diff
# a=[1, 5, 3, 19, 18, 25]
# print (smalldiff(a))
"""monotonic array"""
def monotonic(a):
for i in range(0,len(a)-1):
if a[i]>a[i+1]:
return False
return True
"""spiral traverse"""
def spiraltraverse(a,k,n):
x=k
y=n
for i in range(0,x):
for j in range(i,y):
print(a[i][j],end=" ")
for l in range(i+1,x):
print (a[l][y-1],end=" ")
if i==k//2:
break
for m in range(y-2,i-1,-1):
print (a[x-1][m],end=" ")
for h in range(x-2,i,-1):
print (a[h][i],end=" ")
x=x-1
y=y-1
return
# a=[ [1, 2, 3, 4],
# [5, 6, 7, 8], [ 9, 10, 11, 12],
# [13, 14, 15, 16] ]
# spiraltraverse(a, 4, 4)
"""longest peak"""
import math
def longestpeak(a):
mini=-math.inf
count=0
peakrange=0
i=0
for i in range(i,len(a)):
while (i<len(a) and a[i]>mini):
count+=1
mini=a[i]
i+=1
if i==len(a):
count=0
break
while(i<len(a) and a[i]<mini):
count+=1
mini=a[i]
i+=1
if peakrange<count:
if count>1:
peakrange=count
count=1
return peakrange
# a=[1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5]
# a=[2,4,3]
# print(longestpeak(a))
"""sorting suubarray"""
class stack:
def __init__(self):
self.stack=[]
self.size=0
def push(self,x):
self.stack.append(x)
self.size+=1
def pop(self):
data=self.stack[-1]
del(self.stack[-1])
self.size-=1
return data
def peek(self):
return self.stack[-1]
def isempty(self):
if self.size==0:
return "True"
return False
def get_stack(self):
return self.stack
def get_size(self):
return self.size
def sortsubarr(a):
if len(a)==0:
return "no array"
st=stack()
i=0
start=len(a)-1
end=len(a)-1
x=-math.inf
while i<len(a):
if a[i]>=x:
st.push(a[i])
x=a[i]
i+=1
else:
while not st.isempty() and st.peek()>a[i]:
st.pop()
if st.get_size()<start:
start=st.get_size()
end=i
i+=1
if start==end:
return "perfect array"
else:
return (start,end)
# a=[10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]
# a=[0, 1, 15, 25, 6, 7, 30, 40, 50]
# print(sortsubarr(a))
"""max range"""
def maxrange(a):
dic={}
z=0
for ele in a:
dic[ele]=False
for ele in a:
if dic[ele]==True:
continue
while True:
dic[ele]=True
ele -=1
if ele not in dic.keys():
x=ele+1
break
while True:
dic[ele]=True
ele+=1
if ele not in dic.keys():
y=ele-1
break
if (y-x)>z:
m=x
n=y
z=y-x
return ([m,n])
# a=[1,11,3,3,0,15,5,2,4,10,7,12,6]
# print (maxrange(a))
"""zigzag traverse"""
def zigzag(a,k,n):
i=0
j=0
result=[[] for i in range(k+n-1)]
for i in range(k):
for j in range(n):
sum=i+j
if sum%2==0:
result[sum].insert(0, a[i][j])
else:
result[sum].append(a[i][j])
for i in result:
for j in i:
print(j,end=" ")
# a=[[ 1, 2, 3,4], [ 5, 6 ,7,8], [ 9,10,11,12 ],[13,14,15,16] ]
# zigzag(a, 4, 4)
"""appartment nunting"""
# import math
def ab(a,b):
return abs(a-b)
def apparthunt(a,ran):
if len(a)<2:
return a
a.sort()
if a[0]==a[-1]:
return a[-1]
b=[]
j=0
prev=a[0]
while j<len(a):
while j<len(a):
if ab(a[j],prev)<ran:
j+=1
elif ab(a[j],prev)==ran:
if b==[]:
b.append(a[j])
prev=a[j]
j+=1
elif ab(a[j],b[-1])>ran:
b.append(a[j])
prev=a[j]
j+=1
else:
j+=1
else:
if b==[]:
b.append(a[j-1])
elif ab(a[j-1],b[-1])>ran:
b.append(a[j-1])
prev=a[j]
break
if ab(a[-1],b[-1])>ran:
b.append(a[-1])
return b
# a=[2,5,8]
# a=[2,4,5,6,7,9,11,12]
# a=[1]
a=[3,]
print(apparthunt(a,2))
|
f8b5da75967beb83ce248c744aedbdcef844481b | akash9579/python_snippets | /python_basic_stack_using_deque.py | 525 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 21:25:03 2021
@author: 91937
"""
# stack follow the last in first out
# example web brawsing application
# push,pop operation
"""
Write a function in python that can reverse a string using stack data structure.
"""
string = "we will play football"
x = string.split(" ")
from collections import deque
stack = deque()
for ele in x:
stack.append(ele[::-1])
print(stack)
# for reverse string
# txt = "Hello World" [::-1]
# print(txt) |
fa63e80619af8eaa57cf50ee582972453341d31e | akash9579/python_snippets | /substring.py | 301 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 09:56:02 2021
@author: 91937
"""
string = "akash"
sub = []
for i in range(len(string)):
for j in range (i,len(string)+1):
sub.append(string[i:j])
print(len(sub))
se=set(sub)
nsub=list(se)
print(len(nsub))
|
3185f97dd036042062b6b56ab0b57ba2adfcec9f | akash9579/python_snippets | /python_oops/property_setter_deleter.py | 1,301 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 23 19:28:18 2020
@author: akash
"""
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property # known as property decorator we can use that method as attribute
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last
@fullname.deleter
def fullname(self):
print('Delete Name!')
self.first = None
self.last = None
emp_1 = Employee('John', 'Smith')
emp_1.fullname = "Corey Schafer" # without setter method we cant set the fullname method after doing @property also
# for updating method we use setter,deleter method
print(emp_1.first)
print(emp_1.email) # due to @property we are using email method as a attribute
print(emp_1.fullname)
del emp_1.fullname |
62159d8fc2552b4764870818ab5a6e1b3041cf90 | akash9579/python_snippets | /python_basic_tree.py | 722 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 18:11:17 2021
@author: 91937
"""
class treenode:
def __init__(self,data):
self.data=data
self.children=[]
self.parent=None
def add_children(self,child):
child.parent=self
self.children.append(child)
def print_tree(self):
print(self.data)
for ele in self.children:
print(ele.print_tree())
root = treenode("president")
parshuram = treenode("parshuram")
root.add_children(parshuram)
root.add_children(treenode("parshuram1"))
root.add_children(treenode("parshuram2"))
root.print_tree() |
a75a23d202b58959853cd395cd403ddb2a937ef5 | pjcperpso/PythonPlayer | /PAT/PAT_乙级/1023_组个最小数.py | 701 | 3.890625 | 4 | """给定个数小于10的几个数
要求组成最小数 0不能做首位
如:00121123-------10011223
思路利用排序算法将数字从小到大排列
取出第一个为不为0的数和第一个互换
在调用list转换成str的方法
首位不能为0
"""
list = [0,1,2,3,5,6,1,1,1]
for x in range(0,len(list)):
temp = 0
for y in range(0,len(list)-x-1):
if list[y]>list[y+1]:
temp = list[y]
list[y] = list[y+1]
list[y+1] = temp
num = 0
for x in list:
if x!=0:
print(x,num)
break;
num = num+1
temp1 = 0
temp1 = list[num]
list[num] = list[0]
list[0] = temp1
new_list = [str(x) for x in list]
print("".join(new_list))
|
f216a4c7e7782b56ce7bac081478e58cf136d491 | pjcperpso/PythonPlayer | /PAT/PAT_乙级/testnum.py | 333 | 3.9375 | 4 | """python字符串截取"""
list = ["hEllo","Hello","Helo","hello","hell"]
str_test = "Hellohhelloooohlhello"
num = 0
#print(list[0].upper())
#for x in list:
#if x.upper()=="HELLO":
#num = num+1;
#print(num)
for i in range(0,len(str_test)):
if str_test[i:i+5].lower() == "hello":
num = num + 1;
print(num)
|
92e77e768e1a412f4a67b09f4aa52ec2a5b893ad | 40586/Functions | /starter.py | 376 | 4 | 4 | #Kieran burnett
#Starter program
b_hours = int(input("Please enter the number of basic hours worked: "))
e_hours = int(input("Please enter the number of overtime hours worked: "))
pay = int(input("Please enter your pay per hour: "))
o_pay = pay + (pay / 2)
overtime = e_hours * o_pay
basic = b_hours * pay
total = basic + overtime
print("Your total pay is: £",total)
|
4207409a35d60c91076752e24083cf4e00ccc20e | deivid-01/manejo_archivos | /csv/csv_module/csv_read.py | 327 | 3.84375 | 4 | import csv
fields = []
rows = []
fileName="personas.csv"
with open(fileName,'r') as csv_file:
#Crear objeto reader
csv_reader= csv.reader(csv_file)
#Obtener encabezado
fields = next(csv_reader)
#Extrar cada una de las filas
for row in csv_reader:
rows.append(row)
print(fields)
print(rows)
|
d8ab5ec281b21f17f17008519ef108f37d918e16 | kimje0322/Algorithm | /기타/0226/Queue.py | 168 | 3.640625 | 4 | def enqueue(n):
global rear
if rear == len(queue)-1:
print('full')
else:
rear += 1
queue[rear] = n
queue = [0]*3
front = rear = -1
|
3d46c364b2fda038f09bb32781197ad0144ee312 | kimje0322/Algorithm | /문자열/1213 팰린드롬 만들기.py | 699 | 3.671875 | 4 | def check_palindrome(word):
cnt = 0
ans = [0]*len(word)
cnt_word = []
one_word = list(set(word))
one_word.sort()
for i in range(len(one_word)):
cnt_word.append(word.count(one_word[i]))
for c in range(len(cnt_word)):
if (cnt_word[c] % 2):
cnt += 1
ans[len(ans)//2] = word.pop(word.index(one_word[c]))
if cnt >= 2:
print("I'm Sorry Hansoo")
return
i = 0
while word:
if word[0] == word[1]:
ans[i] = word.pop(0)
ans[len(ans)-1-i] = word.pop(0)
i += 1
for w in ans:
print(w, end='')
s = list(input())
s.sort()
check_palindrome(s)
|
eec9859f53416b41e566f456284399272f7f5abb | kimje0322/Algorithm | /기타/가비아.py | 362 | 3.640625 | 4 | # import math
# def solution(n):
# cnt = countFive(n)
# return cnt
# def countFive(n):
# count = 0
# # print(math.floor(n/5))
# if math.floor(n/5) >= 5:
# count += math.floor(n/5)
# return countFive(math.floor(n/5))
# else:
# count += math.floor(n/5)
# return count
# solution(30)
s = 'hidd'
print(set(s)) |
d60e11d393a63a48c798da4f5f89b77a43b7af6a | kimje0322/Algorithm | /문자열/10809 알파벳 찾기.py | 187 | 3.5 | 4 | word = input()
check = [-1]*26
for w in range (len(word)):
if check[ord(word[w]) - 97] == -1:
check[ord(word[w]) - 97] = w
print(*check)
# ord(a) = 97 (0)
# ord(z) = 122 (25)
|
b3e7c0ea4503e50c1389a2dd07b77f2423003d8b | rkbarnwal/python-experiment1 | /liked-list.py | 841 | 3.671875 | 4 | class Node:
def __init__(self, data, next):
self.data = data
self.next = next
def getData(self):
return self.data
def setData(self, value):
self.data = value
def getNext(self):
return self.next
def setNext(self, newNext):
self.next = newNext
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.currentSize = 0
def size(self):
return self.currentSize
def isEmpty(self):
return self.size() == 0
def add(self, value):
if self.isEmpty():
self.head = Node(value, None)
self.tail = self.head
else:
self.tail.setNext(Node(value,None))
self.tail = self.tail.getNext()
self.currentSize += 1
return True
|
f059d95e2757aacf6853f1c697e94570eb11b0dc | k123456774/PythonCode | /score_B10309034.py | 152 | 3.75 | 4 | z=int(input("the hightest score"))
y=int(input("medium score"))
x=int(input("the lowest score"))
z=x*0.5
y=y*0.3
x=x*0.2
a=float(x+y+z)
print("a=%s"%a)
|
88e0893f2afce21f3eae1cf65e1cef3a833f09b2 | outcoldman/codeinterview003 | /2013/cracking/01-02.py | 426 | 4.15625 | 4 | # coding=utf8
# Write code to reverse a C-Style String. (C-String means that "abcd" is represented as five characters, including the null character.)
def reverse_string(str):
buffer = list(str)
length = len(buffer)
for i in xrange(length / 2):
t = buffer[i]
buffer[i] = str[length - i - 1]
buffer[length - i - 1] = t
return "".join(buffer)
print "Result %s" % reverse_string("abcde")
|
b5ad4a2c2126a96419f269d065c86e97eb295da3 | karthikeyansa/Data_Structures_python | /Tree/tree.py | 1,132 | 3.96875 | 4 | class Node(object):
def __init__(self,data):
self.data = data
self.left = None
self.right = None
''' def insert(self,data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
'''
def printree(self):
if self.left:
self.left.printree()
print(self.data)
if self.right:
self.right.printree()
def lca(root,n1,n2):
if root is None:
return None
if root.data == n1 or root.data == n2:
return root.data
l_lca = lca(root.left,n1,n2)
r_lca = lca(root.right,n1,n2)
if l_lca and r_lca:
return root.data
return l_lca if l_lca is not None else r_lca
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
#n = int(input('enter total number of nodes'))
#arr = [int(n) for n in input('enter elements separated by space').split()]
root.printree()
print(lca(root,4,5))
# 2
|
c8a861aa57631a538f48389f522e2627b29c892e | MGelein/simulating-mistakes | /agent.py | 3,523 | 3.546875 | 4 | from random import choice, random, randint
from util import similar_looking_word, closest_word
class Agent:
def __init__(self, simulation, number):
self.simulation = simulation
self.canonical_text = simulation.text[:]
self.written_text = self.canonical_text[:]
self.remembered_text = self.canonical_text[:]
self.memory = simulation.sample_memory()
self.arrogance = simulation.sample_arrogance()
self.influence = simulation.sample_influence()
self.vocabulary = simulation.sample_vocabulary()
self.position = simulation.sample_position(number)
self.known_words = {}
def in_vocab(self, word):
if word in self.known_words: return self.known_words[word]
known = random() < self.vocabulary
self.known_words[word] = known
return known
def skip_line(self, sentences):
sentence, next_sentence = sentences
if random() < self.arrogance:
return [next_sentence]
for word in next_sentence:
if word in sentence:
start = sentence.index(word)
end = next_sentence.index(word)
return [sentence[:start] + next_sentence[end:]]
return sentences
def substitute_word(self, word):
if random() > self.arrogance and self.in_vocab(word):
return word
try:
top_ten = self.simulation.embeddings.most_similar(positive=[word], topn=10)
except:
return word
return choice(top_ten)[0]
def mutate_letter(self, word, alphabet):
rnd_index = randint(0, len(word) - 1) if len(word) > 1 else 0
letter = choice(alphabet)
new_word = word[:rnd_index] + letter + word[rnd_index + 1:]
if self.in_vocab(new_word):
return new_word
else:
return new_word if random() < self.arrogance else word
def read_word(self, word, line):
if random() > self.memory:
return self.mutate_letter(word, line)
return word
def make_canonical(self):
self.canonical_text = self.written_text
def write_word(self, word):
if self.in_vocab(word):
return self.substitute_word(word)
else:
if random() > self.memory:
return similar_looking_word(word, self.simulation.embeddings.vocab)
else:
return word
def read(self, agent):
read_text = []
skipped_text = []
i = 0
while i < len(agent.canonical_text) - 1:
line = agent.canonical_text[i]
next_line = agent.canonical_text[i + 1]
after_skip_lines = self.skip_line([line, next_line]) if random() > self.memory else [line, next_line]
for l in after_skip_lines: skipped_text.append(l)
i += 2
for line in skipped_text:
read_line = []
joined_line = "".join(line).replace("·", '').replace('\'', '').replace('.', '')
for word in line:
read_line.append(self.read_word(word, joined_line))
read_text.append(read_line)
self.remembered_text = read_text
def write(self):
write_text = []
for line in self.remembered_text:
written_line = []
for word in line:
written_line.append(self.write_word(word))
write_text.append(written_line)
self.written_text = write_text
|
9f0131996b87f8110b6bf1688a496e45ba59d228 | jxhd518/day1 | /day1/ifelse.py | 245 | 3.75 | 4 | age_of_oldboy = 48
guess = int(input(">>:"))
if guess > age_of_oldboy :
print("猜的太大了,往小里试试...")
elif guess < age_of_oldboy :
print("猜的太小了,往大里试试...")
else:
print("恭喜你,猜对了...") |
4e10ff8b70898ac729fa530a4364bd238e215ea3 | jwilke/cs373 | /examples/Test.py | 284 | 3.8125 | 4 | #!/usr/bin/env python
def my_max (x, y) :
if x < y :
return y
return x
def my_max (x, y, bf) :
if bf(x, y) :
return y
else :
return x
assert my_max(2, 3) == 3
assert my_max(2, 3, lambda x, y : y < x) == 2
print "Done."
|
2e891d87430890bacd0c35e202a85609f498f656 | Mrwang19960102/work | /model/machine_learning/sklearn/k_近邻.py | 756 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# @File: | k_近邻.py
# @Date: | 2020/8/5 16:57
# @Author: | ThinkPad
# @Desc: |
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
# k邻近算法模型
from sklearn.neighbors import KNeighborsClassifier
# 手动创建训练数据集
feature = np.array([[170, 65, 41], [166, 55, 38], [177, 80, 39], [179, 80, 43], [170, 60, 40], [170, 60, 38]])
target = np.array(['男', '女', '女', '男', '女', '女'])
# 实例k邻近模型,指定k值=3
knn = KNeighborsClassifier(n_neighbors=3)
# 训练数据
knn.fit(feature, target)
# 模型评分
s = knn.score(feature, target)
print('训练得分:{}'.format(s))
# 预测
p = knn.predict(np.array([[176, 71, 38]]))
print(p)
|
28c74e11030275997ea19c2b3195a11645f540d7 | v4nh4n/practicepython.org | /ex25.py | 437 | 3.765625 | 4 | def guesser():
i = 0
m = 100
mid = 50
print("Guess some number btw 0-100")
condition=input("Is your guess"+str(mid)+"? exact/low/high")
while condition!="exact":
if condition=="low":
i = mid + 1
elif condition=="high":
m = mid - 1
mid = (i+m)//2
condition=input("Is your guess"+str(mid)+"? exact/low/high")
return "I did it !!!!"
print(guesser())
|
faeeac5a13e7acc581496ff6ed3cde7b3c820fa3 | v4nh4n/practicepython.org | /ex11.py | 271 | 4.03125 | 4 | def prime_number(num):
if num==1 or num==2:
return True
for i in range(num):
if i>1 and num%i==0:
return False
return True
while True:
number = int(input("ENTER A NUMBER (CTRL+C TO EXIT) => "))
print(prime_number(number))
|
38b243be83f550104533a75da2cf8b1e250c7bd6 | v4nh4n/practicepython.org | /ex6.py | 178 | 3.828125 | 4 | a = input("ENTER A STRING: ")
x = int((len(a)/2))
print(x)
h1 = a[:x]
h2 = a[x+1:]
print(h1)
print(h2)
if h1==h2:
print("palindrome!")
else:
print('not a palindrome...')
|
44848bd2b67081257b43f36a02cdf198be762ea5 | anthonykid/HelloWorldWithButton | /hello.py | 452 | 3.75 | 4 | import tkinter as tk
root = tk.Tk()
canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.pack()
def hello():
label1 = tk.Label(root, text="Hello I'm AnthonyKid", fg='green',
font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 200, window=label1)
button1 = tk.Button(text='Click Me', command=hello, bg='brown', fg='white')
canvas1.create_window(150, 150, window=button1)
root.mainloop()
|
eec8c0278f1ab0c8a01c7a12c36205e7f9e03657 | awenhaowenchao/bee | /src/bee/db/psd/table.py | 1,215 | 3.515625 | 4 | class Table():
def name(self) -> str:
pass
def alias(self) -> str:
pass
def prefix(self) -> str:
pass
def to_table(table: object) -> "Table":
if isinstance(table, str):
return SimpleTable(table)
elif isinstance(table, Table):
return table
def new_table(name: str, *alias) -> "Table":
if len(alias) == 0:
return SimpleTable(name)
else:
return new_alias_table(name, alias[0])
class SimpleTable(str, Table):
def __init__(self, t: str):
self.t = t
def name(self) -> str:
return self.t
def alias(self) -> str:
return ""
def prefix(self) -> str:
return self.t
class AliasTable(Table):
def __init__(self, name: str, alias: str, prefix: str):
self._name = name
self._alias = alias
self._prefix = prefix
def name(self) -> str:
return self._name
def alias(self) -> str:
return self._alias
def prefix(self) -> str:
return self._prefix
def new_alias_table(name, alias):
prefix = ""
if alias == "":
prefix = name
else:
prefix = alias
return AliasTable(name, alias, prefix=prefix)
|
029eed69f21e51fe196224a5fbf95c8c5983cd84 | bhamal7/Task3 | /9.py | 108 | 4.03125 | 4 | n = int(input("Enter the number:"))
dict1 = dict()
for i in range(1,n+1):
dict1[i] = i*2
print(dict1)
|
0f972ebd21136f1593ad9a7726b129534706936d | Mezz403/Project-Euler | /Python/059_XOR Decryption (Optimized)/main.py | 742 | 3.671875 | 4 | import brute_force
import encryption
import letter_frequency
import text_analyzer
def main(filename):
with open(filename) as text:
intText = list(map(int, text.read().split(',')))
chrText = list(map(chr, intText))
frequencies = text_analyzer.text_analyzer(filename)
print('\nCreating brute force encryption file...')
brute_force.brute_force_encrypt(chrText, 97, 123)
print('Please review the created file to obtain the password')
password = input('\nWhat is the determined password: ')
message = encryption.encrypt(chrText, password)
return print('\nThe sum of the encrypted message is %d' % sum(message))
if __name__ == '__main__':
main('p059_cipher.txt') |
8554ac9b1cfd70eae40a5b2819014edb7b4580a7 | kukubimaa/Tugas-Kampus-- | /Tugas 4.py | 934 | 3.546875 | 4 | NAMA = raw_input("MASUKKAN NAMA ANDA :")
NIM = raw_input("MASUKKAN NIM ANDA :")
UTS = int(raw_input("MASUKKAN NILAI UTS ANDA :"))
UAS = int(raw_input("MASUKKAN NILAI UAS ANDA :"))
TUGAS = int(raw_input("MASUKAN NILAI TUGAS ANDA :"))
akhir = (UTS+UAS+TUGAS)/3
print"=================================="
print " NILAI AKHIR ANDA :", akhir
print "*****************************"
if akhir >=70 :
print "A"
print "LULUS"
elif akhir >=60 :
print "B"
print "LULUS"
elif akhir >=55 :
print "C"
print "TIDAK LULUS"
elif akhir <= 30 :
print "D"
print "TIDAK LULUS"
elif akhir <= 0 :
print "E"
print "TIDAK LULUS"
print "================================================================="
print "| Nama | NIM | Tugas | UTS | UAS | Akhir "
print "================================================================="
print "| rachmad dani bimaputra | 311710845 | 80 | 80 | 80 | 80 "
|
03d8c1b147a21616b238c33644b0bd6a488ba1ee | hellokayas/Some-Programming-Samples | /bit_manip.py | 6,364 | 4.34375 | 4 | import math
import sys
# | is bitwise or
# & and ~ are bitwise and and not respectively.
# x << y = x * 2**y which is x has its bits shifted to right by y places(think like multiplying by power of 10)
# x>>y = x // 2**y left shift
# can test if two bits equal or not by xoring them(^).
# Can flip a bit by xoring it with 1
#Write a function that takes an unsigned integer and returns the number of 1 bits it has.
#Iterate 32 times, each time determining if the ith bit is a ’1′ or not.
#This is probably the easiest solution, and the interviewer would probably not be too happy about it.
#MAIN IDEA : x - 1 would find the first set bit from the end, and then set it to 0, and set all the bits following it
#Which means if x = 10101001010100, Then x - 1 becomes 10101001010(011). All other bits in x - 1 remain unaffected.
#This means that if we do (x & (x - 1)), it would just unset the last set bit in x (which is why x&(x-1) is 0 for powers of 2).
# This method with x ^ (x-1) will also help finding number of trailing zeroes by setting them all to 1
def num_of_bit(A):
count = 0
while(A!= 0):
A = A & (A-1)
count += 1
return count
# reverse a binary number(atmost 32 bit) bitwise
def reverse(A):
ans = 0
for i in range(32):
if A & (1<<i):# 1<<i is 1 followed by i zeroes. A & (1<<i) gives the ith bit of A, if that is 1, then flip the just opposite bit
ans = ans | (1<<(31-i))#in ans, if the bit is 0, then we will have the opposite bit set in ans. 31-i gives the pos of the ith
return ans# bit reading from left to right
#We define f(X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f(2, 7) = 2,
#since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2
#given an array of N positive integers, A1, A2 ,…, AN. Find sum of f(Ai, Aj) for all pairs (i, j) such that 1 ≤ i, j ≤ N
def countbits(A):# we fix a bit and check how many a in A have that ith bit set and how many has ith bit unset
n = len(A)# count = how many has ith bit set. So on the ith bit we have count*(N-count) differences already. Need take x2 since
ans = 0# f(a,b) = f(b,a).
for i in range(31):# So now iterate over 31 bits and find the difference based on each bit and add that to the ans
count = 0# number of elems with ith bit set
for a in A:
if a & (1<<i):# gives the ith bit of a
count += 1# if ith bit set increase count
ans = ans + count*(n-count)*2
return ans
#Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value.
#Soln: Let’s suppose that the answer is not X[i] XOR X[i+1], but A XOR B and there exists C in the array such as A <= C <= B
#Next is the proof that either A XOR C or C XOR B are smaller than A XOR B.
#Let A[i] = 0/1 be the i-th bit in the binary representation of A
#Let B[i] = 0/1 be the i-th bit in the binary representation of B
#Let C[i] = 0/1 be the i-th bit in the binary representation of C
#This is with the assumption that all of A, B and C are padded with 0 on the left until they all have the same length
#Let i be the leftmost (biggest) index such that A[i] differs from B[i]. So B[i] = 1 and A[i] = 0. Two cases:
#1) C[i] = A[i] = 0, then (A XOR C)[i] = 0 and (A XOR B)[i] = 1. This implies (A XOR C) < (A XOR B)
#2) C[i] = B[i] = 1, then (B XOR C)[i] = 0 and (A XOR B)[i] = 1. This implies (B XOR C) < (A XOR B)
def minxor(A):#The first step is to sort the array. The answer will be the minimal value of X[i] XOR X[i+1] for every i
n = len(A)
A.sort()
result = float("inf")
for i in range(n):
val = A[i] ^ A[i+1]
result = min(result,val)
return result
#Given an array of integers, every element appears thrice except for one which occurs once. Find that element which does not appear thrice.
#If O(1) space constraint was not there, you could've gone for a hashmap with values being the count of occurrences in O(n) time.
# Soln: Run a loop for all elements in array. At the end of every iteration, maintain following two values.
#ones: The bits that have appeared 1st time or 4th time or 7th time .. etc.
#twos: The bits that have appeared 2nd time or 5th time or 8th time .. etc.
#Finally, we return the value of ‘ones’
#How to maintain the values of ‘ones’ and ‘twos’?
#‘ones’ and ‘twos’ are initialized as 0. For every new element in array, find out the common set bits in the new element and previous
# value of ‘ones’. These common set bits are actually the bits that should be added to ‘twos’. So do bitwise OR of the common set bits
#with ‘twos’. ‘twos’ also gets some extra bits that appear third time. These extra bits are removed later.
#Update ‘ones’ by doing XOR of new element with previous value of ‘ones’. There may be some bits which appear 3rd time. These extra bits
#are also removed later.
# Both ‘ones’ and ‘twos’ contain those extra bits which appear 3rd time. Remove these extra bits by finding out common set bits in
# ‘ones’ and ‘twos’.
def getSingle(arr, n):
ones = 0
twos = 0
for i in range(n):
# one & arr[i]" gives the bits that
# are there in both 'ones' and new
# element from arr[]. We add these
# bits to 'twos' using bitwise OR
twos = twos | (ones & arr[i])
# one & arr[i]" gives the bits that
# are there in both 'ones' and new
# element from arr[]. We add these
# bits to 'twos' using bitwise OR
ones = ones ^ arr[i]
# The common bits are those bits
# which appear third time. So these
# bits should not be there in both
# 'ones' and 'twos'. common_bit_mask
# contains all these bits as 0, so
# that the bits can be removed from
# 'ones' and 'twos'
common_bit_mask = ~(ones & twos)
# Remove common bits (the bits that
# appear third time) from 'ones'
ones &= common_bit_mask
# Remove common bits (the bits that
# appear third time) from 'twos'
twos &= common_bit_mask
return ones |
02ff53a09789c33fef7e5deb5a13942183203a08 | hellokayas/Some-Programming-Samples | /quicksort-leftright.py | 460 | 3.78125 | 4 | def qsort(l,b,e):
if b>=e:
return
p = b
q = p+1
while (q<=e):
if (l[q] > l[b]):
q=q+1
else:
l[q],l[p+1] = l[p+1],l[q]
p = p+1
q= q+1
l[b],l[p] = l[p],l[b]
qsort(l,b,p-1)
qsort(l,p+1,e)
def quicksort(l):
ls = l
qsort(ls,0,len(ls)-1)
return (ls)
M=[2,3,5,8,7,4,5,4,1,2,5,4,8,9,6,5,4,7,8,5,4,1,25,4,7,8]
quicksort(M)
print(M)
|
97d71dead162e971e3f3000fc85846ca8e14cbe8 | hellokayas/Some-Programming-Samples | /Strings.py | 10,521 | 3.984375 | 4 | import math
import sys
import string
from itertools import groupby
#Given a string A. Return the string A after reversing the string word by word.
#"the sky is blue" --> "blue is sky the"
def revword(S):# join returns words joined by space. Strip removes irrelevant spaces from start and end of the str
return "".join(S.strip().split()[::-1])# split decomposes the string into words by space, after that we reverse it and then join
#Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
#If the last word does not exist, return 0
def lastwordlen(s):
wordlength = 0
wordfound = False
new_s = s[::-1]# now look for the first word after spaces
for c in new_s:
if c == " ":# if space, then not found first word
if wordfound == True:# if found first word and c == " ", that means this is 2nd word, so return wordlength accumulated
return wordlength
continue# if first word not found and getting spaces only, go on
wordlength += 1# first letter encounter after c first gets a non space character
wordfound = True# c = a char not space, then set flag to true
return wordlength# if nothing found this returns 0 at the end
#Given the array of strings A, you need to find the longest string S which is the prefix of ALL the strings in the array
def longcomprefix(A):
min_word = min(A,key = lambda word : len(word))# find the word in A which has the least length, then the result will be its substring
m = len(A)
n = len(min_word)# the algorithm is O(mn)
for i in range(n):# fix the first letter of the smallest word
for j in range(m):# check the first letter of all the strings, if matches, then start with 2nd letter of min_word and match
if A[j][i] != min_word[i]:# if no match, then upto this is the longest match got, if fails for any j, then fails totally
return min_word[:i]
return min_word# all matches done and everything has gone through, so the whole of smallest string is prefix of all the rest strings
#1 is read off as one 1 or 11. 11 is read off as two 1s or 21. 21 is read off as one 2, then one 1 or 1211.
#Given an integer A, generate the Ath number in the sequence
def countnsay(A):
if A == 1:
return "1"
seed = countnsay(A-1)# using recursion
ans = ""
for i,n in groupby(seed):# look at https://www.geeksforgeeks.org/itertools-groupby-in-python/
ans += str(len(list(n))) + i[0]
return ans
#Compare two version numbers version1 and version2. If version1 > version2 return 1, If version1 < version2 return -1, otherwise return 0.
#For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level
# revision. 0.1 < 1.1 < 1.2 < 1.13 < 1.13.4 is a correct ordering of versions.
def compareversion(A,B):
verA = list(map(int,A.split(".")))# split both the numbers by "." to compare the real numbers and put them in the lists verA and verB
verB = list(map(int,B.split(".")))
a = len(verA)
b = len(verB)
for index in range(max(a,b)):# iterate over maxlen so that we cover both the lists
if index < a:# if index in range
anum = verA[index]# temp variable anum reqd for comparison
else:# index out of range, assign 0, bnum will be greater anyway if the value is nonzero
anum = 0
if index < b:
bnum = verB[index]# again temp var for verB
else:
bnum = 0
if anum > bnum :# we compare here
return 1
if bnum > anum:
return -1
return 0# equlaity has hold throughout
# string to integer atoi function to be implemented
def atoi(s):
s = s.strip() # strips all spaces on left and right
if not s: return 0
sign = -1 if s[0] == '-' else 1
val, index = 0, 0
if s[0] in ['+', '-']: index = 1
while index < len(s) and s[index].isdigit():
val = val*10 + ord(s[index]) - ord('0') # assumes there're no invalid chars in given string
index += 1
#return sign*val
return max(-2**31, min(sign * val,2**31-1))
# convert roman(given as string) to Integer
def romanToInt(A):
#The key is to notice that in a valid Roman numeral representation the letter with the most value always occurs at the start of the string.
#Whenever a letter with lesser value precedes a letter of higher value, it means its value has to be added as negative of that letter’s
#value. In all other cases, the values get added.
bank = {'X': 10, 'V' : 5, 'I' : 1, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}
res = 0
for i in xrange(0, len(A)):
cur = bank[A[i]]
if i+1 < len(A) and cur < bank[A[i+1]]:
res -= cur
else:
res+= cur
return res
def intToRoman(num):
num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
roman = ''
while num > 0:
for i, r in num_map:
while num >= i:
roman += r
num -= i
return roman
# given an int A, determine if it is a power of 2
def ispower(A):
s=int(A)
if s<=2:
return 0
if s&(s-1)==0:# another way: if(math.ceil(math.log2(num))==math.log2(num)): return 1
return 1
return 0
# given two binary strings add them
def add_bin_strings(x,y):
maxlen = max(len(x),len(y))# find the maxlen to pad the left of both strs with 0's
x = x.zfill(maxlen)
y = y.zfill(maxlen)
carry = 0# initialize
result = ""
for i in range(maxlen-1,-1,-1):# going backwards
temp = carry# staritng to add along each columns and carry
temp += 1 if x[i] == "1" else 0
temp += 1 if y[i] == "1" else 0# at this stage, temp is the sum of the current column along with carry
result += "1" if temp % 2 == 1 else "0"# acc to rules of bin addition
carry = 0 if temp < 2 else 1# acc rules of bin addition, temp = 1 means only one number in the column is 1
if carry != 0:# if no carry, we have got the result
result = "1" + result# else we add the most significant bit
return result.zfill(maxlen)
# Given two integers as strings, multiply them without any lib funcs
def str_multiply(num1,num2):
len1,len2 = len(num1),len(num2)
num1 = list(map(int,reversed(num1)))# converting each string to list whose elems are the digits in the reverse order
num2 = list(map(int,reversed(num2)))
result = [0]*(len1+len2)# init a result arr with all zeroes
for j in range(len2):
for i in range(len1):
result[i+j] += num1[i]*num2[j]
result[i+j+1] += result[i+j] // 10# this is adding the carry
result[i+j] = result[i+j] % 10# can have only one digit in each slot of the arr
i = len(result) - 1# going from back and removing the extra zeroes(now on right but the result is reversed now)
while(i>0 and result[i] == 0):
i -= 1# find that i upto where it has been padded with 0s
return "".join(map(str,result[:i+1][::-1]))# result[:i+1] removes the 0 padding and then [::-1] reverses, then converts to str
#Given an string A. The only operation allowed is to insert characters in the beginning of the string.
#Find how many minimum characters are needed to be inserted to make the string a palindrome string
def mincharpalin(A):# for the best soln see geeksforgeeks how to implement ideas from KMP algorithm
if A[::-1] == A:# already palindrome
return 0
j = len(A)-1
while(j>=0):# goinf back starting from full length
B = A[:j]# removing char one by one from the back
if B == B[::-1]:# if palindrome, then we have removed len(A)-j chars from back we have to append those in front to get
return len(A)-j# a palindrome
j -= 1# else just go on iterating
return len(A)-1# never a palindrome, the whole str needs to be appended in the front in reverse way to make a planindrome
# Given a string S, find the longest palindromic substring S[i...j] in S
# for the best soln refer: https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-3-2/
def longestpalin(s):
n = len(s)
for width in range(n-1,0,-1):# start with the max possible width of the substr and reduce upto substr of form [i,i+1]
index = 0# starting from the first so that if there is two substrs of equal length, we return the first one
while (index + width < n):# keeping a fixed width here
substr = s[index:index+width]
if substr == substr[::-1]:# the palindrome check
return substr# if found
index += 1# else go to the next index keeping the fixed width
#Given a string A consisting only of lowercase characters, we need to check whether it is possible to make this string a palindrome
#after removing exactly one character from this. If it is possible then return 1 else return 0.
def solve(A):
if(A==A[::-1]):# already palindrome
return(1)
i=0
j=len(A)-1
while(j>=i):# two pointer approach
if(A[i]==A[j]):# while equal go on to find the first mismatch
i+=1
j-=1
continue# can be ignored
elif(A[i]!=A[j]):# when the 1st mismatch found,
str1=A[i+1:j+1]# remove A[i] and check if palindrome
str2=A[i:j]# remove A[j] and check palindrome
if(str1==str1[::-1] or str2==str2[::-1]):# checking is done here, if one of them is, then done!
return(1)
else:
return(0)
i+=1# can be ignored
j-=1# can be ignored
return(0)
#Given a string A of parantheses ‘(‘ or ‘)’. The task is to find minimum number of parentheses ‘(‘ or ‘)’ (at any positions) we must
# add to make the resulting parentheses string valid.
def solve(A):
count1 = 0# how many ")" will be reqd corresponding to the open br
count2 = 0# how many "(" will be reqd corresponding to closed br
for i in A:
if i == "(":
count1 += 1
if i == ")" and not count1:# we putting close br but no open brackets there
count2 += 1
if i == ")" and count1> 0:# closing br but many open already present, since we can put anywhere the new brackets
count1 -= 1# the problem is lot easier
return count1+count2 |
d835bfb12ca4573d9088694f592fdd7366dc830b | hellokayas/Some-Programming-Samples | /Kruskals.py | 645 | 3.625 | 4 | from DisjSet import DisjSet
# Graph vertices are number 0 .. N-1 and M is the number of edges
def readEdgeList():
line = input()
l = line.split()
N = int(l[0])
M = int(l[1])
G = [] # List of the form (wt,vertex1,vertex2)
for i in range(0,M):
line = input()
l = line.split()
ls = list(map(int,l))
G.append((ls[2],ls[0],ls[1])) # put weight first
return (N,G)
def mcst():
(N,G) = readEdgeList()
G.sort(reverse=True)
S = DisjSet(N)
Tree = []
Wt = 0
while G != [] :
(w,u,v) = G.pop()
su = S.find(u)
sv = S.find(v)
if su != sv:
S.merge(su,sv)
Tree.append((u,v,w))
Wt = Wt + w
print(Wt)
print(Tree)
mcst()
|
7eb869c50b42c1dc264327091a01d2b8bf5650bd | alvaronem/Codewars-Python-practice | /Sum-by-factors.py | 773 | 3.65625 | 4 | def prime_factors(n):
i = 2
factors = []
if n < 0:
n *= -1
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def combine(arr1, arr2):
for a in arr1:
if not a in arr2:
arr2.append(a)
return arr2
def sum_for_list(lst):
#....
factors = []
sums = []
for i in range(len(lst)):
combine(prime_factors(lst[i]),factors)
for i in range(len(factors)):
msum = 0
for j in range(len(lst)):
if not lst[j]%factors[i]:
msum += lst[j]
sums.append([factors[i], msum])
sums.sort(key=lambda factors:factors[0])
return sums
|
3e4752456955b6e55f9063a8a5fc7d5a295a1489 | saitoshin45/AnimalTetris- | /tetris2.py | 2,310 | 3.6875 | 4 | #tetris2.py
#import the necessary drivers
import tkinter
import random
#variable declaration
mouseX = 0
mouseY = 0
mouseC = 0
cursorX = 0
cursorY = 0
#function for the mouse positions
def mouse_move(e):
global mouseX, mouseY
mouseX = e.x
mouseY = e.y
#function to get the mouse click
def mouse_press(e):
global mouseC
mouseC = 1
#array for the tetris game
board = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]
]
def draw_piece():
for y in range(10):
for x in range(8):
if board[y][x] > 0:
cvs.create_image(x*72+60, y*72+60, image = p_img[board[y][x]],tag ="PUZZLE")
#function to drop the pieces
def drop():
for y in range(8,-1,1):
for x in range(8):
if puzzle[y][x] != 0 and puzzle[y+1][x] == 0:
puzzle[y+1][x] = puzzle[y][x]
puzzle[y][x] = 0
#function for the game
def game_main():
global cursorX, cursorY, mouseC
drop()
if 24 <= mouseX and mouseX < 24+72*8 and 24 <= mouseY and mouseY < 24*72+10:
cursorX = int((mouseX -24)/72)
cursorY = int((mouseY-24)/72)
if mouseC == 1:
mouseC = 0
puzzle[cursorY][cursorX] = random.randint(1,6)
cvs.delete("CURSOR")
cvs.create_image(cursorX*72+60, cursorY*72+60, image=cursor, tag="CURSOR")
cvs.delete("PUZZLE")
draw_piece()
root.after(100,game_main)
cvs.pack()
#main driver
root = tkinter.Tk()
root.title("practice")
root.resizable(False,False)
root.bind("<Motion>",mouse_move)
cvs = tkinter.Canvas(root, width=912, height=768)
cvs.pack()
bg = tkinter.PhotoImage(file="neko_bg.png")
cursor = tkinter.PhotoImage(file="neko_niku.png")
p_img = [
None,
tkinter.PhotoImage(file="pokeball.png"),
tkinter.PhotoImage(file="superball.png"),
tkinter.PhotoImage(file="masterball.png"),
tkinter.PhotoImage(file="rain.png"),
tkinter.PhotoImage(file = "sun.png"),
tkinter.PhotoImage(file="premier-ball.png"),
tkinter.PhotoImage(file = "neko_cursor.png")
]
cvs.create_image(456,384, image = bg)
game_main()
root.mainloop()
|
10bc69d936b58fb5ed927a8a30970b88b804aeb8 | ashutoshabhimanyuxyz/loltracker | /location.py | 275 | 3.5625 | 4 | import phonenumbers
from phonenumbers import carrier
from phonenumbers import geocoder
num = input("Enter your phone number:")
phone_number = phonenumbers.parse(num)
print(geocoder.description_for_number(phone_number,"en"))
print(carrier.name_for_number(phone_number,"en")) |
c9c178a50f1a0a35908b8c38b43e798f27c27f2c | MSO-star/SP_opdrachten | /4.py | 485 | 3.578125 | 4 | def palindroom_version2(woord):
letters_woord= list(woord)
pali= True
for i in letters_woord:
if i ==letters_woord[-1]:
letters_woord.pop(-1)
else:
pali= False
break
return pali
print(palindroom_version2("malayalam"))
def palindroom_version1(woord):
woord_rev= reversed(woord)
if list(woord) == list(woord_rev):
print("True")
else:
print("False")
print(palindroom_version1("malayalam")) |
517d7f68fcfa50417dc4cc8fd4902b41d706171e | LilGherkin/PythonPractice | /2FlowControl.py | 7,599 | 4.5625 | 5 | # Boolean values are values that equate to either True or False.
booleanexample1 = True
booleanexample2 = False
# Python has comparision operators that will output as True or False.
# == equal to. 42 == 42 outputs 2. 41 == 42 outputs false.
# != not equal to. 42 != 41 outputs true. 42 != 42 is false.
# < less than. 42 < 43 is true. 42 < 41 is false.
# > greater than. 42 > 41 is true. 42 > 43 is false.
# <= less than or equal to. 42 <= 42 is true. 42 <= 41 is false.
# >= greater than or equal to. 42 >= 42 is true. 42 >= 43 is false.
# == & != can work for any data type including strings. "Hello" == "Hello" is true. "Hello" == "hello" is false due to case sensitivity.
# == cannot work between strings and ints/floats, but == can work between floats and ints.
# != would work mostly as intended between strings and ints/floats
print(42==42.0) #This will evaluate to true as both are numbers.
print('42'==42) #This will evaluate to false becase '42' is different from 42.
# Boolean operators exist. They are AND, OR, and NOT.
# AND evaluates to true if all parts of the expression are true.
## True AND True = True. True AND False = False.
# OR evalautes to true if at least one of the parts of the expression are true.
## True OR True = True, True OR False = True, False OR False = False
# NOT inverts whatever the end result is.
## NOT True = False, NOT False = True.
## NOT operators can be nested. NOT NOT True = True.
# We can use comparison operators and boolean operators in conjunction with one another.
print((5 > 3) and (5 >2))
# Flow control statements often start with a part called the condition and are always followed by a block of code called the clause.
# Conditions always evaluate down to a Boolean value, True or False.
# A flow control statement decides what to do based on whether its condition is True or False.
# Almost every flow control statement uses a condition.
# Lines of Python code can be grouped together in blocks.
# You can tell when a block begins and ends from the indentation of the lines of code.
# There are three rules for blocks.
## Blocks begin when the indentation increases.
## Blocks can contain other blocks.
## Blocks end when the indentation decreases to zero or to a containing block’s indentation.
name = 'Mary'
password = 'swordfish'
if name == 'Mary':
print('Hello, Mary')
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
# If statements are a form of flow control. If the condition is met, then execute the following line, otherwise, skip it.
# else is to be executed if the evaluation at the if statement is false. if x is true do y, else do z.
# elif is to be included in things where we have multiple cases, with the else acting as a catch all.
## if name == 'mary' do x, elif name == 'sue' do y, else do z.
name = 'Carol' # Set our name to Carol
age = 3000 # Set our age to 3000
if name == 'Alice': # Is our name == 'Alice'. No, it's Carol. We'll skip this block.
print('Hi, Alice.') # Skipped
elif age < 12: # Is our age < 12? No, we're 3000. Skip this block.
print('You are not Alice, kiddo.') # Skipped.
elif age > 2000: # Is our age > 2000? Yes, we're 3000, we'll execute this block.
print('Unlike you, Alice is not an undead, immortal vampire.') # Print this line.
elif age > 100: # We've already hit our first true statement, so this will get skipped even though it is true as well.
print('You are not Alice, grannie.') # Skipped.
# We can swap the age blocks, and get a different print out.
name = 'Carol' # Set our name to Carol
age = 3000 # Set our age to 3000
if name == 'Alice': # Is our name == 'Alice'. No, it's Carol. We'll skip this block.
print('Hi, Alice.') # Skipped
elif age < 12: # Is our age < 12? No, we're 3000. Skip this block.
print('You are not Alice, kiddo.') # Skipped.
elif age > 100: # Is our age > 100? Yes, we're 3000, we'll execute this block.
print('You are not Alice, grannie.') # Print this line.
elif age > 2000: # We already hit a true condition. So this is skipped.
print('Unlike you, Alice is not an undead, immortal vampire.') # Skipped.
# We don't have any else statements in this block. So if we were to change our age to somewhere between 12 and 100, it would error out.
# We can set it up with an else statement that serves as a catch all.
name = 'Carol'
age = 75
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
# WHILE Loops
# We can set a loop that continues to run until something causes it to stop.
counter = 0
while counter < 5:
print("Hello, world!")
counter = counter + 1
# The above will print out Hello world 5 times, counter keeps getting overwritten with a new number until counter < 5 = false.
# We can set up an annoying while loop that doesn't break until you set your name to 'your name'
name = '' #blank out our name variable since we use it in our previous examples.
while name != 'your name':
print('Please type your name')
name = input()
print('Thank you.')
# Assuming we never figured out that name needs to be your name, we would be trapped there until we figured it out.
# We can do the same thing, except we can theoretically trap someone forever.
# We can use the following code to create an infinite loop. The only thing that saves someone is by typing your name to trigger a break.
# If the break werent' there, no matter what they typed in, they'd be stuck.
# Break takes escapes you from the current block.
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you.')
# A true infite loop can be broken by hitting CTRL + C in the command prompt. Uncomment the following 2 lines to test it.
# while True:
# print('Hello, world!')
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. Please enter your password.')
password = input()
if password == 'Barricuda':
break
print('Access granted')
# Continue is similar to break, except we tell it to essentially skip whatever use case we hit. For example if we have a divid by 0
# we can use continue to essentially keep running the loop, but know that if we hit 0 we need to skip over it.
# FOR loops
# For each item in a list do the following.
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
total = 0
for num in range(101):
total = total + num
print(total)
# You can use a while loop in place of a for loop some times such as in the following:
print('My name is')
i = 0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i = i + 1
# Some functions can take in multipe arguments. range() is one of them. We can call range(x y z) x = starting value y = end z = interval.
# range(0, 10, 2) Will get every number from 0-10 and increments by 2 so we'll see 0, 2, 4, 6, 8.
for i in range(0, 10, 2):
print(i)
# We can use this functionality to count down as well. The following will print out 5, 4, 3, 2, 1, 0.
for i in range(5, -1, -1):
print(i)
# We can import modules into python to perform functiosn outside of basic python's scope.
# We call these with 'import' along with the module name.
# The following calls the random module white
import random
for i in range(5):
print(random.randint(1,10))
# We can import multiple modules by separating them with commas as seen in the following example.
import random, sys, os, math |
08a2ef01d9989af3a634dec93ccbd125000eda40 | m-kashani/Problem-Solving-in-Data-Structures-Algorithms-using-Python | /IntroductoryChapters/Bulb.py | 574 | 3.53125 | 4 | #!/usr/bin/env python
class Bulb(object):
def __init__(self): # Constructor
self.isOn = False # Instance Variable
def turnOn(self): # Instance Method
self.isOn = True
def turnOff(self): # Instance Method
self.isOn = False
def isOnFun(self): # Instance Method
return self.isOn
b = Bulb()
print "bulb is on return : " , b.isOnFun()
b.turnOn()
print "bulb is on return : " , b.isOnFun()
c = Bulb()
print "bulb c is on return : " , c.isOnFun()
|
bdf32e67adb4716e6e2e5f7e122c6359832021a7 | m-kashani/Problem-Solving-in-Data-Structures-Algorithms-using-Python | /IntroductoryChapters/ForDemo.py | 710 | 3.96875 | 4 | #!/usr/bin/env python
text = "Hello, World!"
PI = 3.141592653589793
def main1():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
totalsum = 0
for n in numbers:
totalsum += n
print "Sum is :: " , totalsum
def main2():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
totalsum = 0
i = 0
while i < len(numbers):
totalsum += numbers[i]
i += 1
print "Sum is :: " , totalsum
def main3():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
totalsum = 0
i = 0
while True:
totalsum += numbers[i]
i += 1
if i >= len(numbers):
break
print "Sum is :: " , totalsum
main1()
main2()
main3()
|
c73a54771e27fb298a73d595b5d925514f68e6cc | prashantchanne12/Leetcode | /find the first k missing positive numbers.py | 1,383 | 4.125 | 4 | '''
Given an unsorted array containing numbers and a number ‘k’, find the first ‘k’ missing positive numbers in the array.
Example 1:
Input: [3, -1, 4, 5, 5], k=3
Output: [1, 2, 6]
Explanation: The smallest missing positive numbers are 1, 2 and 6.
Example 2:
Input: [2, 3, 4], k=3
Output: [1, 5, 6]
Explanation: The smallest missing positive numbers are 1, 5 and 6.
Example 3:
Input: [-2, -3, 4], k=2
Output: [1, 2]
Explanation: The smallest missing positive numbers are 1 and 2.
'''
def find_first_k_missing_positive(nums, k):
n = len(nums)
i = 0
while i < n:
j = nums[i] - 1
if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
# swap
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
missing_numbers = []
extra_numbers = set()
for i in range(n):
if len(missing_numbers) < k:
if nums[i] != i + 1:
missing_numbers.append(i+1)
extra_numbers.add(nums[i])
# add the remaining numbers
i = 1
while len(missing_numbers) < k:
candidate_number = i + n
# ignore if the extra_array contains the candidate number
if candidate_number not in extra_numbers:
missing_numbers.append(candidate_number)
i += 1
print(missing_numbers)
find_first_k_missing_positive([2, 3, 4], 3)
|
879cde7a247d8c82757190d715cca62bcad6d168 | prashantchanne12/Leetcode | /longest substring without repeat character.py | 1,100 | 4.09375 | 4 | '''
Share
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
'''
class Solution(object):
def lengthOfLongestSubstring(self, s):
dict = {}
current_length = 0
max_length = 0
current_sub_start = 0
for i, letter in enumerate(s):
if letter in dict and dict[letter] >= current_sub_start:
current_sub_start = dict[letter]+1
current_length = i - dict[letter]
dict[letter] = i
else:
dict[letter] = i
current_length += 1
if current_length> max_length:
max_length = current_length
return max_length
|
5718a2011b7dcd969516e4c3f2b24b2cebfa713b | prashantchanne12/Leetcode | /reverse linked list.py | 1,355 | 4.3125 | 4 | '''
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
'''
# Solution 1
class Solution(object):
def reverseList(self, head):
prev = None
current = head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
head = prev
return head
# Solution 2
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def print_list(head):
while head is not None:
print(head.val, end='->')
head = head.next
def reverse_linked_list(current):
previous = None
current = head
next = None
while current is not None:
next = current.next # temporary store the next node
current.next = previous # reverse the current node
# before we move to the next node, point previous node to the current node
previous = current
current = next # move on the next node
return previous
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
reversed = reverse_linked_list(head)
print_list(reversed)
|
831977afd452ae4782e43ffef22f77c08dfafcbc | prashantchanne12/Leetcode | /Kth largets element.py | 976 | 4 | 4 | from heapq import *
'''
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
'''
# Solution - 1
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
return nums[::-1][k-1]
# Solution - 2 (preferred)
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
min_heap = []
for i in range(0, k):
heappush(min_heap, nums[i])
for i in range(k, len(nums)):
if nums[i] > min_heap[0]:
heappop(min_heap)
heappush(min_heap, nums[i])
return min_heap[0]
|
37d21dbd7a42294165351460e68d301d30416a5a | prashantchanne12/Leetcode | /trapping rainwater.py | 1,421 | 4.09375 | 4 | '''
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
'''
class Solution(object):
def trap(self, height):
total_water = 0
max_left = 0
max_right = 0
left = 0
right = len(height) - 1
while left < right:
if height[left] <= height[right]:
if height[left] >= max_left:
# cant form a wall, current pointer has greater height
max_left = height[left]
else:
total_water += max_left - height[left]
left += 1
else:
if height[right] >= max_right:
# cant form a wall, current pointer has greater height
max_right = height[right]
else:
total_water += max_right - height[right]
right -= 1
return total_water |
d57e3c988f5311a9198d2d8bcd415c58ebb837d6 | prashantchanne12/Leetcode | /daily tempratures.py | 923 | 4.1875 | 4 | '''
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
'''
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
res = [0] * len(T)
stack = []
for i, t in enumerate(T):
while stack and t > stack[-1][1]:
index, temprature = stack.pop()
res[index] = i - index
stack.append((i, t))
return res
|
20801f067b8f3b6248285c98c759bf60ef833c5f | prashantchanne12/Leetcode | /backspace string compare - stack.py | 1,839 | 4.1875 | 4 | '''
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
'''
# Solution - 1
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def build(str):
arr = []
for i in str:
if i != '#':
arr.append(i)
else:
if arr:
arr.pop()
return ''.join(arr)
return build(S) == build(T)
# Solution - 2
def build(string):
arr = []
for chr in string:
if chr == '#' and len(arr) != 0:
arr.pop()
elif chr != '#':
arr.append(chr)
return arr
def typed_out_strings(s, t):
s_arr = build(s)
t_arr = build(t)
return ''.join(s_arr) == ''.join(t_arr)
print(typed_out_strings('##z', '#z'))
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
string_1 = ''
string_2 = ''
for char in s:
if char == '#':
if len(string_1) > 0:
string_1 = string_1[:-1]
else:
string_1 += char
for char in t:
if char == '#':
if len(string_2) > 0:
string_2 = string_2[:-1]
else:
string_2 += char
return string_1 == string_2
|
209882f118ac28481841a9577f2caba3b5ecdbf6 | prashantchanne12/Leetcode | /path with given sequence.py | 2,155 | 4 | 4 | '''
Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.
'''
# Solution - 1
# sequence - 101 (in the form of integer)
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def path_with_given_sequence(root, sequence):
return find_numbers(root, 0, sequence)
def find_numbers(current_node, path_sum, sequence):
if current_node is None:
return 0
# calculate the path number of the current node
path_sum = 10 * path_sum + current_node.val
# if the current node is a leaf, return the current path sum
if current_node.left is None and current_node.right is None:
return path_sum == sequence
# traverse the left and the right sub-tree
return find_numbers(current_node.left, path_sum, sequence) or find_numbers(current_node.right, path_sum, sequence)
def main():
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)
print(path_with_given_sequence(root, 101))
main()
# Solution - 2
# sequence - [1,0,1] (in the form of array)
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def path_with_given_sequence(root, sequence):
return find_numbers(root, [], sequence)
def find_numbers(current_node, path, sequence):
if current_node is None:
return 0
path.append(current_node.val)
if current_node.left is None and current_node.right is None:
return path == sequence
# traverse the left and the right sub-tree
return find_numbers(current_node.left, path, sequence) or find_numbers(current_node.right, path, sequence)
def main():
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)
print(path_with_given_sequence(root, [1, 0, 1]))
main()
|
e2aa15140104f1ea6013fdc5526e3dac39720a5a | prashantchanne12/Leetcode | /first duplicate.py | 504 | 3.921875 | 4 | '''
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
'''
class Solution(object):
def findDuplicate(self, nums):
l = set()
for i in nums:
if i in l:
return i
else:
l.add(i) |
4cc773965da12e433077f96090bdeea04579534a | prashantchanne12/Leetcode | /pascal triangle II.py | 688 | 4.1875 | 4 | '''
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
'''
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [[1]]
for i in range(rowIndex):
temp = [0] + res[-1] + [0]
row = []
for j in range(len(res[-1])+1):
row.append(temp[j] + temp[j+1])
res.append(row)
return res[-1]
|
68b5f431afb5a3422a1f90195e341c0bb348a8f4 | prashantchanne12/Leetcode | /balance a binary search tree.py | 1,405 | 4.09375 | 4 | '''
Given a binary search tree, return a balanced binary search tree with the same node values.
A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.
If there is more than one answer, return any of them.
Example 1:
Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2,null,null] is also correct.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.arr = []
def inorder(self, root):
if root is not None:
self.inorder(root.left)
self.arr.append(root)
self.inorder(root.right)
def balanceBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.inorder(root)
def solve(left, right):
if left > right:
return
mid = (left + right) // 2
node = self.arr[mid]
node.left = solve(left, mid-1)
node.right = solve(mid+1, right)
return node
left = 0
right = len(self.arr) - 1
return solve(left, right)
|
5efbfb64f054e7cbcd77aa0f55599835c48b4d0d | prashantchanne12/Leetcode | /bitonic array maximum.py | 998 | 4.34375 | 4 | '''
Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explanation: The maximum number in the input bitonic array is '12'.
Example 2:
Input: [3, 8, 3, 1]
Output: 8
Example 3:
Input: [1, 3, 8, 12]
Output: 12
Example 4:
Input: [10, 9, 8]
Output: 10
'''
def find_max_in_bitonic_array(arr):
low = 0
high = len(arr) - 1
while low < high:
mid = (low+high) // 2
if arr[mid] > arr[mid+1]:
high = mid
else:
low = mid + 1
# at the end of the while loop, 'start == end'
return arr[low]
print(find_max_in_bitonic_array([1, 3, 8, 12, 4, 2]))
print(find_max_in_bitonic_array([3, 8, 3, 1]))
print(find_max_in_bitonic_array([1, 3, 8, 12]))
print(find_max_in_bitonic_array([10, 9, 8]))
|
a66aab6ac79fbd01af1c0c3f4558ef3f75277d8d | prashantchanne12/Leetcode | /set mismatch.py | 859 | 4.0625 | 4 | '''
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
'''
class Solution(object):
def findErrorNums(self, nums):
dict = {}
res = []
for i in nums:
if i in dict:
res.append(i)
else:
dict[i] = True
for i in range(1,len(nums)+1):
if i not in nums:
res.append(i)
return res
|
c8ce6f1d1f34106357210c7361c2471bea783240 | prashantchanne12/Leetcode | /smallest missing positive number.py | 712 | 4.21875 | 4 | '''
Given an unsorted array containing numbers, find the smallest missing positive number in it.
Example 1:
Input: [-3, 1, 5, 4, 2]
Output: 3
Explanation: The smallest missing positive number is '3'
Example 2:
Input: [3, -2, 0, 1, 2]
Output: 4
Example 3:
Input: [3, 2, 5, 1]
Output: 4
'''
def find_missing_positive(nums):
i = 0
n = len(nums)
while i < n:
j = nums[i] - 1
if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
# swap
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
for i in range(0, n):
if nums[i] != i + 1:
return i + 1
return n + 1
print(find_missing_positive([3, -2, 0, 1, 2]))
|
5944bd2874c4a561cebcc44ab45cd8a725b0cc05 | prashantchanne12/Leetcode | /power of two.py | 344 | 3.953125 | 4 | '''
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
'''
class Solution(object):
def isPowerOfTwo(self, n):
return (n != 0) and ((n & (n - 1)) == 0);
|
f9cdd9e18578be52a8d31f9d525d5376520bc13f | prashantchanne12/Leetcode | /reconstruct sequence.py | 2,926 | 3.765625 | 4 | '''
Given a sequence originalSeq and an array of sequences, write a method to find if originalSeq can be uniquely reconstructed from the array of sequences.
Unique reconstruction means that we need to find if originalSeq is the only sequence such that all sequences in the array are subsequences of it.
Example 1:
Input: originalSeq: [1, 2, 3, 4], seqs: [[1, 2], [2, 3], [3, 4]]
Output: true
Explanation: The sequences [1, 2], [2, 3], and [3, 4] can uniquely reconstruct
[1, 2, 3, 4], in other words, all the given sequences uniquely define the order of numbers
in the 'originalSeq'.
Example 2:
Input: originalSeq: [1, 2, 3, 4], seqs: [[1, 2], [2, 3], [2, 4]]
Output: false
Explanation: The sequences [1, 2], [2, 3], and [2, 4] cannot uniquely reconstruct
[1, 2, 3, 4]. There are two possible sequences we can construct from the given sequences:
1) [1, 2, 3, 4]
2) [1, 2, 4, 3]
Example 3:
Input: originalSeq: [3, 1, 4, 2, 5], seqs: [[3, 1, 5], [1, 4, 2, 5]]
Output: true
Explanation: The sequences [3, 1, 5] and [1, 4, 2, 5] can uniquely reconstruct
[3, 1, 4, 2, 5].
'''
from collections import deque
def reconstruct_sequence(oringinal_seq, sequences):
sorted_order = []
if len(oringinal_seq) <= 0:
return False
# 1) Initiliaze the graph
# count of incoming edges
in_degrees = {}
# count of adjecency list graph
graph = {}
for sequence in sequences:
for num in sequence:
in_degrees[num] = 0
graph[num] = []
# 2) Built the graph
for parnet, child in sequences:
graph[parnet].append(child)
in_degrees[child] += 1
# if we don't have ordering rules for all the numbers we'll not able to uniquely construct the sequence
if len(in_degrees) != len(oringinal_seq):
return False
# 3) Find all sources i.e. all nodes with 0 in-degrees
sources = deque()
for key in in_degrees:
if in_degrees[key] == 0:
sources.append(key)
# 4) For each source, add it to the sorted order and subtract on from all of its children
# if child's in-degrees becomes zero, add it to the sources queue
while sources:
# more than one sequence mean, there is more than one way to reconstruct the sequence
if len(sources) > 1:
return False
if oringinal_seq[len(sorted_order)] != sources[0]:
# the next sources(or number) is different from the original sequence
return False
node = sources.popleft()
sorted_order.append(node)
for child in graph[node]:
in_degrees[child] -= 1
if in_degrees[child] == 0:
sources.append(child)
# if sorted order's size is not equal to original sequence's size, there is no unique way to construct
return len(sorted_order) == len(oringinal_seq)
print(reconstruct_sequence([1, 2, 3, 4], [[1, 2], [2, 3], [3, 4]]))
|
cb3e496fd43b93383a978d3e0ec27b37b5a57008 | prashantchanne12/Leetcode | /partition list.py | 1,071 | 4 | 4 | '''
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2
Output: [1,2]
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
current = l1 = ListNode(0)
l2_start = l2 = ListNode(0)
while head is not None:
if head.val < x:
l1.next = ListNode(head.val)
l1 = l1.next
else:
l2.next = ListNode(head.val)
l2 = l2.next
head = head.next
l1.next = l2_start.next
return current.next
|
4708114b3e8133dddc8e6dc9d758bfc7dc25e5c4 | prashantchanne12/Leetcode | /find shortest path-graph dfs.py | 488 | 3.78125 | 4 | graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def find_shortest_path_dfs(source, destination, visited, graph, dist):
if source not in visited:
visited.add(source)
if source == destination:
print(dist)
for n in graph[source]:
find_shortest_path_dfs(n, destination, visited, graph, dist+1)
visited = set()
print(find_shortest_path_dfs('A', 'E', visited, graph, 0))
|
1811fedf3317e61f5fa1f70b1669b47cae04716d | prashantchanne12/Leetcode | /validate binary search tree.py | 1,294 | 4.125 | 4 |
import math
'''
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
'''
# 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 isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
return self.dfs(root, -math.inf, math.inf)
def dfs(self, root, min_val, max_val):
if root.val <= min_val or root.val >= max_val:
return False
if root.left:
if not self.dfs(root.left, min_val, root.val):
return False
if root.right:
if not self.dfs(root.right, root.val, max_val):
return False
return True
|
0423ec8f68bdbea0933002ff792eaaf73b0026e5 | prashantchanne12/Leetcode | /merge intervals.py | 1,718 | 4.375 | 4 | '''
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Intervals: [[1,4], [2,5], [7,9]]
Output: [[1,5], [7,9]]
Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into
one [1,5].
Example 2:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 3:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
'''
def sort_array(intervals):
arr = []
# sort outer elements
intervals.sort()
# sort inner elements
for nums in intervals:
nums.sort()
arr.append(nums)
return arr
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if len(intervals) <= 1:
return intervals
# sort 2D array of intervals
arr = sort_array(intervals)
merged_array = []
start = arr[0][0]
end = arr[0][1]
for i in range(1,len(intervals)):
interval = intervals[i]
if interval[0] <= end:
end = max(end, interval[1])
else:
merged_array.append([start, end])
# update the start and end
start = interval[0]
end = interval[1]
# add the last interval
merged_array.append([start, end])
return merged_array |
8f2ce57a0f07d2f6087b2511b27d44546559d555 | prashantchanne12/Leetcode | /doubly linked list.py | 1,327 | 4 | 4 | class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_at_beg(self,data):
if self.head == None:
node = Node(data, None, None)
self.head = node
self.tail = node
else:
node = Node(data)
self.head.prev = node
node.next = self.head
node.prev = None
self.head = node
def insert_at_end(self,data):
pass
def display_forward(self):
if self.head == None:
print('List is empty')
return
temp = self.head
while temp:
print(temp.data, end=' -> ')
temp = temp.next
def display_backwords(self):
if self.head == None:
print('List is empty')
return
temp = self.tail
while temp:
print(temp.data, end=' -> ')
temp = temp.prev
l = LinkedList()
l.insert_at_beg(10)
l.insert_at_beg(20)
l.insert_at_beg(30)
l.display_forward()
print()
l.display_backwords() |
30c022b03d26825d5edcce633de3b490123772eb | prashantchanne12/Leetcode | /valid pallindrome.py | 698 | 4.21875 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
import re
class Solution(object):
def isPalindrome(self, s):
s = s.lower()
arr = re.findall(r'[^\W_]', s)
s = ''.join(arr)
left = 0
right = len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return False
return True
|
d25b0c3eb45e06f100dab5ca4699e529a17d0db6 | prashantchanne12/Leetcode | /insert interval.py | 3,240 | 4.1875 | 4 | '''
Given a list of non-overlapping intervals sorted by their start time, insert a given interval at the correct position and merge all necessary intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Input: Intervals=[[1,3], [5,7], [8,12]], New Interval=[4,6]
Output: [[1,3], [4,7], [8,12]]
Explanation: After insertion, since [4,6] overlaps with [5,7], we merged them into one [4,7].
Example 2:
Input: Intervals=[[1,3], [5,7], [8,12]], New Interval=[4,10]
Output: [[1,3], [4,12]]
Explanation: After insertion, since [4,10] overlaps with [5,7] & [8,12], we merged them into [4,12].
Example 3:
Input: Intervals=[[2,3],[5,7]], New Interval=[1,4]
Output: [[1,4], [5,7]]
Explanation: After insertion, since [1,4] overlaps with [2,3], we merged them into one [1,4].
'''
# Solution 1
def sort_array(intervals):
arr = []
intervals.sort()
for nums in intervals:
nums.sort()
arr.append(nums)
return arr
def insert(intervals, new_intervals):
intervals.append(new_intervals)
# sort the array
arr = sort_array(intervals)
start = arr[0][0]
end = arr[0][1]
merged = []
for i in range(1, len(intervals)):
interval = intervals[i]
if interval[0] <= end:
# merge the overlap array
end = max(end, interval[1])
else:
merged.append([start, end])
# update the start end
start = interval[0]
end = interval[1]
# add the last interval
merged.append([start, end])
return merged
print(insert([[1, 3], [5, 7], [8, 12]], [4, 6]))
# Solution 2
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
merged_array = []
index = 0
# skip all the intervals before 'newInterval'
while index < len(intervals) and newInterval[0] > intervals[index][1]:
merged_array.append(intervals[index])
index += 1
start = newInterval[0]
end = newInterval[1]
for i in range(index, len(intervals)):
interval = intervals[i]
if interval[0] <= end:
start = min(start, interval[0])
end = max(end, interval[1])
else:
merged_array.append([start, end])
start = interval[0]
end = interval[1]
merged_array.append([start, end])
return merged_array
# Solution - 3
def insert_interval(intervals, new_interval):
res = []
index = 0
while index < len(intervals) and new_interval[0] > intervals[index][1]:
res.append([intervals[index][0], intervals[index][1]])
index += 1
start = new_interval[0]
end = new_interval[1]
for i in range(index, len(intervals)):
interval = intervals[i]
if interval[0] <= end:
start = min(start, interval[0])
end = max(end, interval[1])
else:
res.append([start, end])
start = interval[0]
end = interval[1]
res.append([start, end])
return res
|
6aab48bb7e3c455f36278482dad88fa76915b4c4 | prashantchanne12/Leetcode | /single number bitwise.py | 347 | 4.0625 | 4 | '''
In a non-empty array of integers, every number appears twice except for one, find that single number.
Example 1:
Input: 1, 4, 2, 1, 3, 2, 3
Output: 4
Example 2:
Input: 7, 9, 7
Output: 9
'''
def find_single_number(arr):
res = 0
for num in arr:
res = res ^ num
return res
print(find_single_number([1, 2, 3, 2, 1]))
|
8eab0b75982372250d35703ec9ae464e24498417 | prashantchanne12/Leetcode | /longest subarray with ones after replacemenet.py | 1,114 | 4.03125 | 4 | '''
Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.
Example 1:
Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
Output: 6
Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6.
Example 2:
Input: Array=[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], k=3
Output: 9
Explanation: Replace the '0' at index 6, 9, and 10 to have the longest contiguous subarray of 1s having length 9.
'''
def ones_after_replacement(nums, k):
window_start = 0
max_length = 0
max_ones = 0
for window_end in range(0, len(nums)):
if nums[window_end] == 1:
max_ones += 1
if (window_end-window_start+1) - max_ones > k:
# shrink the window from start
if nums[window_start] == 1:
max_ones -= 1
window_start += 1
max_length = max(max_length, (window_end-window_start+1))
return max_length
print(ones_after_replacement([0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2))
|
713c22ad11eec595b3337a723d15c8ae336ea4bd | prashantchanne12/Leetcode | /count paths for sum.py | 1,458 | 3.78125 | 4 | '''
Given a binary tree and a number ‘S’, find all paths in the tree such that the sum of all the node values of each path equals ‘S’. Please note that the paths can start or end at any node but all paths must follow direction from parent to child (top to bottom).
'''
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_paths(root, sum):
return count_paths_recursive(root, sum, [])
def count_paths_recursive(current_node, sum, current_path):
if current_node is None:
return 0
# add the current node to the path
current_path.append(current_node.val)
path_count = 0
path_sum = 0
# start, end, jump
for i in range(len(current_path)-1, -1, -1):
path_sum += current_path[i]
# if the sum of any sub-path is equal to 'sum' we increment our path count
if path_sum == sum:
path_count += 1
# traverse the left sub-tree
path_count += count_paths_recursive(current_node.left, sum, current_path)
path_count += count_paths_recursive(current_node.right, sum, current_path)
del current_path[-1]
return path_count
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(4)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print(count_paths(root, 11))
main()
|
3726adcdf00bf55230f9320a44a4b4a25da5efde | prashantchanne12/Leetcode | /01 knapsack.py | 2,045 | 3.5 | 4 | # Solution 1 - Recursive
def knapsack(profits, weights, capacity, n):
# base case
if n == 0 or capacity == 0:
return 0
if weights[n-1] <= capacity:
return max(
profits[n-1] + knapsack(profits, weights,
capacity-weights[n-1], n-1),
knapsack(profits, weights, capacity, n-1)
)
else:
knapsack(profits, weights, capacity, n-1)
print(knapsack([1, 6, 10, ], [1, 2, 3], 5, 3))
# Solution 2 - DP
def solve_knapsack(profits, weights, capacity):
n = len(profits)
dp = [[-1 for x in range(0, capacity+1)] for y in range(0, n)]
return knapsack_recursive_dp(profits, weights, capacity, n, dp)
def knapsack_recursive_dp(profits, weights, capacity, n, dp):
if n == 0 or capacity == 0:
return 0
if dp[n-1][capacity] != -1:
return dp[n-1][capacity]
if weights[n-1] <= capacity:
dp[n-1][capacity] = max(
profits[n-1] +
knapsack_recursive_dp(
profits, weights, capacity-weights[n-1], n-1, dp),
knapsack_recursive_dp(profits, weights, capacity, n-1, dp)
)
return dp[n-1][capacity]
else:
dp[n-1][capacity] = knapsack_recursive_dp(
profits, weights, capacity, n-1, dp)
return dp[n-1][capacity]
print(solve_knapsack([1, 6, 10], [1, 2, 3], 5))
# Solution 3 - DP Bottom up approach
def knapsack_bottom_up(profits, weights, capacity):
# create matrix
dp = [[0 if x == 0 or y == 0 else -
1 for x in range(0, capacity+1)] for y in range(0, len(profits)+1)]
for i in range(1, len(profits)+1):
for j in range(1, capacity+1):
if weights[i-1] <= j:
dp[i][j] = max(
profits[i-1] + dp[i-1][j-weights[i-1]],
dp[i-1][j]
)
else:
dp[i][j] = dp[i-1][j]
return dp[len(profits)][capacity]
print(knapsack_bottom_up([20, 30, 10, 50], [1, 3, 4, 6], 10))
|
ab90f228d7ce78e24b1af10e31d8857a2ea8db63 | prashantchanne12/Leetcode | /intersection of two linked list.py | 2,693 | 3.9375 | 4 | '''
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
It is guaranteed that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
len_a = 0
len_b = 0
temp_a = headA
temp_b = headB
while temp_a is not None:
len_a += 1
temp_a = temp_a.next
while temp_b is not None:
len_b += 1
temp_b = temp_b.next
diff = abs(len_a - len_b)
if len_a > len_b:
while diff:
headA = headA.next
diff -= 1
else:
while diff:
headB = headB.next
diff -= 1
while headA is not None and headB is not None:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None
|
3198e640494c234e8603277b2d4f33922f3528c3 | prashantchanne12/Leetcode | /conflicting appointments.py | 1,061 | 4.03125 | 4 | '''
Given an array of intervals representing ‘N’ appointments, find out if a person can attend all the appointments.
Example 1:
Appointments: [[1,4], [2,5], [7,9]]
Output: false
Explanation: Since [1,4] and [2,5] overlap, a person cannot attend both of these appointments.
Example 2:
Appointments: [[6,7], [2,4], [8,12]]
Output: true
Explanation: None of the appointments overlap, therefore a person can attend all of them.
Example 3:
Appointments: [[4,5], [2,3], [3,6]]
Output: false
Explanation: Since [4,5] and [3,6] overlap, a person cannot attend both of these appointments.
'''
def can_attend_all_appointments(intervals):
# sort the intervals
intervals.sort()
start = intervals[0][0]
end = intervals[0][1]
for i in range(1, len(intervals)):
interval = intervals[i]
if end > interval[0]:
return False
else:
# update start and end
start = interval[0]
end = interval[1]
return True
print(can_attend_all_appointments([[6, 7], [2, 4], [8, 12]]))
|
9b2706672b9ab33617c4f91645e99eb990ec9e25 | DmitryKop/firststeps | /Python/TicTacToe.py | 5,554 | 4.09375 | 4 | import random
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player_1_name = ''
player_2_name = ''
def get_names():
global player_1_name
player_1_name = input("Player 1, enter your name: ")
global player_2_name
player_2_name = input("Player 2, now please enter your name: ")
def get_markers():
player_1_symbol = ''
global markers
while player_1_symbol != 'X' and player_1_symbol != 'O':
player_1_symbol = input(player_1_name + ", what would you prefer 'X' or 'O'?: ").upper()
if player_1_symbol != 'X' and player_1_symbol != 'O':
print("You must choose only between theese two!")
print("OK, " + player_1_name + ", your symbol is " + player_1_symbol)
symbols = ('X', 'O')
for x in symbols:
if player_1_symbol == symbols[0]:
player_2_symbol = symbols[1]
else:
player_2_symbol = symbols[0]
print("Got it, " + player_2_name + ", your symbol is " + player_2_symbol)
if player_1_symbol == 'X':
markers = ('X', 'O')
else:
markers = ('O', 'X')
def display_board(board):
print('\n'*100)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
def whos_first():
if random.randint(0, 1) == 0:
return player_1_name
else:
return player_2_name
def place_marker(player, place, board):
while place not in range(1,10):
place = int(input("Enter the correct number of cell (from 1 to 9): "))
while board[place] != ' ':
place = int(input("This cell is not empty! Choose another one: "))
player_1_marker, player_2_marker = markers
if player == player_1_name:
board[place] = player_1_marker
return board
else:
board[place] = player_2_marker
return board
def check_spaces(board):
if ' ' in board[1:]:
return True
else:
return False
def winner_check(board, markers):
player_1_marker, player_2_marker = markers
if board[1] == board[2] == board[3] != ' ':
if board[1] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[4] == board[5] == board[6] != ' ':
if board[4] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[7] == board[8] == board[9] != ' ':
if board[7] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[1] == board[4] == board[7] != ' ':
if board[1] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[2] == board[5] == board[8] != ' ':
if board[2] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[3] == board[6] == board[9] != ' ':
if board[3] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[1] == board[5] == board[9] != ' ':
if board[1] == player_1_marker:
return player_1_name
else:
return player_2_name
elif board[3] == board[5] == board[7] != ' ':
if board[3] == player_1_marker:
return player_1_name
else:
return player_2_name
else:
return False
def start_game(board):
firstplayer = whos_first()
print(firstplayer + " goes first!")
display_board(board)
place = int(input(firstplayer + ", where do you want to place you mark?\n(Choose the number of a cell, from 1 to 9): "))
place_marker(firstplayer,place,board)
free_cells = check_spaces(board)
winner = winner_check(board,markers)
while not winner and free_cells:
display_board(board)
p1marks = board.count(markers[0])
p2marks = board.count(markers[1])
if p1marks > p2marks:
player = player_2_name
place = int(input(player + ", now your turn. Where do you want to place you mark?\n(Choose the number of a cell, from 1 to 9): "))
place_marker(player, place, board)
elif p1marks < p2marks:
player = player_1_name
place = int(input(player + ", now your turn. Where do you want to place you mark?\n(Choose the number of a cell, from 1 to 9): "))
place_marker(player, place, board)
else:
if firstplayer == player_1_name:
player = player_1_name
else:
player = player_2_name
place = int(input(player + ", now your turn. Where do you want to place you mark?\n(Choose the number of a cell, from 1 to 9): "))
place_marker(player, place, board)
free_cells = check_spaces(board)
winner = winner_check(board, markers)
if winner:
display_board(board)
print("Congrats, " + winner + ", you did it!")
else:
print("It's a draw!")
rematch = input("Do you want a rematch? [Y/N]: ").upper()[0]
if rematch == 'Y':
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
start_game(board)
else:
print("Thanks for playing the game!")
get_names()
get_markers()
start_game(board) |
bf5dfe5e82866019001867bb7136e266b549593a | Sonjongkook/Group4-Emergency-Vehicle-Dispatching-System-Project- | /project/vertex.py | 1,006 | 3.859375 | 4 | import sys
class Vertex:
# initialize member variables of the vertex
def __init__(self, node_value):
self.id = node_value
self.neighbor = {}
self.distance = float('inf')
self.visited = False
self.previous = None # predecessor which is essential for graph
def add_neighbor(self, adjacent, weight=0):
self.neighbor[adjacent] = weight
def get_id(self):
return self.id
def get_weight(self, adjacent):
return self.neighbor[adjacent]
def set_distance(self, d):
self.distance = d
def get_distance(self):
return self.distance
def set_visited(self):
self.visited = True
def set_previous(self, current): # predecessor is important to backtrackinng shortest route
self.previous = current
def get_previous(self):
return self.previous
def __lt__(self, other):
return self.id < other.id # to implement heapify
|
04774b08d79956c826dd25ece5d12f3aea56922b | sgpl/project_euler | /1_solution.py | 586 | 4.28125 | 4 | #!/usr/bin/python 2.7
# If we list all the natural numbers
# below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5
# below 1000.
counter = 0
terminating_condition = 1000
sum_of_multiples = 0
while counter < terminating_condition:
if counter % 3 == 0 and counter % 5 == 0:
sum_of_multiples += counter
elif counter % 3 == 0:
sum_of_multiples += counter
elif counter % 5 == 0:
sum_of_multiples += counter
else:
sum_of_multiples += 0
counter += 1
print sum_of_multiples
|
6f5846ece2ce5539be0a08087f7d369e2b9ada35 | alphaonezero/python | /while.py | 133 | 4.0625 | 4 | L=[]
while len(L)<3:
new_name = input("Please add a new name: ").strip()
L.append(new_name)
print("The list is now full.")
|
dfb36aeb80967cd2386adaba35b7c98ca8a47a21 | theForgerass/3DPointCloud | /Commonstruct/Point2D.py | 2,126 | 3.96875 | 4 | """
二维点
"""
import math
class Point2D:
__slots__ = ('_x', '_y')
def __init__(self, x=0.0, y=0.0):
"""
初始化点坐标
:param x: X坐标
:param y: Y坐标
"""
self._x = x
self._y = y
def __add__(self, other):
if isinstance(other, Point2D):
return Point2D(self._x + other.x, self._y + other.y)
elif isinstance(other, int):
return Point2D(self._x + other, self._y + other)
else:
return None
def __sub__(self, other):
if isinstance(other, Point2D):
return Point2D(self._x - other.x, self._y - other.y)
elif isinstance(other, int):
return Point2D(self._x - other, self._y - other)
else:
return None
def __truediv__(self, other):
if isinstance(other, int) and other != 0:
return Point2D(self._x / other, self._y / other)
else:
return None
def __mul__(self, other):
if isinstance(other, int):
return Point2D(self._x * other, self._y * other)
else:
return None
def __eq__(self, other):
return isinstance(other, Point2D) and self._x == other.x and self._y == other.y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
@x.setter
def x(self, x):
self._x = x
@y.setter
def y(self, y):
self._y = y
@staticmethod
def norm(pt):
"""
计算点pt到原点的距离
:param pt: 输入的点
:return: 点到原点的距离
"""
return math.sqrt(pt.x * pt.x + pt.y * pt.y + pt.z * pt.z)
@staticmethod
def toPoint(other):
"""
输入list类型的实例,转化为Point3D类型的实例
:param other: 1*3 list实例
:return: Point3D类型的实例
"""
if len(other) == 2:
return Point2D(other[1], other[2])
else:
return None
def __str__(self):
return '[%.4f, %.4f]' % (self._x, self._y)
|
56c8db8750b288b5483a7bc339e865d589a1d503 | walterschell/classcode | /dict_demo.py | 207 | 3.96875 | 4 | def main():
ages = {}
ages["Alice"] = 29
ages["Bob"] = 21
ages["Eve"] = 30
for name in ages.keys():
print '%s: %s' % (name, ages[name])
if __name__ == '__main__':
main()
|
fdc04a8ea2ec6264781dd8fa7a91dc2bab4f46f7 | iamsabhoho/PythonProgramming | /Q1-3/MasteringFunctions/Accumulation.py | 233 | 3.90625 | 4 | #Write the accumulated sum of a list.
#For example, if the input is [1, 2, 3, 4, 5],
#then the output should be [1, 3, 6, 10, 15].
p = 1
list = [1,2,3,4,5]
print(list[0])
for i in range(len(list)-1):
p += list[i]+1
print(p)
|
e3ca39e8ccdee4d39038a95701ce541f85f19ff8 | iamsabhoho/PythonProgramming | /Q1-3/myLib.py | 2,323 | 4.09375 | 4 | def readText(filepath):
"""
read and return a text in a file
:param filepath:
:return:
"""
f = open(filepath, 'r')
returnText = f.read()
f.close()
return returnText.split()
def findNextWord(word, text):
"""
find the words that appears in the text file
:param word: the keywords
:param text: the text file
:return: a list of nextwords
"""
nextWord, frequency = [], []
for idx, wrd in enumerate(text):
if wrd == word:
#finding the next word
nextWrd = text[idx+1]
if nextWrd in nextWord:
#counting the f
frequency[nextWord.index(nextWrd)]+=1
else:
#if not yet on the list, add the word to the list,
#f starts at 1
nextWord.append(nextWrd)
frequency.append(1)
print(nextWord)
print(frequency)
#print('next word is {}'.format(text[idx+1]))
return nextWord, frequency
def probOcurrence(count):
nEvents = sum(count)
prob = [1.0*x/nEvents for x in count]
density = []
total = 0
for p in prob:
total += p
density.append(total)
return density
'''
def randomWord(words, density):
generate the next word
:param words:
:param density:
:return:
import random as rn
n = rn.random()
idx = 0
while n > density[idx]:
idx += 1
return words[idx]
'''
def randomCmate(inputlist = ['Sabrina','Cici','Stephanie','Daniel','Darren']):
'''
select a classmate name at random
return classmate name
'''
import random as rn
NumStu = len(inputlist) - 1
x = rn.randint(0, NumStu)
name = inputlist[x]
print(name)
return name
def capitalize(words = ['Bob', 'JOHN','alice','bob','ALICE','J','Bob']):
name = [x[0].upper() + x[1:].lower() for x in words if len(x) > 2]
print(name)
return name
def combinelists(colors = ['red','yellow','blue'], clothes = ['hat','shirt', 'pants']):
x = [a + ' ' + b for a in colors for b in clothes]
print(x)
return x
def takeOutVowels(sentence = 'Your mother was a hamster', vowels = ['aeiou']):
x = [l for l in sentence if l not in 'aeiou']
print(x)
s = ''
for l in x:
s+= l
print(s)
return s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.