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 |
|---|---|---|---|---|---|---|
b29571ed3f997a0b2dfc5fcceefb41050f009feb | bovard/advent_of_code_2016 | /01/part_one.py | 599 | 3.765625 | 4 | from maps import Direction, Location
with open('input.txt') as f:
instructions = f.read().strip().split(', ')
# start at 0,0 facing North
start = Location(0, 0)
direction = Direction.NORTH
current = start
for inst in instructions:
lr = inst[0]
n = int(inst[1:])
# turn left or right
if lr == 'L':
direction = Direction.rotate_left(direction)
elif lr == 'R':
direction = Direction.rotate_right(direction)
# walk n units forward
current = current.add(direction, n)
# report the distance back to the beginning
print start.distance_to_loc(current)
|
a1c1248449fc07ddce4ef66ab33cdc9f42dd8653 | mcttn1/python | /parameter.py | 10,310 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 16:52:31 2018
@author: huashuo
"""
#Python的函数定义,除了正常定义的必选参数外,还可以使用默认参数、
#可变参数和关键字参数,使得函数定义出来的接口,不但能处理复杂的参数,还可以简化调用者的代码。
# #位置参数
# =============================================================================
# #我们先写一个计算x2的函数
# def power(x):
# return x*x
# #参数x就是一个位置参数,当我们调用power函数时,必须传入有且仅有的一个参数x
# print(power(5))
#
# #计算x4、x5……,可以把power(x)修改为power(x, n),用来计算xn
# def power(x,n=2):#默认参数就排上用场了。由于我们经常计算x2,
# #所以,完全可以把第二个参数n的默认值设定为2
# s=1
# while n>0:
# s=s*x
# n=n-1
# return s
# #可以计算任意数的n次方
#
# print(power(2,10))
# #修改后的power(x, n)函数有两个参数:x和n,这两个参数都是位置参数,
# #调用函数时,传入的两个值按照位置顺序依次赋给参数x和n
#
# print(power(5))#TypeError: power() missing 1 required positional argument: 'n'
# #默认计算x的2次方,默认参数可以简化函数的调用
# =============================================================================
# #默认参数
# =============================================================================
# #使用默认参数有什么好处?最大的好处是能降低调用函数的难度。
# #当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。
# #我们写个一年级小学生注册的函数,需要传入name和gender两个参数
# def enroll(name,gender):
# print('name=',name)
# print('gender=',gender)
# #调用enroll函数
# enroll('M','F')
#
# #如果要继续传入年龄、城市等信息怎么办?这样会使得调用函数的复杂度大大增加。
# #我们可以把年龄和城市设为默认参数:
# def enroll(name,gender,age=7,city='SH'):
# print('name=',name)
# print('gender=',gender)
# print('age=',age)
# print('city=',city)
# enroll('M','F')
#
# #大多数学生注册时不需要提供年龄和城市,只提供必须的两个参数
# #只有与默认参数不符的学生才需要提供额外的信息:
# enroll('C','F',6)
# enroll('T','M',city='SZ')#没有输入age参数时,需要将city的参数名写出来
# =============================================================================
# =============================================================================
# def add_end(L=[]):
# L.append('END')
# return L
#
# print(add_end([1,2,3]))#正常调用时,结果似乎不错
# print(add_end(['x','y','z']))
# print(add_end())#当你使用默认参数调用时,一开始结果也是对的
# print(add_end())#但是,再次调用add_end()时,结果就不对了:
# print(add_end())#返回['END', 'END', 'END']
# =============================================================================
# =============================================================================
# #函数似乎每次都“记住了”上次添加了'END'后的list
# #定义默认参数要牢记一点:默认参数必须指向不变对象!
# #要修改上面的例子,我们可以用None这个不变对象来实现:
# def add_end(L=None):
# if L is None:
# L=[]
# L.append('END')
# return L
# print(add_end())#返回['END']
# print(add_end())#无论调用多少次,都不会有问题:返回['END']
# =============================================================================
# #可变参数
# =============================================================================
# #给定一组数字a,b,c……,请计算a2 + b2 + c2 + ……
# #要定义出这个函数,我们必须确定输入的参数。由于参数个数不确定,
# #我们首先想到可以把a,b,c……作为一个list或tuple传进来,这样,函数可以定义如下:
# def calc(numbers):
# sum=0
# for n in numbers:
# sum=sum+n*n
# return sum
#
# print(calc([1,2,3]))
# print(calc((1,3,5,7)))
# #如果利用可变参数,调用函数的方式可以简化成这样:
# #把函数的参数改为可变参数:
# def calc(*numbers):
# sum=0
# for n in numbers:
# sum=sum+n*n
# return sum
# #在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。
# #但是,调用该函数时,可以传入任意个参数,包括0个参数:
# print(calc(1,2,3))
# print(calc(1,3,5,7))
# print(calc())
# #如果已经有一个list或者tuple,要调用一个可变参数怎么办?可以这样做:
# nums=[1,2,3]
# print(calc(nums[0],nums[1],nums[2]))
#
# #这种写法当然是可行的,问题是太繁琐,
# #所以Python允许你在list或tuple前面加一个*号,
# #把list或tuple的元素变成可变参数传进去:
# print(calc(*nums))
#
# =============================================================================
# #关键字参数
# =============================================================================
# #可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。
# #而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。请看示例:
#
# def person(name,age,**kw):
# print('name:',name,'age:',age,'other:',kw)
#
# print(person('M',30))
# print(person('C',25,city='SH'))
# print(person('T',23,gender='F',job='Engineer'))
#
# #和可变参数类似,也可以先组装出一个dict,然后,把该dict转换为关键字参数传进去:
# extra={'city':'Beijing','job':'Engineer'}
#
# print(person('J',24,city=extra['city'],job=extra['job']))
#
# #上面复杂的调用可以用简化的写法:
# print(person('J',24,**extra))
# #注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra
# =============================================================================
# #命名关键字参数
# =============================================================================
# #对于关键字参数,函数的调用者可以传入任意不受限制的关键字参数。
# #至于到底传入了哪些,就需要在函数内部通过kw检查。
# #仍以person()函数为例,我们希望检查是否有city和job参数:
#
# def person(name,age,**kw):
# if 'city' in kw:
# #有city参数
# pass
# if 'job' in kw:
# #有job参数
# pass
# print('name:',name,'age:',age,'other:',kw)
#
# #但是调用者仍可以传入不受限制的关键字参数:
# print(person('P',33,city='Beijing',zipcode=123456))
#
# #如果要限制关键字参数的名字,就可以用命名关键字参数,
# #例如,只接收city和job作为关键字参数。这种方式定义的函数如下:
# def person(name,age,*,city,job):
# print(name,age,city,job)
# #和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,
# #*后面的参数被视为命名关键字参数
#
# print(person('TT',18,city='SH',job='IT'))
#
# #如果函数定义中已经有了一个可变参数,
# #后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
# def person(name,age,*args,city,job):
# print(name,age,city,job)
# #命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错
# #person('Jack',24,'Beijing','IT')#TypeError: person() missing 2 required keyword-only arguments: 'city' and 'job'
#
# #命名关键字参数可以有缺省值,从而简化调用:
# def person(name,age,*,city='Beijing',job):
# print(name,age,city,job)
#
# print(person('JACK',24,job='IT'))
#
# #使用命名关键字参数时,要特别注意,如果没有可变参数,就必须加一个*作为特殊分隔符。
# #如果缺少*,Python解释器将无法识别位置参数和命名关键字参数:
#
# def person(name,age,city,job):
# #缺少*,city和job被视为位置参数
# pass
# =============================================================================
# #参数组合
# =============================================================================
# #在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。
# #但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
#
# def f1(a,b,c=0,*args,**kw):
# print('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw)
#
# def f2(a,b,c=0,*,d,**kw):
# print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
#
# print(f1(1,2))
# print(f1(1,2,c=3))
# print(f1(1,2,3,'a','b'))
# print(f1(1,2,3,'a','b',x=99))
# print(f1(1,2,3,'a','b',x=99,y=3))
# print(f2(1,2,d=99,ext=None))
#
# #最神奇的是通过一个tuple和dict,你也可以调用上述函数:
# args=(1,2,3,4)
# kw={'d':99,'x':'#'}
# print(f1(*args,**kw))
#
# args=(1,2,3)
# kw={'d':88,'x':'#'}
# print(f2(*args,**kw))
#对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。
# =============================================================================
#练习
#以下函数允许计算两个数的乘积,请稍加改造,
#变成可接收一个或多个数并计算乘积:
def product(x, y):
return x * y
def product(*numbers):
multiply=1
for n in numbers:
multiply=multiply*n
return multiply
nums=[3,4,5,6,7]
print(product(*nums))
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
|
1eb516ec2ab4265e7fcd8cabf42dc7e3b63acd6c | hub851/HIT137-Group-11-Assignment-2 | /210212_PY_HIT137_Assignement 2 Part 1-Group 11.py | 1,468 | 3.609375 | 4 | from turtle import *
a = int(input("How many flowers would you like?: "))
ht()
pu()
goto(((a/2)*-400),0)
screensize((400*a)+400,600)
bgcolor("skyblue")
speed(50)
pd()
b = 1
for i in range (a):
color("green","green")
begin_fill()
for i in range(1):
forward(10)
right(90)
forward(250)
left(135)
circle(-80,90)
right (90)
circle (-80,90)
left(135)
forward(250)
right(90)
forward(20)
right(90)
forward(150)
left(135)
circle(-80,90)
right (90)
circle (-80,90)
left(135)
forward(350)
right(90)
forward(10)
end_fill()
if b == 1:
c = "red"
elif b == 2:
c = "orange"
elif b == 3:
c = "yellow"
elif b == 4:
c = "green"
elif b == 5:
c = "blue"
elif b == 6:
c = "purple"
elif b == 7:
c = "indigo"
else:
b = 1
c = "red"
color(c, c)
begin_fill()
for i in range(6):
circle(100)
left(60)
end_fill()
color("white","white")
begin_fill()
b = b + 1
for i in range(1):
pu()
setheading(270)
forward(50)
pd()
setheading(0)
circle(50)
setheading(90)
pu()
forward(50)
setheading(0)
pd()
end_fill()
setheading(0)
pu()
forward(410)
pd()
exitonclick()
|
22d1c4d381fbbf7cbf52568137b1b079f41e1e3c | RicardoBaniski/Python | /Opet/4_Periodo/Scripts_CEV/Mundo_01/Aula009.py | 1,449 | 4.78125 | 5 | print('''Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender são o Fatiamento de String, Análise com len(), count(), find(), transformações com replace(), upper(), lower(), capitalize(), title(), strip(), junção com join().
''')
frase = 'Curso em Video Python'
print(frase[3]) # indice 3
print(frase[3:13]) # indice 3 ao 13
print(frase[:13]) # até o indice 13
print(frase[1:15]) # indice 1 ao 15
print(frase[1:15:2]) # indice 1 ao 15, com intervalo de 2
print(frase[1::2]) # indice 1 até o fim com intervalo de 2
print(frase[::2]) # do inicio ao fim com intervalo
print(frase.count('o')) # conta "o" minusculo
print(frase.count('O')) # conta "O" maiusculo
print(frase.upper().count('O')) # transforma em maiusculo e depois conta "O"
print(len(frase)) # tamanho do vetor
print(len(frase.strip())) # tamanho sem espaços no inicio e fim
print(frase.replace('Python', 'Android')) # substitui palavras para impressão
# frase = frase.replace('Python', 'Android') // substitui palavra na variável
print('Curso' in frase) # Se palavra está contida
print(frase.find('Video')) # encontre a posição da palavra exata
print(frase.lower().find('video')) # transforma o conteudo do vetor em minusculo para depois encontrar a palavra
print(frase.split()) # divide por espaçamento
dividido = frase.split() # armazena em lista
print(dividido[0]) #imprime um indice da lista |
4b9fbf78ffbe61cd1eee106b8929079f972ada80 | RicardoBaniski/Python | /Opet/4_Periodo/Scripts_CEV/Mundo_01/Desafio012.py | 170 | 3.53125 | 4 | preco = int(input('Preço: '))
d = 5
desconto = preco * (d/100)
total = preco - desconto
print('Desconto de {}'.format(desconto))
print('O total é {}'.format(total))
|
477b8432b498cca5243fd4555e02f2bb0d0e90d7 | RicardoBaniski/Python | /Opet/4_Periodo/Scripts_CEV/Mundo_02/Desafio041.py | 304 | 3.953125 | 4 | from datetime import date
hoje = date.today()
nascimento = int(input('Data de nascimento: '))
idade = hoje.year-nascimento
if idade <= 9:
print('MIRIM')
elif idade <= 14:
print('INFANTIL')
elif idade <= 19:
print('JUNIOR')
elif idade <= 20:
print('SÊNIOR')
else:
print('MASTER')
|
c2f65bfedca5938fd832d18e2c924e789d146da1 | RicardoBaniski/Python | /Opet/5_Periodo/CifraDeCesar.py | 1,290 | 3.75 | 4 | # RICARDO BANISKI - 1201800164
alfabeto = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz '
def criptografar(alfabeto, texto, chave):
texto_criptografado = ''
for caractere in texto:
if caractere in alfabeto:
index = alfabeto.find(caractere) + chave
if index >= len(alfabeto):
index -= len(alfabeto)
texto_criptografado += alfabeto[index]
return texto_criptografado
def descriptografar(alfabeto, texto_criptogradado, chave):
texto = ''
for caractere in texto_criptogradado:
if caractere in alfabeto:
index = alfabeto.find(caractere) - chave
texto += alfabeto[index]
return texto
def main():
print('')
print('Selecione uma opção:')
print('1 - Codificar')
print('2 - Decodificar')
opc()
def opc():
chave = int(input('\nInsira a chave: '))
mensagem = input('Insira a mensagem: ')
x = int(input('\nOpção: '))
if(x == 1):
c = criptografar(alfabeto, mensagem, chave)
print('Texto Codificado: "', c, '"')
elif (x == 2):
dc = descriptografar(alfabeto, mensagem, chave)
print('Texto Decodificado: "', dc, '"')
else:
print('\nOpção inválida')
main()
if __name__ == "__main__":
main()
|
0bd4e81ad9d204b1c6d546b5095fbce1e2090d09 | RicardoBaniski/Python | /Opet/4_Periodo/Scripts_CEV/Mundo_01/Desafio016.py | 121 | 3.828125 | 4 | import math
n = float(input('Digite um numero Real: '))
print('Parte inteira do numero Real {}'.format(math.trunc(n)))
|
098136c8b597b81e8cc2c769e837f54d1e0046c4 | RicardoBaniski/Python | /Opet/4_Periodo/Scripts_CEV/Mundo_01/Desafio029.py | 233 | 3.765625 | 4 | velocidade = int(input('Qual a velocidade do carro: '))
if velocidade > 80:
print('Você foi multado em R${:.2f} por excesso de velocidade'.format((velocidade-80)*7))
else:
print('Você esta dentro do limite de velocidade')
|
85d84d9c937233fb243c2a67a482c84d778bb60b | nicolas-huber/reddit-dailyprogrammer | /unusualBases.py | 1,734 | 4.3125 | 4 | # Decimal to "Base Fib" - "Base Fib" to Decimal Converter
# challenge url: "https://www.reddit.com/r/dailyprogrammer/comments/5196fi/20160905_challenge_282_easy_unusual_bases/"
# Base Fib: use (1) or don't use (0) a Fibonacci Number to create any positive integer
# example:
# 13 8 5 3 2 1 1
# 1 0 0 0 1 1 0 = 16 in "Base Fib"
# collect and save user input
input_line = raw_input("Enter base (F or 10) and number to be converted: ")
input_list = input_line.split(" ")
base = input_list[0]
number = input_list[1]
# translate from base fib to decimal
if base == "F":
# Create sufficient amount of Fibonacci Numbers
a, b = 0, 1
fib_numbers = []
for i in range(len(number)):
a, b = b, a+b
fib_numbers.append(a)
fib_numbers.sort(reverse=True)
result = []
number_digit_list = [int(i )for i in str(number)]
for item1, item2 in zip(number_digit_list, fib_numbers):
if item1 == 1:
result.append(item2)
else:
pass
print(sum(result))
# translate from decimal to base fib
elif base == "10":
# Create sufficient amount of Fibonacci Numbers
a, b = 0, 1
fib_num_list = []
while True:
a, b = b, a+b
fib_num_list.append(a)
if fib_num_list[-1] >= int(number):
fib_num_list.sort(reverse=True)
break
fib_result = []
for entry in fib_num_list:
if int(number)/entry == 1:
fib_result.append(int(number)/entry)
number = int(number)%entry
else:
fib_result.append(0)
# remove first item of fib_results since excess 0 is added (?)
print(" ".join(str(x) for x in fib_result[1:]))
|
9a803033d24f76a0d9e71afa22238385872de5c7 | ZacharyAngelucci/SeniorProject2019TBA | /datagen/general.py | 266 | 3.828125 | 4 | import random
def yesno_question(chance=.5):
""" Returns a yes or a no
Args:
chance (float): Chance for yes result [0->0.999...]
Defaults to 0.5
"""
if random.random() <= chance:
return "Yes"
else:
return "No" |
bc7608a79c1dcecb188038ccd921cd731a62e555 | Seraffina-93/Hacking-with-Python | /Password Cracking/cryptforce.py | 789 | 3.828125 | 4 | #!/usr/bin/python
import crypt
from termcolor import colored
def crackPass(cryptWord):
salt = cryptWord[0:2]
dictionary = open("dictionary.txt", 'r')
for word in dictionary.readlines():
word = word.strip('\n')
cryptPass = crypt.crypt(word, salt)
if (cryptWord == cryptPass):
print (colored("[+] Found password: " + word, 'green'))
return
else:
print (colored("[-] Failed with: " + word, 'red'))
print ("[!!] Password not in list!")
return
def main():
passFile = open('pass.txt', 'r')
for line in passFile.readlines():
if ':' in line:
user = line.split(':')[0]
cryptWord = line.split(':')[1].strip(' ').strip('\n')
print ("[+] Cracking password for: " + user)
if crackPass(ryptWord):
pass
else:
print ("[-] Password not found!")
main()
|
dc7846f11f5728a9ab5aa3421fe3c3b83c0b2b43 | czqzju/10_Days_Of_Statistics | /day5/Normal_Distribution_II.py | 481 | 3.546875 | 4 | #https://www.hackerrank.com/challenges/s10-normal-distribution-2/problem
import math
def normal_distribution(x, u, stdd):
return 0.5 + 0.5 * math.erf((x - u) / (stdd * 2 ** 0.5))
if __name__ == "__main__":
u = 70
stdd = 10
res1 = 1 - normal_distribution(80, u, stdd)
res2 = 1 - normal_distribution(60, u, stdd)
res3 = normal_distribution(60, u, stdd)
print("%.2f" % (res1 * 100))
print("%.2f" % (res2 * 100))
print("%.2f" % (res3 * 100))
|
503f39efb0709290c23d3d882563e91bfec6dd6c | LJ-Godfrey/Learn-to-code | /Encryption-101/01/loops.py | 783 | 3.96875 | 4 | # This code is a basic loop that runs something x number of times
inp = input("Enter something...: ")
#This is an infinite loop that breaks when the letter 'q' is entered
while inp != 'q':
print("You entered: {}".format(inp))
inp = input("Enter something else: ")
'''
i = 0
while i < 10:
print(i)
i = i + 1
for i in range(0, 10):
print(i)
'''
# This is a list of different strings.
list_a = ['a', 'b', 'c', 'joel', 'hi', '4', '5', '9']
#(len(list_a))
#for value in list_a[:list_a[5]]:
# print(value)
# This joins each element (string) in the list with a -.
print('-'.join(list_a))
# This is a dictionary
dict_a = {'a':'Hello, govna', 'b':'Wassup dude'}
asciii = {'a': ['A', 'a', '4']}
# This prints the string corresponding with 'b' key (Wassup dude)
print(dict_a['b']) |
b0b353eb1b6e426d235a046850ba74aea627d7a2 | LJ-Godfrey/Learn-to-code | /Encryption-101/encryption_project/encrypt.py | 1,178 | 4.25 | 4 | # This file contains various encryption methods, for use in an encryption / decryption program
def caesar(string):
res = str()
for letter in string:
if letter.lower() >= 'a' and letter.lower() <= 'm':
res += chr(ord(letter) + 13)
elif letter.lower() >= 'n' and letter.lower() <= 'z':
res += chr(ord(letter) - 13)
else:
res += letter
return res
def reverse(string):
res = str()
for letter in string:
res = letter + res
return res
def xor(string, key):
res = str()
for letter in string:
res += chr(ord(letter) ^ key)
return res
def rotate(string):
res = str()
if len(string) % 2 > 0:
mid = string[len(string)/2 + 1]
res = string[:mid] + string[mid+1:]
res = rot_sub(res)
res = res[:len(res)/2] + mid + res[len(res)/2:]
else:
res = rot_sub(string)
return res
# This function is used in the 'rotate' function
def rot_sub(string):
res = string
# pylint: disable=unused-variable
for letter in range(int(len(string)/2)):
last = len(res) - 1
res = res[last] + res[:last]
return res |
5ab248c3454e6d44f06b1f5ee5e34469c343e108 | mgh3326/GyeonggiBigDataSpecialist | /python_exam/0727/class_value_practice.py | 507 | 3.828125 | 4 | class Car:
color = '' # 인스턴스 변수
speed = 0 # 인스턴스 변수
count = 0 # 클래스 변수
def __init__(self):
self.speed = 0
Car.count += 1
myCar1, myCar2 = None, None
myCar1 = Car()
myCar1.speed = 30
myCar2 = Car()
myCar2.speed = 60
myCar2.count += 1
print('자동차1의 현재 속도는 %dkm, 생산된 자동차는 총 %d대 ' % (myCar1.speed, Car.count))
print('자동차1의 현재 속도는 %dkm, 생산된 자동차는 총 %d대' % (myCar2.speed, Car.count))
|
0df23278174bc73727e05e9e946754be4204bae4 | mgh3326/GyeonggiBigDataSpecialist | /python_exam/0726/factorail_practice.py | 163 | 3.84375 | 4 | num = input("정수를 입력하시오 : ")
result = 1
for i in range(int(num)):
result = result * (i + 1)
print(str(num) + "!은" + str(result) + "이다.")
|
49ed58e490d2080a68ec00b60a9d204f41fa10e0 | mgh3326/GyeonggiBigDataSpecialist | /python_exam/0801/tensorflow_exam01.py | 1,701 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 10:06:04 2017
@author: student
"""
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
matrix1 = tf.constant([[3., 3.]])
# 2x1 행렬을 만드는 constant op을 만들어봅시다.
# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[2.], [2.]])
# 'matrix1'과 'matrix2를 입력값으로 하는 Matmul op(역자 주: 행렬곱 op)을
# 만들어 봅시다.
# 이 op의 결과값인 'product'는 행렬곱의 결과를 의미합니다.
# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
# The returned value, 'product', represents the result of the matrix
# multiplication.
product = tf.matmul(matrix1, matrix2)
sess = tf.Session()
print(sess.run(product))
###########################
import tensorflow as tf
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
sess.run(train, {x: x_train, y: y_train})
# evaluate training accuracy
sess.run([W, b, loss], {x: x_train, y: y_train})
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))
|
1445db9e8404002912add906b8e5c6986bec42c8 | tt-n-walters/thebridge-python | /downloader.py | 493 | 3.578125 | 4 | import requests
print("Enter url to download:")
url = input(">> ")
print("Enter filename to save:")
filename = input(">> ")
# Download the url
print("Downloading...")
response = requests.get(url)
# Check the download succeeded
if not response.status_code == 200:
print("Download error.")
exit()
print("Download successful.")
# Open, write, close file
print("Saving to file...")
file = open(filename, "wb")
file.write(response.content)
file.close()
print("Saved successfully.")
|
5032238dacd0d2d0fc51d50833bcd13e49bc51cd | nikita26078/Python-exercises | /ex12/3.py | 569 | 3.828125 | 4 | def superset(a, b):
if a > b:
print(f'Объект {a} является чистым супермножеством')
elif a < b:
print(f'Объект {b} является чистым супермножеством')
elif a == b:
print('Множества равны')
else:
print('Супермножество не обнаружено')
set1 = {2, 9, 8, 5}
set2 = {8, 5}
set3 = {5, 8, 9, 2}
set4 = {32, 42, 55}
superset(set1, set2)
superset(set1, set3)
superset(set3, set2)
superset(set4, set2)
|
6c548753a2ecc08cc68c2e3d96411f62e2a067e8 | Frazl/algorithms-data-structures-python-notes | /Algorithms/Graphs/breadthfirstsearch.py | 3,350 | 3.625 | 4 | #!/usr/bin/env python3
from collections import defaultdict
# Breadth First Search
# Uses the graph from ../DataStructures/graph.py
# Uses the queue from ../DataStructures/queue.py
# Includes Breadth First Paths (Shortest Path from source vertice to another based on edges (not weights))
# Operations
# path_to --> Returns the path from the source to the given vertice if one exists else returns None
# has_path_to --> Returns whether or not a path exists from the source to the given vertice. (True / False)
# Performance
# Dependent on graph structure.
# Comparisons
# Useful for searching for shortest path in terms of edges in unweighted graphs.
class BreadthFirstSearch(object):
def __init__(self, graph, source):
self.marked = defaultdict(bool)
self.edge_to = defaultdict(list)
self.source = source
self.bfs(graph, source)
def bfs(self, graph, source):
q = Queue()
self.marked[source] = True
q.enqueue(source)
while not q.is_empty():
v = q.dequeue()
for edge in graph.adj[v]:
if not self.marked[edge]:
self.edge_to[edge] = v
self.marked[edge] = True
q.enqueue(edge)
def has_path_to(self, vertice):
return self.marked[vertice]
def path_to(self, v):
if not self.has_path_to(v):
return None
#path acts as a stack in this instance - could import stack data type
path = [v]
x = v
while not(x == self.source):
x = self.edge_to[x]
path.append(x)
return path[::-1]
# Dependent Data Structures
class Queue(object):
def __init__(self):
self.q = []
def enqueue(self, s):
self.q.append(s)
def dequeue(self):
item = self.q[0]
self.q = self.q[1:]
return item
def __len__(self):
return len(self.q)
def first(self):
return self.q[0]
def is_empty(self):
return len(self.q) == 0
class Graph(object):
def __init__(self, directed=False):
self.E = 0
self.V = 0
self.directed = directed
self.adj = defaultdict(list)
self.inverted_index = []
self.symbol_table = {}
def add_edge(self, v1, v2):
if v1 not in self.symbol_table.keys():
self.symbol_table[v1] = self.V
self.inverted_index.append(v1)
self.V += 1
if v2 not in self.symbol_table.keys():
self.symbol_table[v2] = self.V
self.inverted_index.append(v2)
self.V += 1
self.adj[self.symbol_table[v1]].append(self.symbol_table[v2])
self.E += 1
if not self.directed:
self.adj[self.symbol_table[v2]].append(self.symbol_table[v1])
self.E += 1
def __str__(self):
text = ""
for key in self.adj.keys():
text += str(key)+" : "+str(self.adj[key])+"\n"
return text
#Simple Test
def main():
q = Graph()
q.add_edge(1, 4)
q.add_edge(4, 5)
q.add_edge(5, 6)
q.add_edge(6, 2)
q.add_edge(2, 3)
q.add_edge(1, 2)
bfs = BreadthFirstSearch(q, 0)
print(str(bfs.path_to(3)))
if __name__ == '__main__':
main()
|
8fc56cb02c388fee48e9c777c33e2169f3535b77 | Frazl/algorithms-data-structures-python-notes | /DataStructures/graph.py | 2,370 | 3.75 | 4 | #!/usr/bin/env python3
from collections import defaultdict
# Simple Graph class. This uses the adjaceny lists variation of a graph.
# This graph uses a symbol table to limit memory usage. e.g. Instead of storing possibly large strings we record the value and link it to an number in a list.
# The alternative version of a graph is an adjacency matricies.
# This graph does not account for weights
# Operations
# add_edge - Add's an edge from one vertice to another, if directed is False then it adds an edge in the opposite direction too. i.e. Accounts for both directed and undirected graphs.
# Performance
# Space - E + V
# add edge - 1
# check whether w is adjacent to v - length of adjacent list of v (i.e. degree(v))
# iterate through vertices adjacent to v - length of adjacent list of (i.e. degree(v))
# Comparisons
# Similar to a matrices graph but with different performance.
# This uses less Space (memory) for sparse graphs compared to matrices graphs
# Higher performance requirements for checking adjacency given source and other vertice
# Higher performance requirements for iterating through vertices adjacent to a given vertice
class Graph(object):
def __init__(self, directed=False):
self.E = 0
self.V = 0
self.directed = directed
self.adj = defaultdict(list)
self.inverted_index = []
self.symbol_table = {}
def add_edge(self, v1, v2):
if v1 not in self.symbol_table.keys():
self.symbol_table[v1] = self.V
self.inverted_index.append(v1)
self.V += 1
if v2 not in self.symbol_table.keys():
self.symbol_table[v2] = self.V
self.inverted_index.append(v2)
self.V += 1
self.adj[self.symbol_table[v1]].append(self.symbol_table[v2])
self.E += 1
if not self.directed:
self.adj[self.symbol_table[v2]].append(self.symbol_table[v1])
self.E += 1
def __str__(self):
text = ""
for key in self.adj.keys():
text += str(key)+" : "+str(self.adj[key])+"\n"
return text
#Simple Test
def main():
q = Graph()
q.add_edge('Hello', 'World')
q.add_edge('World', 'Sean')
q.add_edge('End', 'Near')
q.add_edge('World', 'Peace')
print(q)
if __name__ == '__main__':
main()
|
dbc24899f01dd38cb9f8d7501b5434850fcb790f | gangqing/PythonExercise | /p01_阶乘.py | 613 | 3.5 | 4 |
def fac1(n):
result = 1
for i in range(2,n+1):
result *= i
return result
def fac2(n):
result = [1]
for i in range(2,n+1):
mul(result,i)
return toString(result)
def mul(result,a):
add =0
for position in range(len(result)):
aa = result[position] * a + add
result[position] = aa % 10
add = aa // 10
while add > 0:
result.append(add % 10)
add //= 10
def toString(result):
return "".join([str(e) for e in reversed(result)])
if __name__ == '__main__':
for n in range(1,100+1):
print(f"{n} != {fac2(n)}") |
7f430ce04b78b846d49a928b2a47994105fd3ba5 | gangqing/PythonExercise | /p04_囚犯.py | 796 | 3.5625 | 4 |
import random
def func(n):
list = [False] * n
light = False
while False in list:
countor = 0
a = random.randint(0,n-1)
print(f"{getName(a,countor)},{getWake(list[a])},{getLight(light)}")
prisoner = list[a]
if a == countor and light:
list[a] = True
light = False
print("操作:关灯")
elif (not prisoner) and (not light):
light = True
list[a] = True
print("操作:开灯")
def getName(a,countor):
return "计数人" if a == countor else f"{a}号囚犯"
def getWake(prisoner):
return "守过夜" if prisoner else "没守过夜"
def getLight(bool):
return "灯是开着的" if bool else "灯是关着的"
if __name__ == '__main__':
func(4) |
68e47a9d12af2369f9f84a721554083dd371f08e | Nickkun/day3 | /function.py | 279 | 3.875 | 4 |
def hello(name='Nick', age='10'):
print("Hello, " + name )
print(age + " years old")
# typing = input("What is your name? ")
# hello(typing)
tp1 = input("Your Name: ")
tp2 = input("How old are you? ")
# hello(name, age)
# hello(name)
# hello()
hello(age=tp2, name=tp1) |
a302ba4f56d279639dcb66cddd9a8c5191edf94c | Nickkun/day3 | /classCal.py | 953 | 3.890625 | 4 | class Cal():
def __init__(self, value):
self.value = value
def result(self):
print(self.value)
def add(self, input_value):
self.value += input_value
#self.value = self.value + input_value
def sub(self, input_value):
self.value -= input_value
def mul(self, input_value):
self.value *= input_value
def div(self, input_value):
try:
self.value /= input_value
except:
print("오류가 발생했습니다")
finally:ㄴ
print("나누기 실행완료")
class SafeCal(Cal):
def __init__(self, value):
self.value = value
def div(self, input_value):
if (input_value == 0):
self.value = 0
else:
self.value /= input_value
cal1 = Cal(0)
cal1.add(10)
cal1.result()
cal1.div(0)
cal1.result()
cal2 = SafeCal(0)
cal2.add(10)
cal2.result()
cal2.div(0)
cal2.result() |
99e7d3e826da13061bec7b5e9ed7de9add6e4a60 | hpcflow/pyinstaller-test | /hpcflow/parameters.py | 4,134 | 3.65625 | 4 | import copy
import numpy as np
class Parameter:
def __init__(self, name):
self.name = name
class Input(Parameter):
def __init__(self, name):
super().__init__(name)
def __repr__(self):
return f'<Input({self.name})>'
def __eq__(self, other):
"""Two Inputs are considered equal if their names are equal."""
if isinstance(other, Input):
if self.name == other.name:
return True
return False
class Output(Parameter):
def __init__(self, name):
super().__init__(name)
def __repr__(self):
return f'<Output({self.name})>'
class ParameterValue:
"""ParameterValue"""
def __init__(self, parameter, value):
self.parameter = parameter
self.value = value
class InputValue:
def __init__(self, input_parameter, value):
self.input_parameter = input_parameter
self.value = value
def __repr__(self):
return f'<InputValue(input={self.input_parameter.name}, value={self.value})>'
def hydrate(self):
# Maybe this method would be used to fully load the value from persistent?
# And also a dehydrate method to remove value from memory, and/or sync changes
# to persistent?
# Thinking in terms of importing parameter values. How would a parameter value be
# loaded into the new workflow (in-memory and persistent)?
pass
class InputValueSequence:
def __init__(self, parameter, values, base_value=None, address=None):
if base_value is not None:
if not isinstance(base_value, InputValue):
base_value = InputValue(parameter, base_value)
self.parameter = parameter
self.values = values
self.base_value = base_value
self.address = address
if (address is not None and base_value is None) or (
base_value is not None and address is None):
msg = (f'Either specify both of `base` and `address`, or neither.')
raise ValueError(msg)
self.check_address_exists(address)
def __repr__(self):
return f'<InputValueSequence(parameter={self.parameter}, base_value={self.base_value}, values={self.values}, address={self.address})>'
def check_address_exists(self, address):
"""Check a given nested dict/list "address" resolves to somewhere within
`self.base_value`."""
if address:
sub_val = self.base_value.value
for i in address:
try:
sub_val = sub_val[i]
except (IndexError, KeyError, TypeError):
msg = (f'Address {self.address} does not exist in the base '
f'value: {self.base_value.value}')
raise ValueError(msg)
def resolve_value(self, value):
if not self.base:
return copy.deepcopy(value)
base_value = copy.deepcopy(self.base_value.value)
sub_val = base_value
for i in self.address[:-1]:
sub_val = sub_val[i]
sub_val[self.address[-1]] = value
return base_value
@classmethod
def from_range(cls, parameter, start, stop, step=1, base_value=None, address=None):
if isinstance(step, int):
return cls(
parameter,
base_value=base_value,
values=list(np.arange(start, stop, step)),
address=address,
)
else:
# Use linspace for non-integer step, as recommended by Numpy:
return cls.from_linear_space(
parameter,
start,
stop,
base_value=base_value,
num=int((stop - start) / step),
address=address,
endpoint=False,
)
@classmethod
def from_linear_space(cls, parameter, start, stop, base_value=None, num=50, address=None, **kwargs):
values = list(np.linspace(start, stop, num=num, **kwargs))
return cls(parameter, values, base_value=base_value, address=address)
|
0dbf1a44855066d066ca5d036b4712ea90f97bc6 | Moby5/myleetcode | /python/155_Min_Stack.py | 3,989 | 3.6875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
https://leetcode.com/problems/min-stack/description/
[LeetCode]155. Min Stack
题目描述:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
题目大意:
设计一个栈,支持在常数时间内push,pop,top,和取最小值。
push(x) -- 元素x压入栈
pop() -- 弹出栈顶元素
top() -- 获取栈顶元素
getMin() -- 获取栈中的最小值
解题思路:
“双栈法”,栈stack存储当前的所有元素,minStack存储栈中的最小元素。
在操作元素栈stack的同时,维护最小值栈minStack。
对于push(x)操作:
stack.push( x )
minStack.push( min( minStack.top(), x ) )
1
2
注意事项(Tricks):
leetcode OJ对于该题目的内存限制比较严苛,直接使用双栈法容易出现Memory Limit Exceeded(MLE)
可以使用下面的优化解决此问题,minStack存储元组(minVal, count),分别记录当前的最小值和出现次数。
如果新增元素x与最小值栈顶的minVal相同,则只更新count。
"""
class MinStack:
# @param x, an integer
# @return an integer
def __init__(self):
self.stack = []
self.minStack = [] #最小值栈 (最小值,出现次数)
def push(self, x):
self.stack.append(x)
#如果 新增值x == 最小值栈顶的值
if len(self.minStack) and x == self.minStack[-1][0]:
#最小值栈顶元素次数+1
self.minStack[-1] = (x, self.minStack[-1][1] + 1)
#如果 最小值栈为空,或者新增值 < 最小值栈顶的值
elif len(self.minStack) == 0 or x < self.minStack[-1][0]:
#x入最小值栈
self.minStack.append((x, 1))
def pop(self):
#如果 栈顶值 == 最小值栈顶值
if self.top() == self.getMin():
#如果 最小值栈顶元素次数 > 1
if self.minStack[-1][1] > 1:
#最小值栈顶元素次数 - 1
self.minStack[-1] = (self.minStack[-1][0], self.minStack[-1][1] - 1)
else:
#最小值栈顶元素弹出
self.minStack.pop()
return self.stack.pop()
def top(self):
return self.stack[-1]
def getMin(self):
return self.minStack[-1][0]
class MinStack_v2(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if not self.min_stack or x < self.min_stack[-1][0]:
self.min_stack.append((x, 1))
elif x == self.min_stack[-1][0]:
self.min_stack[-1] = (x, self.min_stack[-1][1]+1)
def pop(self):
"""
:rtype: void
"""
if not self.stack:
return
if self.top() == self.getMin():
if self.min_stack[-1][1] == 1:
self.min_stack.pop()
else:
self.min_stack[-1] = (self.min_stack[-1][0], self.min_stack[-1][1]-1)
self.stack.pop()
def top(self):
"""
:rtype: int
"""
if self.stack:
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min_stack[-1][0]
minStack = MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
print minStack.getMin(); #--> Returns -3.
minStack.pop();
print minStack.top(); #--> Returns 0.
print minStack.getMin(); #--> Returns -2.
|
fd1f0836c9c89a66ff6a555f48577538e398f026 | Moby5/myleetcode | /python/671_Second_Minimum_Node_In_a_Binary_Tree.py | 2,525 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@File: 671_Second_Minimum_Node_In_a_Binary_Tree.py
@Desc:
@Author: Abby Mo
@Date Created: 2018-3-10
"""
"""
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node.
If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
题目大意:
给定一棵二叉树,树中的节点孩子个数为偶数(0个或者2个),若包含2个孩子节点,则值等于较小孩子的值。求树中第二小的节点。
解题思路:
遍历二叉树,记录比根节点大的所有节点中值最小的元素
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root or not root.left:
return -1
res = self.traverse(root)
res = sorted(res)
return res[1] if len(res) >= 2 else -1
def traverse(self, node):
if not node:
return {}
res = {node.val}
res.update(self.traverse(node.left))
res.update(self.traverse(node.right))
return res
def findSecondMinimumValue_ref(self, root): # http://bookshadow.com/weblog/2017/09/03/leetcode-second-minimum-node-in-a-binary-tree/
self.ans = 0x80000000
minVal = root.val
def traverse(root):
if not root: return
if self.ans > root.val > minVal:
self.ans = root.val
traverse(root.left)
traverse(root.right)
traverse(root)
return self.ans if self.ans != 0x80000000 else -1
if __name__ == '__main__':
solution = Solution()
n1, n2, n3 = TreeNode(5), TreeNode(8), TreeNode(5)
n1.left, n1.right = n2, n3
print solution.findSecondMinimumValue(n1)
|
91dc5dea5001604537abc3760d68c22add6737c8 | Moby5/myleetcode | /python/396_Rotate_Function.py | 2,452 | 3.90625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/09/11/leetcode-rotate-function/
396. Rotate Function
Given an array of integers A and let n to be its length.
Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].
Calculate the maximum value of F(0), F(1), ..., F(n-1).
Note:
n is guaranteed to be less than 105.
Example:
A = [4, 3, 2, 6]
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
题目大意:
给定一个整数数组A,其长度为n。
假设Bk是将数组A顺时针旋转k个位置得到的数组,我们定义一个“旋转函数”F如下所示:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].
计算F(0), F(1), ..., F(n-1)的最大值
注意:
n确保小于10^5
解题思路:
假设数组A的长度为4,其旋转函数F的系数向量如下所示:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
假设数组A的长度为5,其旋转函数F的系数向量如下所示:
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
用每一行系数与其上一行做差,差值恰好为sum(A) - size * A[size - x],其中x为行数
因此,通过一次遍历即可求出F(0), F(1), ..., F(n-1)的最大值。
"""
class Solution(object):
def maxRotateFunction_v0(self, A): #Time Limit Exceeded
"""
:type A: List[int]
:rtype: int
"""
if not A: return 0
F = []
for k in range(len(A)):
# print k, A[-k:] + A[:-k]
newA = A[-k:] + A[:-k]
fk = 0
for idx, x in enumerate(newA):
fk += idx * x
F.append(fk)
return max(F)
def maxRotateFunction(self, A): # ref
size = len(A)
sums = sum(A)
sumn = sum(idx * n for idx, n in enumerate(A))
ans = sumn
for x in range(size - 1, 0, -1):
sumn += sums - size * A[x]
ans = max(ans, sumn)
return ans
test = Solution()
A = [4, 3, 2, 6]
print test.maxRotateFunction(A) # 26
A = []
print test.maxRotateFunction(A) # 0
|
b76d2e373ea53f6ef7498888b0a80365bc48ec38 | Moby5/myleetcode | /python/532_K-diff_Pairs_in_an_Array.py | 2,592 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
LeetCode 532. K-diff Pairs in an Array
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].
题目大意:
给定一个整数数组nums,以及一个整数k,找出其中所有差恰好为k的不重复数对。
注意:
数对(i, j) 和 (j, i)算作同一个数对
数组长度不超过10,000
所有整数在范围[-1e7, 1e7]之间
解题思路:
字典(Map)
首先将nums中的数字放入字典c
遍历set(nums),记当前数字为n
若n + k在c中,则将结果+1
"""
import argparse
import collections
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
c = collections.Counter(nums)
thres = 0 if k else 1
return sum(c[n+k] > thres for n in c.keys())
# return sum(c[n+k] > 1 - bool(k) for n in c.keys())
def findPairs_2(self, nums, k): # Time Limit Exceeded
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
ans = set()
arr = sorted(nums)
# print 'arr:', arr
for i in range(len(arr) - 1):
if arr[i] not in ans and (arr[i] + k) in arr[i+1:]:
# print arr[i], arr[i+1:]
ans.add(arr[i])
return len(ans)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='find k-diff pairs in an array')
parser.add_argument('-nums', type=int, nargs='+')
parser.add_argument('-k', type=int)
args = parser.parse_args()
test = Solution()
print test.findPairs(args.nums, args.k)
|
94ad5d8a58263a018c0166cc84be1875cf7427b4 | Moby5/myleetcode | /python/111_Minimum_Depth_of_Binary_Tree.py | 1,526 | 4.03125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
[LeetCode] 111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
题目大意:
给定一棵二叉树,计算其最小深度。
最小深度是指从根节点出发到达最近的叶子节点所需要经过的节点个数。
解题思路:
DFS或者BFS均可,详见代码。
"""
import collections
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# DFS
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if left and right:
return min(left, right) + 1
return max(left, right) + 1
# BFS
def minDepth2(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = collections.deque([(root, 1)])
while queue:
node, step = queue.popleft()
if not node.left and not node.right:
return step
if node.left:
queue += (node.left, step + 1), # 注意逗号
if node.right:
queue += (node.right, step + 1),
|
01db338d18893fed2689056c5b9d20ae3f102b06 | Moby5/myleetcode | /python/225_Implement_Stack_using_Queues.py | 3,792 | 4.03125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2015/06/11/leetcode-implement-stack-using-queues/
225. Implement Stack using Queues
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
题目大意:
使用队列实现栈的下列操作:
push(x) -- 将元素x压入栈.
pop() -- 移除栈顶元素.
top() -- 获得栈顶元素.
empty() -- 返回栈是否为空.
注意:
你可以假设所有的操作都是有效的(例如,不会对空栈执行pop或者top操作)
取决于你使用的语言,queue可能没有被原生支持。你可以使用list或者deque(双端队列)模拟一个队列,只要保证你仅仅使用队列的标准操作即可——亦即只有如下操作是有效的:
push to back(加入队尾),pop from front(弹出队首),size(取队列大小)以及is empty(判断是否为空)
解题思路:
# push(x) -- 使用queue的push to back操作.
# pop() -- 将queue中除队尾外的所有元素pop from front然后push to back,最后执行一次pop from front
# top() -- 将queue中所有元素pop from front然后push to back,使用辅助变量top记录每次弹出的元素,返回top
# empty() -- 使用queue的is empty操作.
"""
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.queue.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
# for x in range(len(self.queue) - 1):
# self.queue.append(self.queue.pop(0))
# self.queue.pop(0)
return self.queue.pop()
def top(self):
"""
Get the top element.
:rtype: int
"""
# top = None
# for x in range(len(self.queue)):
# top = self.queue.pop(0)
# self.queue.append(top)
# return top
return self.queue[-1]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return len(self.queue) == 0
if __name__ == '__main__':
obj = MyStack()
for x in range(5):
obj.push(x)
param_2 = obj.pop()
param_3 = obj.top()
param_4 = obj.empty()
print param_2
print param_3
print param_4
"""
class Stack:
# initialize your data structure here.
def __init__(self):
self.queue = []
# @param x, an integer
# @return nothing
def push(self, x):
self.queue.append(x)
# @return nothing
def pop(self):
for x in range(len(self.queue) - 1):
self.queue.append(self.queue.pop(0))
self.queue.pop(0)
# @return an integer
def top(self):
top = None
for x in range(len(self.queue)):
top = self.queue.pop(0)
self.queue.append(top)
return top
# @return an boolean
def empty(self):
return self.queue == []
""" |
87549ca576db27ba40347d375273a4014275e55a | Moby5/myleetcode | /python/232_Implement_Queue_using_Stacks.py | 4,434 | 3.96875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2015/07/07/leetcode-implement-queue-using-stacks/
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
题目大意:
使用栈实现队列的下列操作:
push(x) -- 将元素x加至队列尾部
pop() -- 从队列头部移除元素
peek() -- 获取队头元素
empty() -- 返回队列是否为空
注意:
你只可以使用栈的标准操作——这意味着只有push to top(压栈), peek/pop from top(取栈顶/弹栈顶),以及empty(判断是否为空)是允许的
取决于你的语言,stack可能没有被内建支持。你可以使用list(列表)或者deque(双端队列)来模拟,确保只使用栈的标准操作即可
你可以假设所有的操作都是有效的(例如,不会对一个空的队列执行pop或者peek操作)
解题思路:
“双栈法”或者“单栈法”均可。
"""
"""
双栈法:
维护两个栈inStack与outStack,其中inStack接收push操作新增的元素,outStack为pop/peek操作提供服务
由于栈具有后进先出(Last In First Out)的性质,栈A中的元素依次弹出并压入空栈B之后,栈A中元素的顺序会被逆转
当执行pop或者peek操作时,如果outStack中元素为空,则将inStack中的所有元素弹出并压入outStack,然后对outStack执行相应操作
由于元素至多只会从inStack向outStack移动一次,因此peek/pop操作的平摊开销为O(1)
"""
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.inStack = []
self.outStack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.inStack.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
self.peek()
return self.outStack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if not self.outStack:
while self.inStack:
self.outStack.append(self.inStack.pop())
return self.outStack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return len(self.inStack) + len(self.outStack) == 0
"""
单栈法:
在执行push操作时,使用辅助栈swap,将栈中元素顺序按照push顺序的逆序存储。
此时,push操作的时间复杂度为O(n),其余操作的时间复杂度为O(1)
"""
class MyQueue2(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
swap = []
while self.stack:
swap.append(self.stack.pop())
swap.append(x)
while swap:
self.stack.append(swap.pop())
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
return self.stack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
return self.stack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return len(self.stack) == 0
if __name__ == '__main__':
obj = MyQueue2()
for x in range(5):
obj.push(x)
param_2 = obj.pop()
param_3 = obj.peek()
param_4 = obj.empty()
print param_2
print param_3
print param_4
|
1956ea7ce6d5955b343157031ad1089928bf0dfa | Moby5/myleetcode | /python/202_Happy_Number.py | 2,098 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
202. Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
题目大意:
编写一个算法判断某个数字是否是“快乐数”。
快乐数的定义过程如下:从任意一个正整数开始,将原数替换为其每一位的平方和,
重复此过程直到数字=1(此时其值将不再变化),
或者进入一个不包含1的无限循环。那些以1为过程终止的数字即为“快乐数”。
例如:19是一个快乐数,演算过程见题目描述。
解题思路:
模拟题,循环过程中用set记录每次得到的平方和
当出现非1的重复平方和时,返回False
否则,返回True
"""
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def sum_of_squares_of_digits(num):
ans = 0
a = num
while a > 0:
ans += (a % 10) ** 2
a = a / 10
return ans
num = n
num_set = set()
while num != 1 and num not in num_set:
num_set.add(num)
num = sum_of_squares_of_digits(num)
# print num
return num == 1
def isHappy_v1(self, n):
numSet = set()
while n != 1 and n not in numSet:
numSet.add(n)
sum = 0
while n:
digit = n % 10
sum += digit * digit
n /= 10
n = sum
return n == 1
test = Solution()
print test.isHappy(19)
print test.isHappy(2)
|
3d7405e5cb56a877aba49c4c6cbb74fec7487dbd | Moby5/myleetcode | /python/13_Roman_to_Integer.py | 3,949 | 4 | 4 | #!/usr/bin/env python
# coding=utf-8
# Date: 2018-07-23
"""
https://leetcode.com/problems/roman-to-integer/description/
13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: C = 100, L = 50, XXX = 30 and III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
"""
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
symbol2num = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, "IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900}
ans, idx, size = 0, 0, len(s)
while idx < size:
if idx < size - 1 and s[idx: idx + 2] in symbol2num:
sym = s[idx: idx + 2]
idx += 2
else:
sym = s[idx]
idx += 1
ans += symbol2num[sym]
return ans
def romanToInt_v1(self, s):
symbol2num = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, "a": 4, "b": 9, "c": 40, "d": 90, "e": 400, "f": 900}
sym2subtraction = {"IV": "a", "IX": "b", "XL": "c", "XC": "d", "CD": "e", "CM": "f"}
for k, v in sym2subtraction.items():
s = s.replace(k, v)
return sum([symbol2num[k] for k in s])
def romanToInt_v2(self, s):
symbol2num = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
ans, idx, size = 0, 0, len(s)
for idx, value in enumerate(s):
if idx < size - 1 and symbol2num[s[idx]] < symbol2num[s[idx + 1]]:
ans -= symbol2num[s[idx]]
else:
ans += symbol2num[s[idx]]
return ans
solutio = Solution()
ss = ["III", "IV", "IX", "LVIII", "MCMXCIV"]
for s in ss:
print(s, solutio.romanToInt(s))
"""
https://leetcode.com/problems/roman-to-integer/discuss/152501/My-python-solutionb
def romanToInt(self, x):
foo = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000, "a":4,"b":9,"c":40,"d":90,"e":400,"f":900}
x = x.replace("IV","a")
x = x.replace("IX","b")
x = x.replace("XL","c")
x = x.replace("XC","d")
x = x.replace("CD","e")
x = x.replace("CM","f")
value= 0
for i in range(len(x)):
value += foo[x[i]]
return value
https://leetcode.com/problems/roman-to-integer/discuss/6537/My-Straightforward-Python-Solution
def romanToInt(self, s):
roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i+1]]:
z -= roman[s[i]]
else:
z += roman[s[i]]
return z + roman[s[-1]]
"""
|
a763c9d6e4f909126e046c04ee2baa79a24923ea | Moby5/myleetcode | /python/62_Unique_Paths.py | 3,652 | 4.28125 | 4 | #!/usr/bin/env python
# coding=utf-8
# Date: 2018-09-12
"""
https://leetcode.com/problems/unique-paths/description/
62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
"""
import operator
class Solution(object):
def uniquePaths(self, m, n): # 排列组合
"""
:type m: int
:type n: int
:rtype: int
"""
if m < n:
m, n = n, m
mul = lambda x, y: reduce(operator.mul, range(x, y), 1)
return mul(m, m + n - 1) / mul(1, n)
def uniquePaths_v1(self, m, n): # 动态规划, 空间复杂度可以优化至O(n)
"""
:type m: int
:type n: int
:rtype: int
"""
if m < n:
m, n = n, m
dp = [0] * n
dp[0] = 1
for x in range(m):
for y in range(n - 1):
dp[y + 1] += dp[y]
return dp[n - 1]
def uniquePaths_v0(self, m, n): # 动态规划
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0] * n for x in range(m)]
dp[0][0] = 1
for x in range(m):
for y in range(n):
if x + 1 < m:
dp[x + 1][y] += dp[x][y]
if y + 1 < n:
dp[x][y + 1] += dp[x][y]
return dp[m - 1][n - 1]
solution = Solution()
for m, n in [[3, 2], [7, 3]]:
print(m, n, solution.uniquePaths(m, n))
"""
http://bookshadow.com/weblog/2015/10/11/leetcode-unique-paths/
题目大意:
一个机器人位于m x n隔板的左上角(在图中标记为“起点”)。
机器人在任意一点只可以向下或者向右移动一步。机器人尝试到达隔板的右下角(图中标记为“终点”)
有多少种可能的路径?
注意:m和n最多为100
解题思路:
解法I:动态规划
状态转移方程:
dp[x][y] = dp[x - 1][y] + dp[x][y - 1]
初始令dp[0][0] = 1
Python代码:
class Solution(object):
def uniquePaths(self, m, n):
dp = [[0] * n for x in range(m)]
dp[0][0] = 1
for x in range(m):
for y in range(n):
if x + 1 < m:
dp[x + 1][y] += dp[x][y]
if y + 1 < n:
dp[x][y + 1] += dp[x][y]
return dp[m - 1][n - 1]
上述解法空间复杂度可以优化至O(n):
class Solution(object):
def uniquePaths(self, m, n):
if m < n:
m, n = n, m
dp = [0] * n
dp[0] = 1
for x in range(m):
for y in range(n - 1):
dp[y + 1] += dp[y]
return dp[n - 1]
解法II:排列组合
题目可以转化为下面的问题:
求m - 1个白球,n - 1个黑球的排列方式
公式为:C(m + n - 2, n - 1)
Python代码:
class Solution(object):
def uniquePaths(self, m, n):
if m < n:
m, n = n, m
mul = lambda x, y: reduce(operator.mul, range(x, y), 1)
return mul(m, m + n - 1) / mul(1, n)
"""
|
bd4619b0c4c69fddaa93c8e896a89873c74e245a | Moby5/myleetcode | /python/414_Third_Maximum_Number.py | 2,199 | 4.15625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/10/09/leetcode-third-maximum-number/
414. Third Maximum Number
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
题目大意:
给定一个整数数组,返回数组中第3大的数,如果不存在,则返回最大的数字。时间复杂度应该是O(n)或者更少。
解题思路:
利用变量a, b, c分别记录数组第1,2,3大的数字
遍历一次数组即可,时间复杂度O(n)
"""
import numpy as np
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a, b, c = None, None, None
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c = n, b
elif b > n > c:
c = n
return c if c is not None else a # 不能直接 return c if c else a 因为c可能为0
def thirdMax_runtime_error(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ns = np.unique(nums)
return np.max(ns) if len(ns) < 3 else ns[-3]
def thirdMax_ref(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = b = c = None
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c = n, b
elif b > n > c:
c = n
return c if c is not None else a
test = Solution()
print test.thirdMax([3,2,1])
print test.thirdMax([1,2])
print test.thirdMax([2,2,3,1])
print test.thirdMax([3,3,4,3,4,3,0,3,3])
|
6fb4526978401246c9407b8bbcaeb87c7c86d611 | Moby5/myleetcode | /python/389_Find_the_Difference.py | 2,215 | 3.734375 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/08/28/leetcode-find-the-difference/
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
题目大意:
给定两个字符串s和t,都只包含小写字母。
字符串t由字符串s打乱顺序并且额外在随机位置添加一个字母组成。
寻找t中新增的那个字母。
测试用例如题目描述。
解题思路:
分别统计s与t的字母个数,然后比对即可。若使用Python解题,可以使用collections.Counter。
"""
from collections import Counter
class Solution(object):
def findTheDifference_v0(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
cs, ct = Counter(s), Counter(t)
for k, v in ct.iteritems():
if k not in cs.keys() or cs[k] != v:
return k
def findTheDifference_ref(self, s, t):
ds, dt = Counter(s), Counter(t)
return (dt - ds).keys().pop()
def findTheDifference(self, s, t): # 效率最高 # 从下面的Java参考代码改编为Python
ans = 0
for i in range(len(s)):
ans = ans ^ ord(s[i])
for i in range(len(t)):
ans = ans ^ ord(t[i])
return chr(ans)
"""
另一种解法,利用异或运算。
Java代码:
public class Solution {
public char findTheDifference(String s, String t) {
char ans = 0;
for (int i = 0; i < s.length(); i++) {
ans ^= s.charAt(i);
}
for (int i = 0; i < t.length(); i++) {
ans ^= t.charAt(i);
}
return ans;
}
}
"""
test = Solution()
s, t = 'abcd', 'abcde'
print test.findTheDifference(s, t)
s, t = 'abcd', 'abcdd'
print test.findTheDifference(s, t)
|
c3a924baa0f8266ed3900f897439da2766392df5 | Moby5/myleetcode | /python/693_Binary_Number_with_Alternating_Bits.py | 1,729 | 4 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2017/10/08/leetcode-binary-number-with-alternating-bits/
693. Binary Number with Alternating Bits
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
题目大意:
给定正整数,判断其二进制是否01交替。
"""
class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
return not bin(n ^ (n >> 1))[2:].count('0')
def hasAlternatingBits_ref1(self, n): # 解法I 进制转换
n = bin(n)
return all (n[x] != n[x + 1] for x in range(len(n) - 1))
def hasAlternatingBits_ref2(self, n): # 解法II 位运算
last = n & 1
n >>= 1
while n:
bit = n & 1
if bit == last: return False
last = bit
n >>= 1
return True
def hasAlternatingBits_ref3(self, n): # Divide By Two https://leetcode.com/problems/binary-number-with-alternating-bits/solution/
n, cur = divmod(n, 2)
while n:
if cur == n % 2: return False
n, cur = divmod(n, 2)
return True
solution = Solution()
nums = [5, 7, 11, 10, 4] # T, F, F, T, F
for n in nums:
print solution.hasAlternatingBits(n)
|
435ea91454abcafece1d68c23106f565bc004030 | Moby5/myleetcode | /python/263_Ugly_Number.py | 1,258 | 4.1875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2015/08/19/leetcode-ugly-number/
263. Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
题目大意:
编写程序判断一个给定的数字是否为“丑陋数” ugly number
丑陋数是指只包含质因子2, 3, 5的正整数。例如,6, 8是丑陋数而14不是,因为它包含额外的质因子7
注意,数字1也被视为丑陋数
解题思路:
将输入数重复除2, 3, 5,判断得数是否为1即可
时间复杂度:
记num = 2^a * 3^b * 5^c * t,程序执行次数为 a + b + c,换言之,最坏情况为O(log num)
"""
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for x in [2, 3, 5]:
while num % x == 0:
num = num / x
return num == 1
test = Solution()
nums = [1, 6, 8, 14]
for num in nums:
print num, test.isUgly(num)
|
8275fed43d66d21fc20c3fde3881859b657ba757 | Moby5/myleetcode | /python/401_Binary_Watch.py | 2,926 | 3.765625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/09/18/leetcode-binary-watch/
LeetCode 401. Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:
The order of output does not matter.
The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
题目大意:
一个二进制手表顶端有4盏LED灯表示小时(0-11),底部有6盏LED灯表示分钟(0-59)。
每一盏LED灯表示一个0或1,最右端为最低位。
例如上图中的例子读数为"3:25"。
给定一个非负整数n表示当前燃亮的LED灯数,返回所有可能表示的时间。
注意:
输出顺序不重要。
小时不可以包含前缀0,例如"01:00"是无效的,应当为"1:00"。
分钟必须包含两位数字,可以包含前导0,例如"10:2"是无效的,应当为"10:02"。
解题思路:
位运算(Bit Manipulation)
10盏灯泡的燃亮情况可以通过0-1024进行表示,然后计数二进制1的个数即可。
利用位运算将状态拆分为小时和分钟。
"""
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
ans = []
for h in range(12):
for m in range(60):
if (bin(h) + bin(m)).count('1') == num:
ans.append('%d:%02d' % (h, m))
return ans
def readBinaryWatch_ref(self, num):
"""
:type num: int
:rtype: List[str]
"""
ans = []
for x in range(1024):
if bin(x).count('1') == num:
h, m = x >> 6, x & 0x3F
if h < 12 and m < 60:
ans.append('%d:%02d' % (h, m))
return ans
def readBinaryWatch_ref2(self, num):
"""
:type num: int
:rtype: List[str]
参考LeetCode Discuss:https://discuss.leetcode.com/topic/59374/simple-python-java
枚举小时h和分钟m,然后判断二进制1的个数是否等于num
"""
ans = []
for h in range(12):
for m in range(60):
if (bin(h)+ bin(m)).count('1') == num:
ans.append('%d:%02d' % (h, m))
return ans
test = Solution()
print test.readBinaryWatch(1)
|
c5e27b7b53627a3de5c75877317753b0a3a810be | Moby5/myleetcode | /python/289_Game_of_Life.py | 4,331 | 4.1875 | 4 | #!/usr/bin/env python
# coding=utf-8
# Date: 2018-10-30
# File: 289_Game_of_Life.py
"""
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population..
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.
Example:
Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
Follow up:
Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
"""
class Solution(object):
def gameOfLife(self, board): # 20 ms
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
dx = (1, 1, 1, 0, 0, -1, -1, -1)
dy = (1, 0, -1, 1, -1, 1, 0, -1)
for x in range(len(board)):
for y in range(len(board[0])):
lives = 0
for z in range(8):
nx, ny = x + dx[z], y + dy[z]
lives += self.getCellStatus(board, nx, ny)
if lives + board[x][y] == 3 or lives == 3:
board[x][y] |= 2
for x in range(len(board)):
for y in range(len(board[0])):
board[x][y] >>= 1
def getCellStatus(self, board, x, y):
if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]):
return 0
return board[x][y] & 1
solution = Solution()
Input = [
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output = [
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
solution.gameOfLife(Input)
assert Input == Output, Input
print("Pass.")
"""
http://bookshadow.com/weblog/2015/10/04/leetcode-game-life/
题目大意:
根据维基百科的文章:“生命游戏,也被简称为生命,是一款由英国数学家约翰·霍顿康威于1970年设计的细胞自动机。”
给定一个m * n的细胞隔板,每一个细胞拥有一个初始状态:存活(1)或者死亡(0)。每一个细胞与其周围的8个邻居细胞(水平,竖直,对角线)发生交互,依据如下四条规则(摘自维基百科):
任何相邻存活细胞数小于2个的存活细胞都会死亡,模拟人口不足。
任何相邻存活细胞数为2个或者3个的存活细胞会存活到下一代。
任何相邻存活细胞数大于3个的存活细胞都会死亡,模拟人口过载。
任何相邻存活细胞数等于3个的死亡细胞都会成为一个存活细胞,模拟繁殖。
编写函数,根据隔板的当前状态,计算其下一个状态(一次更新之后)
进一步思考:
你可以就地完成题目吗?记住隔板需要同时更新:你不能先更新某些细胞然后再以其变更后的值来更新其他细胞。
在这个问题中,我们使用2维数组表示隔板。原则上,隔板是无穷的,这可能导致一些边界问题。你怎么处理边界问题?
解题思路:
位运算(bit manipulation)
由于细胞只有两种状态0和1,因此可以使用二进制来表示细胞的生存状态
更新细胞状态时,将细胞的下一个状态用高位进行存储
全部更新完毕后,将细胞的状态右移一位
"""
|
a3f0ed60542ab8174c23174d1a48c8e2273b9e50 | Moby5/myleetcode | /python/640_Solve_the_Equation.py | 2,492 | 4.3125 | 4 | #!/usr/bin/env python
# coding=utf-8
# 566_reshape_the_matrix.py
"""
http://bookshadow.com/weblog/2017/07/09/leetcode-solve-the-equation/
LeetCode 640. Solve the Equation
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
题目大意:
给定一元一次方程,求x的值
解题思路:
字符串处理
用'='将等式分为左右两半
分别求左右两侧x的系数和常数值,记为lx, lc, rx, rc
令x, c = lx - rx, rc - lc
若x != 0,则x = c / x
否则,若c != 0,说明方程无解
否则,说明有无数组解
"""
class Solution(object):
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
left, right = equation.split('=')
lcoef, lconst = self.solve(left)
rcoef, rconst = self.solve(right)
coef, const = lcoef - rcoef, rconst - lconst
if coef: return 'x=%d' % (const / coef)
elif const: return 'No solution'
return 'Infinite solutions'
def solve(self, expr):
coef = const = 0
num, sig = '', 1
for ch in expr + '#':
if '0' <= ch <= '9':
num += ch
elif ch == 'x':
coef += int(num or '1') * sig
num, sig = '', 1
else:
const += int(num or '0') * sig
num, sig = '', 1
if ch == '-': sig = -1
return coef, const
if __name__ == '__main__':
solution = Solution()
equations = ["x+5-3+x=6+x-2", "x=x" ,"2x=x", "2x+3x-6x=x+2", "x=x+2"]
for e in equations:
print e, solution.solveEquation(e)
pass
|
74acc85bd825153d20f67ef4f2d3f5c3cd78c4ef | GarySun527/Python | /elementary/forWhile.py | 227 | 3.6875 | 4 | #for loop
ls = [12, 64, 56, 89, 72, 90]
for grade in ls:
print(grade)
while grade >30:
print(">30")
break
print('end')
print("*********************")
for x in [1,2,3,4,5]:
for y in (9,8,7,6):
print(x+y)
print("end")
|
549ae44ba1517ca134e2677a63cc3fe5cfb5f205 | joaoribas35/distance_calculator | /app/services/calculate_distance.py | 943 | 4.34375 | 4 | import haversine as hs
def calculate_distance(coordinates):
""" Will calculate the distance from Saint Basil's Cathedral and the address provided by client usind Haversine python lib. Saint Basil's Cathedral is used as an approximation to define whether the provided address is located inside the MKAD Moscow Ring Road (MKAD) or not. It's location is the center point to a 18 km radius circle. Will return a null string indicating the address is inside MKAD or a string with the distance from MKAD border, expressed in kilometers, if the address falls outside the MKAD. """
CENTER_POINT = (55.75859164153293, 37.623173678442136)
CIRCLE_RADIUS = 18
input_address = (coordinates['lat'], coordinates['lon'])
distance = hs.haversine(CENTER_POINT, input_address)
if distance <= CIRCLE_RADIUS:
return 'null'
distance_from_border = round(distance - CIRCLE_RADIUS, 2)
return f'{distance_from_border} km'
|
fe2e03f8ab417fdea23b1804a79290c0d62d4dd4 | chuming03403/python3 | /algorithmAndDataStructure/rotate.py | 753 | 3.546875 | 4 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
https://leetcode-cn.com/problems/rotate-array
"""
leng = len(nums);
k %= leng;
loop_time = current = start = 0;
while True:
if loop_time >= leng:
break;
num = nums[current];
while True:
current = (current + k) % leng;
temp = num;
num = nums[current];
nums[current] = temp;
loop_time += 1;
if current == start:
break;
start += 1;
current = start;
return True; |
d533297457a4d78636b6c8e78241327454767d4d | KaranKaira/StorePassword | /STOREPASSWORDS.py | 4,981 | 4.09375 | 4 | #First project
#why?? Just to get a hang of project building
# I will be using tkinter for gui
# This app is for storing passwords offline in a encrypted manner
#Day1 :8,july,19
import tkinter as tk
import tkinter.messagebox as msgbox
import os
HEIGHT = 300
WIDTH = 600
root = tk.Tk()
root.title("STORE PASSWORD")
canvas = tk.Canvas(root,height=HEIGHT,width=WIDTH)
canvas.pack()
frame = tk.Frame(root,bg='white' )
frame.place(relwidth=1,relheight=1)
# windows that will open when 'create new account' button is pressed
# these function done on day2 8,july,19
# Functionality of Create My Account Button inside Create My Account Button
def check(New_User_Name, New_Password): #check for empty fields and then for username uniqueness
if New_Password != '' and New_User_Name != '': # avoiding empty fields
with open('UserNames.txt','r+') as UserName_check:
if os.stat("UserNames.txt").st_size != 0: # to check empty file
if New_User_Name in UserName_check.readlines()[0].split(','):
msgbox.askretrycancel("Error","This UserName already exist")
return False
return True
else:
msgbox.showinfo('Empty Fields', 'You left UserName/Password field empty')
# if anyone field is left empty
def Verify_Login(UserName,Password):
with open('UserInfo.txt','r') as Check_Usernames:
user_info=str(UserName+','+Password)
if Check_Usernames.readlines()[Check_Usernames.readlines().index(user_info)].split(',')[0] == UserName and Check_Usernames.readlines()[Check_Usernames.readlines().index(user_info)].split(',')[1]==Password:
ShowPasswords()
else:
print("This account is not registered")
def ShowPasswords():
msgbox.showinfo("Accounnt is here"," your account is with us")
def ADD_User_Info(New_User_Name,New_Password): # after checkinh for uniqueness finally adding user
with open('UserInfo.txt' , 'a') as add:
add.write( New_User_Name + ',' + New_Password + '\n')
with open('UserNames.txt','a') as Add_New_Username:
Add_New_Username.write(New_User_Name+ ',')
msgbox.showinfo("Account Created" , "Your Account has been created")
def open_new_account_Window():
# this function is for FINALLY creating account after user enters deatails.
def Account_Creation():
New_User_Name = entry_NEW_Username.get()
New_Password = entry_New_Password.get()
if check(New_User_Name , New_Password):
ADD_User_Info(New_User_Name,New_Password) # this fucnton finally adds this user and its password
Create_New_Account_Window=tk.Toplevel()
Create_New_Account_Window.title('Create New Account')
tk.Canvas(Create_New_Account_Window,height=HEIGHT,width=WIDTH).pack()
# UserName Label and Entry
label_NEW_username=tk.Label(Create_New_Account_Window,text='New Username :',bg='white')
label_NEW_username.place(relx=0,rely=0.25,relwidth=0.29,relheight=0.1)
entry_NEW_Username = tk.Entry(Create_New_Account_Window,bg='lightgray')
entry_NEW_Username.place(relx=0.3,rely=0.25,relwidth=0.5,relheight=0.1)
# Password Label and Entry
tk.Label(Create_New_Account_Window,text='Your Master Password',bg='white').place(relx=0,rely=0.4,relwidth=0.29,relheight=0.1)
entry_New_Password=tk.Entry(Create_New_Account_Window,bg='lightgray',show='*')
entry_New_Password.place(relx=0.3, rely=0.4, relwidth=0.5, relheight=0.1)
# Final Create My Account Button
tk.Button(Create_New_Account_Window,text='Create My Account',cursor='hand2',command=Account_Creation).place(relx=0.3,rely=0.6,relwidth=0.4,relheight=0.1)
# Main Window
#create new account button
button_create_new_account=tk.Button(frame,text='Create New Account',cursor='hand2',command=open_new_account_Window)
button_create_new_account.place(relx=0.6,rely=0.9,relwidth=0.40,relheight=0.1)
# Username and its master password
label_username = tk.Label(frame,text='Username :',bg='white').place(relx=0,rely=0.25,relwidth=0.29,relheight=0.1)
entry_username=tk.Entry(frame,bg='lightgray')
entry_username.place(relx=0.3,rely=0.25,relwidth=0.5,relheight=0.1)
label_Login=tk.Label(frame,text='Enter your Master Password :',bg='white').place(relx=0,rely=0.4,relwidth=0.29,relheight=0.1)
entry_masterlogin_Password=tk.Entry(frame, bg='lightgray', show='@')
entry_masterlogin_Password.place(relx=0.3, rely=0.4, relwidth=0.5, relheight=0.1)
# Day 2 9 july,2019 except command parameter
buttton_verify=tk.Button(frame,text='Let Me In',cursor='hand2',command=lambda: Verify_Login(entry_username.get(),entry_masterlogin_Password.get()))
buttton_verify.place(relx=0.5,rely=0.6,relheight=0.1,relwidth=0.1) #button to click Enter
root.mainloop() |
1097684fdea2550be363cb1fa189bada61273464 | LichKing-lee/python_start | /test/MultiplicationTable.py | 113 | 3.78125 | 4 | for num1 in range(2, 10):
for num2 in range(1, 10):
print("%s * %s = %s" % (num1, num2, num1 * num2)) |
c15d22e2cf2192b4e1ef7df1e1d609f5a12f4ae9 | mandycrose/module-02 | /ch04_conditionals/ch04_mandy.py | 5,175 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import random
import datetime
import time
print("hello")
def luckyNumberRandom():
name= input ("please type your name here: ")
print ("hello", name.upper())
number= int(input("please give a number: "))
print ("your luck number is:" + str(random.randint(50,number)))
luckyNumberRandom()
startTime= time.time()
print("date and time", datetime.datetime.now())
print ()
print ("current time:", datetime.datetime.now().time())
def luckyNumberRandom():
name= input ("please type your name here: ")
print ("hello", name.upper())
number= int(input("please give a number: "))
print ("your luck number is:" + str(random.randint(50,number)))
luckyNumberRandom()
processTime= time.time()-startTime
print ()
print("program running time:", round(processTime,2), "seconds")
print("this"=="this")
age = 15
isaTeen= age>=13 and age<=19
print(isaTeen)
age = 24
isaTeen= age>=13 and age<=19
print (isaTeen)
def checkTeen(age):
return age>=13 and age<=19
age = 34
print(checkTeen(age))
################# IF/ELSE statements Task 3/4 ###############
def numberGame ():
number= input("Enter a number between 1 and 10: ")
number = int(number)
if number > 10 :
print("Too high!")
number= input("try again! Enter a number between 1 and 10: ")
number = int(number)
if number <= 0 :
print("Too low")
number= input("try again! Enter a number between 1 and 10: ")
number = int(number)
else:
print ("great number!")
#### last two will be paired -- needs to be elif ###
numberGame()
######## task 5 #####################
def ageGame():
age= input("what is your age? ")
age= int(age)
# if age < 65:
# print("you are an adult")
if age < 13:
print ("you are a child!")
elif age < 18:
print ("you are a teen!")
elif age < 65:
print("you are an adult")
else:
print ("you are a pensioner! Lucky you!")
ageGame()
########## shipping weight project #######
#def ground_shipping(weight):
# if weight <= 2.0:
# return (1.50 * weight)
# elif weight >2.0 and weight <= 6.0:
# return (3.00 * weight)
# elif weight >6.0 and weight <= 10.0:
# return (4.0 * weight)
# else:
# return (weight * 4.75)
#
#print (ground_shipping(11))
#
#def ground_shipping(weight):
# if weight <= 2.0:
# return (4.50 * weight)
# elif weight >2.0 and weight <= 6.0:
# return (9.00 * weight)
# elif weight >6.0 and weight <= 10.0:
# return (12.0 * weight)
# else:
# return (weight * 14.25)
#def best_shipping(weight):
# if weight <= 2.0 and ((1.50 * weight) + 20.00) < ((4.50 * weight) or 125):
# print ("your best shipping is ground")
# elif weight weight >2.0 and weight <= 6.0 and ((3.00 * weight) + 20.00) < ((9.00 * weight)or 125) :
# print("your best shipping is ground")
#def best_shipping(weight):
# if weight <= 2.0 and ((1.50 * weight) + 20) < ((4.50 * weight) or 125):
# return ("your best shipping is ground")
# elif weight <= 2.0 and ((4.50 * weight) < ((1.50 * weight) + 20) or < 125):
# return ("your best shipping is drone")
# elif weight <= 2.0 and ((1.50 * weight) + 20) and (4.50 * weight) > 125:
# return ("your best shipping is flat rate ground")
# else:
# print("hold on")
#def best_shipping(weight):
# if weight <= 2.0 and ((1.50 * weight) + 20) < ((4.50 * weight) or 125):
# return ("your best shipping is ground")
# elif weight <= 2.0 and ((1.50 * weight) + 20) > ((4.50 * weight) or 125):
# return ("your best shipping is drone")
# elif weight <= 2.0 and (((4.50 * weight) + 20) or (1.50 * weight)) > 125:
# return ("your best shipping is flat rate")
#
# elif weight >2.0 and weight <= 6.0 and ((3.00 * weight) + 20) < ((9.00 * weight) or 125):
# return ("your best shipping is ground")
# elif weight >2.0 and weight <= 6.0 and ((3.00 * weight) + 20) > ((9.00 * weight) or 125):
# return ("your best shipping is drone")
# elif weight >2.0 and weight <= 6.0 and (((3.00 * weight) + 20) or (9.00 * weight)) > 125:
# return ("your best shipping is flat rate")
#
# elif weight >6.0 and weight <= 10.0 and ((4.00 * weight) + 20) < ((12.00 * weight) or 125):
# return ("your best shipping is ground")
# elif weight >6.0 and weight <= 10.0 and ((4.00 * weight) + 20) > ((12.00 * weight) or 125):
# return ("your best shipping is drone")
# elif weight >6.0 and weight <= 10.0 and (((4.00 * weight) + 20) or (12.00 * weight)) > 125:
# return ("your best shipping is flat rate")
#
# elif weight > 10.0 and (125 or (14.25 * weight)) > ((4.75 * weight) + 20):
# return ("your best shipping is ground")
# elif weight > 10.0 and ((4.75 * weight) + 20) > ((14.25 * weight) or 125):
# return ("your best shipping is drone")
# elif weight > 10.0 and (125 < (((4.75 * weight) + 20) or (14.25 * weight))):
# return ("your best shipping is flat rate")
#print(best_shipping(400))
#
|
4c0f910b6f9f0dc93578103a3c11a9c0478fd2c7 | mandycrose/module-02 | /ch09_lists_tuples/ch09_mandy.py | 2,137 | 3.890625 | 4 | ### -*- coding: utf-8 -*-
##"""
##Created on Thu Dec 13 09:45:32 2018
##
##@author: 612436112
##"""
################################################################
#lists and tuples
################################################################
#### task 1 ########
my_favourite_fruits = ["apple", "orange", "banana"]
x = ["this", 55, "that", my_favourite_fruits] #list can contain mix type of data!
x = ["this", 55, "that", my_favourite_fruits]
x[3][0]
##### task 2 ########
x.remove(my_favourite_fruits)
print(x)
x[1] = "and" #update list item value by using index of the item in the current list
x.append("again")
print(x)
y = x.append("hello")
print(x)
print(y)
y=x
x.append("test 1")
x.append("test 2")
print (y)
y.append("test 3")
print(x)
print(y)
x = ["the", "cat", "sat"]
y = ["on", "the", "hat"]
z= x+y
print (z)
print(list(zip(x,y)))
print(z*3)
############## task 3 - slicing #####################
a=["the", "cat", "sat","on", "the", "hat"]
print(a[:3])
print(a[2:4])
print(a[-1:])
print(a[-1])
print(a[-3:-1])
####### task 4 - sorting ###############
x = [7,11,3,9,2]
y= sorted(x,reverse=True) #this does not change x, need to assign to variable
print(y)
x.sort(reverse= True) #changes x
print(x)
toppings = ["pepperoni","pinapple","cheese","sausage","olives","anchovies","mushrooms"]
toppings.sort()
print (toppings)
new_toppings = sorted(toppings, reverse= True)
print(new_toppings)
###### task 5 - tuples #######
#list
##
a = [0,1,2,3,4,5,6,7,8,9]
del a [-1]
#
print(a)
#
#tuple
b = (0,1,2,3,4,5,6,7,8,9)
##del b [-1]
##print(b) # error message that tuple does not support deletion
a[2]= "hello"
print(a)
#b[2]= "hello" # again, tuple can not be changed
a.append("this is an appendment")
print(a)
#b.append("this is an appendment") # can't append tuple
#print(b)
#### task 6 - lambda function ######
b = (0,1,2,3,4,5,6,7,8,9)
myFavF = ["apple","3","orange", "banana"]
x = ["afsf", "1", "csdf", "dsdf","fsdf", "sdfe"]
z = ["gsdf", "2", "isdb", "jsdf", "lsdf","ksfs" ]
x2= [("a",3,z),("c", 1, x),("b",5,myFavF)]
#print(sorted(x2))
print(sorted(x2, key=lambda s:s[2][2][-1]))
|
536bf2470f47c6353bc674b6c1efd668f8c03473 | nonbinaryprogrammer/python-poet | /sentence_generator.py | 787 | 4.15625 | 4 | import random
from datetime import datetime
from dictionary import Words
#initializes the dictionary so that we can use the words
words = Words();
#makes the random number generator more random
random.seed(datetime.now)
#gets 3 random numbers between 0 and the length of each list of words
random1 = random.randint(0, 3000) % (len(words.plural_nouns))
random2 = random.randint(0, 3000) % (len(words.plural_verbs))
random3 = random.randint(0, 3000) % (len(words.plural_nouns))
#gets the n-th word from the list of words
#where n is the randomly chosen number above
noun1 = words.plural_nouns[random1]
verb1 = words.plural_verbs[random2]
noun2 = words.plural_nouns[random3]
#prints out each of the randomly chosen words with spaces between them
print noun1 + " " + verb1 + " " + noun2
|
b28c0c119986cc5038a4432cb60f283edbbc1fe3 | geri-brs/machine-learning | /1-python-learning/absolute_sorting.py | 317 | 3.640625 | 4 | def absolute(x):
if x >= 0:
return x
else:
return -x
def sorting(tup):
abs_list = []
for i in(tup):
abs_list.append(absolute(i))
return abs_list
if __name__ == '__main__':
a = (-20, -5, 10, 15)
print(sorted(a, None, lambda a: abs(a))
|
056f8e9d8e18434439f808ff843a6ffa33ded582 | geri-brs/machine-learning | /1-python-learning/best_stock.py | 360 | 3.578125 | 4 | def best_stock(data):
max_key = ""
max_value = 0
for i in (data):
if (data[i] > max_value):
max_key = i
max_value = data[i]
return max_key
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}))
|
29c9b1126c9d887ee79a14ab4f84d2b0649d18bd | geri-brs/machine-learning | /1-python-learning/long repeat.py | 356 | 3.75 | 4 | str = "ddvvrwwwrggg"
max_len = 0
counter = 0
for i in range(0, len(str)-1):
if (str[i] == str[i+1]):
counter = counter +1
print("if counter erteke: ", counter)
if (counter > max_len):
max_len = counter + 1
print("max_len: ", max_len)
else:
counter = 0
print(max_len)
|
7edee44532645aa8d53cb926de43472b2d1a5e88 | geri-brs/machine-learning | /1-python-learning/NonUniqueElements.py | 195 | 3.6875 | 4 | numbers = [1,2,3,1,3]
shadow = numbers
counter = 0
shadow.sort()
for i in shadow:
for j=i+1 in shadow:
if (shadow[i] == shadow[j]): counter = counter + 1
print(counter)
|
c5047dc2219680d70c2510dc19397499c3f7b23e | mraduldubey/HackerRank-Python-Challenge | /Sets/l32.py | 346 | 3.828125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT
eng_n = int(raw_input().strip())
eng = set(map(int,raw_input().split()))
fren_n = int(raw_input().strip())
fren = map(int,raw_input().split())
print len(eng.difference(fren)) #intersection of set and list
|
64f25a6b6a5bdef76122207cad6cca342f7e6c2b | ggb367/Fall-2019 | /366K/hw2/hw2-3.py | 248 | 3.84375 | 4 | import matplotlib.pyplot as plt
import numpy as np
du = np.linspace(1, 5, 100)
g = np.divide(1, np.square(du))
plt.plot(du, g)
plt.xlabel('Distance in Earth Radii')
plt.ylabel('g/g_0')
plt.title('Inverse Square Decay of Gravity Force')
plt.show()
|
40920683637061713bbc5644ef00969ea16444fd | aralyekta/Data-Structures | /stack/singly.py | 6,007 | 4.25 | 4 | # Our methods are:
# Count, index, insert, remove, append, pop, print, delete, clear, contains, peeklast, peekfirst
class Node: #The class for a node of the linked list
def __init__(self, data):
self.data = data
self.ptr = None
class linkedList: #The class for the linked list
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def clear(self):
while self.length > 0:
self.pop()
def contains(self, data):
indexVal = self.index(data)
if indexVal != -1:
return 1
else:
return 0
def peeklast(self):
return self.tail.data
def peekfirst(self):
return self.head.data
def append(self, data):
nodeToAppend = Node(data)
if not self.head: #Check if linked list is empty
self.head = nodeToAppend
self.tail = nodeToAppend
else:
self.tail.ptr = nodeToAppend
self.tail = nodeToAppend
self.length += 1
def print(self):
ptrToIncrement = self.head
if not ptrToIncrement:
print("Linked list doesn't have any elements")
return
while ptrToIncrement:
print(ptrToIncrement.data, end =" ")
ptrToIncrement = ptrToIncrement.ptr
print("")
def pop(self):
if not self.head:
print("Linked list doesn't have any elements")
return None
valToReturn = self.tail.data
if self.head is self.tail: #Check if the linked list has only one node
self.head = None
self.tail = None
else: #If not, do the regular pop operation
ptrToIncrement = self.head
while (ptrToIncrement.ptr is not self.tail): #Find the (n-1)th node
ptrToIncrement = ptrToIncrement.ptr
self.tail = ptrToIncrement
ptrToIncrement.ptr = None
self.length -= 1
return valToReturn
def count(self, data):
counter = 0
ptrToIncrement = self.head
while ptrToIncrement:
if ptrToIncrement.data == data:
counter += 1
ptrToIncrement = ptrToIncrement.ptr
return counter
def index(self, data):
i = 0
ptrToIncrement = self.head
while ptrToIncrement:
if ptrToIncrement.data == data:
return i
i += 1
ptrToIncrement = ptrToIncrement.ptr
return -1
def insert(self, index, data):
if index < 0: # Checks if index is valid
print("Index must be 0 or positive.")
return
if not self.head: # Checks if the linked list is empty
self.append(data)
return
if index == 0: # Case1: Insert at head
nodeToAdd = Node(data)
nodeToAdd.ptr = self.head
self.head = nodeToAdd
self.length += 1
elif index < self.length: # Case2: Insert in the middle
if self.head == self.tail: #Checks if the linked list has only 1 node, if that is the case, append the node.
self.append(data)
else: # If the linked list is larger than one node, perform the regular insertion
i = 1
ptrToIncrement = self.head
while i < index: #Find the (index-1)th node
ptrToIncrement = ptrToIncrement.ptr
i += 1
ptrSecond = ptrToIncrement.ptr
nodeToAdd = Node(data)
ptrToIncrement.ptr = nodeToAdd
nodeToAdd.ptr = ptrSecond
self.length += 1
else: # If the index is bigger than the current length, append
self.append(data)
def remove(self, data):
if self.length == 0: #Case1: No nodes
print("Linked list doesn't have any elements")
return
if self.length == 1: #Case2: 1 node
if data == self.head.data:
self.pop()
return
else:
print("The element doesn't exist in the linked list")
return
else: #Case3: More than 1 node
ptrToIncrement = self.head
if ptrToIncrement.data == data: #Check if the node to be removed is at the 0th index
self.head = self.head.ptr
self.length -= 1
return
while ptrToIncrement.ptr and ptrToIncrement.ptr.data != data: #Find the node which comes before the node to be removed
ptrToIncrement = ptrToIncrement.ptr
if ptrToIncrement is self.tail: #If this is the case, the loop above ended without matching any values
print("The element doesn't exist in the linked list")
return
elif ptrToIncrement.ptr is self.tail: #If this is the case, the node to be removed is at the end
self.pop()
return
else: #All other cases
ptrToIncrement.ptr = ptrToIncrement.ptr.ptr
self.length -= 1
return
def delete(self, index):
if index < 0: #Check for erroneous input
print("Index should be 0 or positive")
return
elif index == 0: #Delete the first node
self.head = self.head.ptr
self.length -= 1
return
elif index == self.length-1: #Delete the last node
self.pop()
return
elif index >= self.length: #Check for erroneous input
print("Index is out of bounds")
return
else: #Delete a node in the middle
counter = 1
ptrToIncrement = self.head
while counter < index:
ptrToIncrement = ptrToIncrement.ptr
counter += 1
ptrToIncrement.ptr = ptrToIncrement.ptr.ptr
self.length -= 1
|
5773535452e99d26aaea7ec8bb32fe803be868fc | jinensetpal/csjournal | /hashsep.py | 139 | 3.96875 | 4 | #!/usr/bin/python3
with open("file.txt", "r") as f:
for i in f.readlines():
for j in i.split():
print(j, end="#")
|
b09738ccf9f02bc0532aefee16a67b5823bf9ec7 | yongseongCho/python_201911 | /Hello_Python.py | 547 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# 주석문 : 소스 코드의 설명을 위해서
# 사용되는 설명문
"""
여러
라인에
걸친
설명문
"""
# 변수의 선언
number = 10
number = 15
# 출력문 사용
# - print 함수를 사용
print(number)
print("Hello Python~!")
print('오늘은 {0}월 {1}일 입니다.'.format(11, 18))
import tkinter as tk
window=tk.Tk()
window.title('Hello Python Window')
window.geometry('300x300+300+300')
window.resizable(False, True)
window.mainloop()
|
6be96a3fae4524ed7d0121635c03e0e3f60518ee | yongseongCho/python_201911 | /day_03/list_05.py | 1,071 | 3.53125 | 4 | # -*- coding: utf-8 -*-
list_1 = [1,2,3,4,5,6,7,8,9,10]
print(list_1)
# 리스트의 데이터를 삭제하는 방법
# 1. 슬라이싱 연산과 빈 리스트 객체를 활용하는 방법
list_1[3:6] = []
print(list_1)
# 리스트의 데이터를 삭제하는 방법
# 2. del 연산자를 활용하는 방법
del list_1[3]
print(list_1)
# 리스트의 데이터를 삭제하는 방법
# 3. remove 메소드를 활용하는 방법
# - 특정 데이터를 검색하여 삭제
# - 아래의 코드는 list_1에서 9를 검색하여 삭제
# - 만약 삭제할 데이터가 존재하지 않는 경우 에러가 발생
list_1.remove(9)
print(list_1)
# (시작 위치부터 검색하여 최초로 발견된 데이터만 삭제)
list_1 = [1,5,2,5,3,5,4,5]
list_1.remove(5)
print(list_1)
list_1.remove(5)
print(list_1)
# pop 메소드는 해당 리스트의 마지막 요소를 삭제합니다.
# (삭제한 데이터를 반환)
# del 리스트변수[-1] 과 유사하게 동작합니다.
list_1.pop()
print(list_1)
|
0c295d77d6d7949b751ca0dfdae7d5e0565e8e88 | yongseongCho/python_201911 | /day_05/if_03_EX_2.py | 612 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# 사용자에게 3과목의 성적을 입력받아
# 평균점수가 90점이상이면 합격, 미만이면
# 불합격을 출력하세요
score_1 = int(input('1번째 성적을 입력하세요 : '))
score_2 = int(input('2번째 성적을 입력하세요 : '))
score_3 = int(input('3번째 성적을 입력하세요 : '))
# 총점 처리
tot = score_1 + score_2 + score_3
# 평균 처리
avg = tot / 3
# 평균 점수에 따라 합격/불합격 처리
if avg >= 90 :
print('합격입니다.')
else :
print('불합격입니다.')
|
495211f83fdd33e53395370d37826ef203d048fd | yongseongCho/python_201911 | /day_04/set_03.py | 665 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# Set 타입의 데이터를 활용한 &(and), |(or), -
numbers_2 = set([2,4,6,8,10,12])
numbers_3 = set([3,6,9,12])
# Set 변수가 저장하고 있는 데이터의 교집합 추출
# (중복 데이터 추출)
print(numbers_2 & numbers_3)
# Set 변수가 저장하고 있는 데이터의 합집합 추출
# (중복되는 데이터는 하나만 유지)
print(numbers_2 | numbers_3)
# Set 변수가 저장하고 있는 데이터의 차집합 추출
# (서로 다른 Set 타입의 데이터에서 중복되는
# 데이터를 제거한 결과를 반환)
print(numbers_2 - numbers_3)
print(numbers_3 - numbers_2)
|
65eee29729b7d55eaafc31fa16848d2fd29296c9 | yongseongCho/python_201911 | /day_17/matplotlib_10.py | 693 | 3.875 | 4 | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
x1 = list(range(1, 101))
y1 = list(map(lambda x : x * 1.2, x1))
x2 = list(range(1, 101))
y2 = list(map(lambda x : x * 1.7, x2))
plt.title('matplotlib example')
plt.xlabel('x label')
plt.ylabel('y label')
# 다수개의 그래프를 생성하는 경우
# 서브플롯 설정 방법
# subplot 함수를 사용
# subplot(행,열,위치)
# subplot(행열위치) -> , 없이 사용할 수 있음
plt.subplot(2,2,1)
plt.plot(x1, y1, '--r', label='first')
plt.legend(loc='upper left')
plt.subplot(224)
plt.plot(x2, y2, '-.g', label='second')
plt.legend(loc='upper left')
plt.show()
|
1b296bb81cc84ad4cdf0e4f5e75096c5a06fc81a | yongseongCho/python_201911 | /day_05/if_02.py | 648 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# input 함수
# 기본 입력(키보드)을 처리할 수 있는 함수
# 변수명 = input("Message")
# Message가 화면에 출력이 되고, 키보드로 입력된 정보가
# '문자열'로 변수에 대입됨
number = input('숫자를 입력하세요 : ')
print(f'입력된 숫자는 {number} 입니다')
# input 함수를 통해서 대입된 데이터는
# 문자열 타입입니다.(str)
print(f"number's type : {type(number)}")
# 문자열을 정수로 변환
number = int(number)
if number % 2 == 1 :
print('홀수')
if number % 2 == 0 :
print('짝수')
|
df751c1729fbf8c9b16e559fd65b8bd0d5ff237d | yongseongCho/python_201911 | /day_11/exception_07.py | 1,388 | 3.90625 | 4 | # -*- coding: utf-8 -*-
class Calculator :
def __init__(self) :
# 아래의 코드는 숫자가 입력되지 않는 경우
# 예외가 발생합니다.
# 예외처리를 활용하여 숫자가 들어올때까지
# 값을 입력받도록 수정하세요.
while True :
self.n1 = input('첫번째 정수 : ')
try :
self.n1 = int(self.n1)
except :
# 예외가 발생한 경우
print(f'{self.n1}은 숫자타입이 아닙니다.')
else :
# 예외가 발생하지 않은 경우
# - 올바르게 입력된 경우 반복을 종료
break
while True :
self.n2 = input('두번째 정수 : ')
try :
self.n2 = int(self.n2)
except :
print(f'{self.n2}은 숫자타입이 아닙니다.')
else :
break
self.r = None
def plus(self) :
self.r = self.n1 + self.n2
self.display('+')
def minus(self) :
self.r = self.n1 - self.n2
self.display('-')
def display(self, op) :
print(f'{self.n1} {op} {self.n2} = {self.r}')
cal = Calculator()
cal.plus()
cal.minus()
|
75cdeb7a52fe1fdee3dbffb6670885373405fce8 | yongseongCho/python_201911 | /day_17/matplotlib_09.py | 734 | 3.5625 | 4 | # -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
x1 = list(range(1, 101))
y1 = list(map(lambda x : x * 1.2, x1))
x2 = list(range(1, 101))
y2 = list(map(lambda x : x * 1.7, x2))
plt.title('matplotlib example')
plt.xlabel('x label')
plt.ylabel('y label')
# 여러 라인을 하나의 그래프에 출력하는 경우
# 각 라인을 구분하기 위한 legend 출력 방법
# 1. plot 함수의 label 매개변수를 설정
# - 각 라인의 제목
# 2. legend 함수의 loc 매개변수를 설정하여
# 어느 위치에 출력할 것인지 지정
plt.plot(x1, y1, '--r', label='first')
plt.plot(x2, y2, '-.g', label='second')
plt.legend(loc='upper left')
plt.show()
|
223a2acb37abfe44d49fd6a11f62f23e1cd224da | yongseongCho/python_201911 | /day_17/matplotlib_11.py | 508 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# 각 구구단의 결과를 서브플롯을 사용하여
# 출력하는 예제
from matplotlib import pyplot as plt
x = list(range(1,10))
y = []
for dan in range(2, 10) :
y.append([])
for mul in range(1, 10) :
y[-1].append(dan*mul)
plt.title('GuGuDan Chart!')
for i, data in enumerate(y) :
plt.subplot(3,3,i+1)
plt.plot(x, data, '--r',
label=f'{i+2} Dan')
plt.legend(loc='best')
plt.show()
|
43d5dce8abcbe7004d305a1a25ea59152ccdd6d5 | yongseongCho/python_201911 | /day_03/list_01.py | 2,117 | 3.75 | 4 | # -*- coding: utf-8 -*-
# LIST 타입의 변수 사용
# 기존의 배열과 유사한 타입의 변수 (동적 배열)
# - 배열의 정의
# - 동일한 타입의 연속된 집합
# 비어있는 리스트 변수의 선언
list_1 = []
# 3개의 정수 요소를 가지는 리스트의 선언
list_2 = [10, 20, 30]
# 다양한 타입의 요소를 가지는 리스트 선언
# - 배열과의 차이점!
list_3 = [10, 11.5, 'Python_List', True]
print(list_1)
print(list_2)
print(list_3)
# 모든 리스트 변수들은 내부에 저장된 요소에 관계없이
# 동일한 리스트 타입으로 인식됩니다.
print(type(list_1))
print(type(list_2))
print(type(list_3))
# len 함수를 사용하여 리스트 내부의 요소 개수를
# 반환받을 수 있습니다.
print('list_1의 요소 개수 : ', len(list_1))
print('list_2의 요소 개수 : ', len(list_2))
print('list_3의 요소 개수 : ', len(list_3))
# 리스트 내부의 요소(데이터)를 접근하는 방법
# 인덱스 연산을 사용 (시작은 0)
print(list_2)
print('list_2[0] -> ', list_2[0])
print('list_2[1] -> ', list_2[1])
print('list_2[2] -> ', list_2[2])
# 범위를 벗어나는 인덱스를 사용하는 경우
# 에러가 발생됩니다.
# - IndexError
print('list_2[3] -> ', list_2[3])
# 리스트 내부에 저장된 마지막 요소에 접근하기 위해서
# -1 인덱스를 활용합니다.
print('list_2[-1] -> ', list_2[-1])
# 리스트 내부 요소의 데이터 변경
# - 특정 인덱스 위치의 데이터를 변경할 수 있음
print(list_2)
list_2[1] = 200
print(list_2)
# 리스트 변수의 슬라이싱 연산
# 리스트변수명[시작인덱스:종료인덱스]
# (종료인덱스 이전까지의 값이 추출됨)
print(list_3)
list_3_part = list_3[1:3]
print(list_3_part)
# 슬라이싱된 리스트는 원본 리스트와 분리됩니다.
# (슬라이싱된 리스트의 데이터를 수정해도 원본
# 리스트의 데이터에는 영향이 없습니다.)
list_3_part[0] = 111
print(list_3_part)
print(list_3)
|
5182e61a1fbf2b9a45709e8a7f6d5f781a6b0967 | yongseongCho/python_201911 | /day_10/class_12.py | 947 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# 구구단 클래스를 작성하세요.
# 구구단 클래스에는 두개의 메소드를 포함합니다.
# printAll 메소드와 printOne 메소드
# printAll 메소드는 매개변수가 없으며, 호출되면
# 전체 구구단을 출력
# printOne 메소드는 하나의 정수형 매개변수가
# 있으며, 호출되면 전달된 매개변수의 구구단 출력
class GuGuDan :
def printAll(self) :
print('printAll 메소드 실행')
for dan in range(2,10) :
print(f'{dan}단을 출력합니다.')
for mul in range(1, 10) :
print(f'{dan} * {mul} = {dan*mul}')
def printOne(self, dan) :
print(f'{dan}단을 출력합니다.')
for mul in range(1, 10) :
print(f'{dan} * {mul} = {dan*mul}')
gugudan = GuGuDan()
#gugudan.printAll()
gugudan.printOne(3)
|
f503a76cf01ef51bc080e7b543fc1ed792585945 | yongseongCho/python_201911 | /day_10/class_10.py | 2,234 | 3.5625 | 4 | # -*- coding: utf-8 -*-
class Animal :
def __init__(self, name, age, color) :
self.name = name
self.age = age
self.color = color
def showInfo(self) :
print(f'name : {self.name}')
print(f'age : {self.age}')
print(f'color : {self.color}')
# 생성자 재정의(오버라이딩)를 통한
# 상속 문법 구현
class Dog (Animal) :
def __init__(self, name, age, color, power) :
# 자식클래스에서 부모클래스의 생성자를
# 사용하지 않고 새롭게 생성자를 정의하는 경우
# 부모클래스의 생성자를 명시적으로 호출하여
# 부모클래스의 인스턴스 변수들이 올바르게
# 생성될 수 있도록 해야합니다.
self.power = power
# super() 함수는 부모클래스에 접근하기 위한
# 참조값을 반환하는 함수
# 1. 부모 클래스의 생성자 호출
# 2. 오버라이딩된 부모클래스의 메소드 호출
super().__init__(name, age, color)
# 부모클래스로부터 물려받은 showInfo 메소드는
# power 값을 출력할 수 없음
# 이러한 경우 부모클래스를 새롭게 재정의하여
# 사용할 수 있습니다. (메소드 오버라이딩)
# 메소드 오버라이딩을 구현하면 부모의 메소드는
# 무시되고 오버라이딩된 자식클래스의 메소드가
# 호출됩니다.
def showInfo(self) :
# super()를 사용하여 부모클래스의
# 오버라이딩된 메소드를 호출할 수 있습니다.
super().showInfo()
print(f'power : {self.power}')
class Cat (Animal) :
def __init__(self, name, age, color, speed) :
super().__init__(name, age, color)
self.speed = speed
def showInfo(self) :
super().showInfo()
print(f'speed : {self.speed}')
d = Dog('바둑이', 10, '흰색',
'무는힘이 아주 강해요...')
c = Cat('나비', 3, '검은색',
'너무 빨라서 잡을수가 없어요...')
d.showInfo()
c.showInfo()
|
3209947bf5e2e8f33dd65561744ecc8380faf4ab | aziaziazi/Euler | /problem 2.py | 235 | 3.765625 | 4 | def sum_fibonacci_not_even():
fib = [1,1]
total = 0
while fib[-1]<4000000:
to_add = fib[-1]+fib[-2]
fib.append(to_add)
if not fib[-1] % 2:
total+=to_add
fib[-1] = 0
print fib
return total
print sum_fibonacci_not_even()w |
7dce36f488376f1961ce6a822b3eda6885291e9f | faeze20/python_examples | /Level3_Examples/all_files_and_directories.py | 202 | 3.78125 | 4 | # list all files and directories
import os
def list_dir(directory):
a = os.listdir(directory)
for i, item in enumerate(a): # All files
print(i, ': ', item)
list_dir(current_dir)
|
44b220ae1398959dfb28f17c78eb558db4c59387 | qtdwzAdam/leet_code | /py/back/work_529.py | 2,137 | 3.5625 | 4 | class Solution(object):
lenx = 0
leny = 0
def set_val(self, board, point, val):
try:
board[point[0]][point[1]] = val
except:
board[point[0]] = board[point[0]][:point[1]] + str(val) + board[point[0]][point[1]+1:]
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
if not board: return board
Solution.lenx = len(board)
Solution.leny = len(board[0])
if board[click[0]][click[1]] == 'M':
self.set_val(board, click, 'X')
return board
self.dfs_check(board, click)
return board
def dfs_check(self, board, point):
if not( 0 <= point[0] < Solution.lenx and 0 <= point[1] < Solution.leny):
return
if board[point[0]][point[1]] not in ['M', 'E']:
return
around_cnt = self.check_around(board, point)
if around_cnt != 0:
self.set_val(board, point, str(around_cnt))
else:
self.set_val(board, point, 'B')
for one_around in self.around_points(point):
self.dfs_check(board, one_around)
def check_one(self, board, point):
if board[point[0]][point[1]] == 'M':
return 1
return 0
def _aroud_points(self, point):
return [
[point[0]-1, point[1]-1],
[point[0]-1, point[1]],
[point[0]-1, point[1]+1],
[point[0], point[1]-1],
[point[0], point[1]+1],
[point[0]+1, point[1]-1],
[point[0]+1, point[1]],
[point[0]+1, point[1]+1],
]
def around_points(self, ori_point):
for point in self._aroud_points(ori_point):
if 0 <= point[0] < Solution.lenx and 0 <= point[1] < Solution.leny:
yield point
def check_around(self, board, point):
cnt = 0
for one_around in self.around_points(point):
cnt += self.check_one(board, one_around)
return cnt
|
25fb291063dade9bb682e0657107aee6c37b07c6 | qtdwzAdam/leet_code | /py/202211/61.旋转链表.py | 1,541 | 3.65625 | 4 | #
# @lc app=leetcode.cn id=61 lang=python
#
# [61] 旋转链表
#
# @lc code=start
# 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 rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
first = head
second = head
cnt = 0
while second and cnt < k:
second = second.next
cnt += 1
if cnt < k:
k = k % cnt
first = head
second = head
cnt = 0
while second and cnt < k:
second = second.next
cnt += 1
if not second:
return head
while second.next:
first = first.next
second = second.next
second.next = head
head = first.next
first.next = None
return head
# @lc code=end
def main():
from listinit import init_list, print_list
x = Solution().rotateRight(init_list([1, 2]), 2)
print(print_list(x) == [1,2])
x = Solution().rotateRight(init_list([1, 2]), 1)
print(print_list(x) == [2,1])
x = Solution().rotateRight(init_list([1,2,3,4,5]), 2)
print(print_list(x) == [4,5,1,2,3])
x = Solution().rotateRight(init_list([0,1,2]), 4)
print(print_list(x) == [2,0,1])
if __name__ == '__main__':
main()
|
b0105281f59f1073588379fd1897e0bab3b49e53 | qtdwzAdam/leet_code | /py/202211/445.py | 1,691 | 3.96875 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
import Queue
s1 = Queue.LifoQueue()
s2 = Queue.LifoQueue()
while l1:
s1.put(l1.val)
l1 = l1.next
while l2:
s2.put(l2.val)
l2 = l2.next
rtn_head = ListNode(0)
list_tmp = rtn_head
inc = 0
while True:
if s1.isEmpty() and s2.isEmpty():
if inc == 1:
list_tmp.next = ListNode(inc)
break
elif s1.isEmpty():
new_val = s2.get() + inc
elif s2.isEmpty():
new_val = s1.get() + inc
else:
new_val = s1.get() + s2.get() + inc
new_ele = ListNode(new_val % 10)
inc = new_val / 10;
list_tmp.next = new_ele
list_tmp = new_ele
return rtn_head
|
975bc50899cf75c023d9d505946ee915c19f3ccd | qtdwzAdam/leet_code | /py/back/work_721.py | 765 | 3.515625 | 4 | from pprint import pprint
class Solution(object):
def accountsMerge(self, accounts):
"""
:type accounts: List[List[str]]
:rtype: List[List[str]]
"""
val = sorted(accounts, key=lambda x: x[0])
output = [val[0]]
for x in val[1:]:
flag_match = False
for y in output:
if x[0] == y[0]:
if any(tmp in y[1:] for tmp in x[1:]):
y.extend(x[1:])
flag_match = True
break
if not flag_match:
output.append(x)
for x in output:
x[1:] = sorted(list(set(x[1:])))
print 'myoutput is:'
pprint(output)
return output
|
5ac31df1a7457d4431e7c8fbdc1892bf02d393d0 | qtdwzAdam/leet_code | /py/back/work_405.py | 1,282 | 4.53125 | 5 | # -*- coding: utf-8 -*-
#########################################################################
# Author : Adam
# Email : zju_duwangze@163.com
# File Name : work_405.py
# Created on : 2019-08-30 15:26:20
# Last Modified : 2019-08-30 15:29:47
# Description :
# Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
#
# Note:
#
# All letters in hexadecimal (a-f) must be in lowercase.
# The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
# The given number is guaranteed to fit within the range of a 32-bit signed integer.
# You must not use any method provided by the library which converts/formats the number to hex directly.
# Example 1:
#
# Input:
# 26
#
# Output:
# "1a"
# Example 2:
#
# Input:
# -1
#
# Output:
# "ffffffff"
#########################################################################
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
def main():
return 0
if __name__ == '__main__':
main()
|
af6c0853be598ba91d3f49818be9de56458064e8 | qtdwzAdam/leet_code | /py/202211/143.重排链表.py | 1,337 | 3.84375 | 4 | #
# @lc app=leetcode.cn id=143 lang=python
#
# [143] 重排链表
#
# @lc code=start
# 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 reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next:
return head
from collections import deque
q = deque()
root = head
while root:
q.append(root)
root = root.next
root = q.popleft()
while True:
if len(q) == 0:
break
right = q.pop()
root.next = right
root = right
if len(q) == 0:
break
left = q.popleft()
root.next = left
root = left
root.next = None
return head
# @lc code=end
def main():
from listinit import init_list, print_list
x = Solution().reorderList(init_list([1,2,3,4]))
print(print_list(x) == [1,4,2,3])
x = Solution().reorderList(init_list([1,2,3,4,5]))
print(print_list(x) == [1,5,2,4,3])
if __name__ == '__main__':
main()
|
317dc1d9bd27a116e57e4ce4ca061b379801bae6 | qtdwzAdam/leet_code | /py/202211/421.py | 1,399 | 3.5 | 4 | # coding=utf-8
"""
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8]
Output: 28
Explanation: The maximum result is 5 ^ 25 = 28.
"""
class Solution(object):
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1: return 0
max_num = max(nums)
bin_max = bin(max_num)
len_max = len(bin_max)
list_check = []
base_idx = 0
for idx in range(3, len_max):
print bin_max[idx]
if base_idx:
tmp_check = [x for x in list_check if bin(x)[2 + idx - base_idx] != bin_max[idx]]
if len(tmp_check) == 1:
return max_num ^ tmp_check[0]
elif not tmp_check:
continue
list_check = tmp_check
elif bin_max[idx] == '0':
if not list_check:
list_check = [x for x in nums if len(bin(x)) == len_max - idx + 2]
base_idx = idx
if len(list_check) == 1:
return max_num ^ list_check[0]
if __name__ == '__main__':
sol = Solution()
nums = [0, 8]
print sol.findMaximumXOR(nums)
|
84c61b1c48b90fee9cd509092a85cd8dff23de00 | ojffjo/hello | /games.py | 1,668 | 4 | 4 | # Guessing Game
# win_num = 7
# guess_count = 1
# guess_limit = 3
# while guess_count <= guess_limit:
# guess_num = int(input("Guess: "))
# if guess_num == win_num:
# print('You won!')
# break
# if guess_count < 3:
# print("Try again!")
# guess_count += 1
# else:
# print('Sorry, you failed!')
# Car Game
car_started = False
while True:
command = input('> ').lower()
if command == 'help':
msg = 'Start - to start the car\nStop - to stop the car\nQuit - to quit the car\n'
print(msg)
elif command == 'start':
if car_started:
msg = 'Car already started!\n'
print(msg)
else:
msg = 'Car started .... ready to go.\n'
car_started = True
print(msg)
# elif command == 'start' and not car_started:
# msg = 'Car started .... ready to go.\n'
# car_started = True
# print(msg)
# elif command == 'start' and car_started:
# msg = 'Car already started!\n'
# print(msg)
elif command == 'stop':
if car_started:
msg = 'Car stopped.\n'
car_started = False
print(msg)
else:
msg = 'Car already stopped.\n'
print(msg)
# elif command == 'stop' and car_started:
# msg = 'Car stopped.\n'
# car_started = False
# print(msg)
# elif command == 'stop' and not car_started:
# msg = 'Car already stopped.\n'
# print(msg)
elif command == 'quit':
print('See you later!')
break
else:
msg = "Oops! I don't understand that.\n"
print(msg)
|
4db43a5be07d760c4feb1346c74d3bc80228880c | vc2309/interview_prep | /data_structures/string_compression.py | 376 | 3.859375 | 4 | def compress(a):
ln = len(a)
if not ln:
return
char = a[0]
count = 1
compressed = char
for i in range(1,ln):
if char!=a[i]:
compressed+=str(count)
count=1
char=a[i]
compressed+=char
else:
count+=1
compressed+=str(count)
return compressed
def main():
word = raw_input("Enter string \n")
print(compress(word))
if __name__ == '__main__':
main() |
2ea19e7b023b6945d34d2a164a5bd668ff5aefb6 | vc2309/interview_prep | /dp/steps.py | 458 | 3.90625 | 4 | def steps(steps_left, steps_counts,hashmap):
if steps_left==0:
return 1
elif steps_left<0:
return 0
if not hashmap.get(steps_left):
hashmap[steps_left]=0
for i in steps_counts:
if i<=steps_left:
hashmap[steps_left]+=steps(steps_left-i,steps_counts,hashmap)
return hashmap[steps_left]
def main():
steps_counts=[1,2,3]
steps_left=int(input("eNTER num steps"))
print (steps(steps_left,steps_counts,{}))
if __name__ == '__main__':
main() |
4b47cd1d45c5a4a1a5587b8f14d48b896eab145b | vc2309/interview_prep | /dp/knapsack.py | 515 | 3.796875 | 4 | def knapsack(W, weights, values):
K={w:v for w,v in zip(weights,values)}
for i in range(W+1):
max_weight=0
for j,wi in enumerate(weights):
if wi <=i:
rem_val=K.get(i-wi) if K.get(i-wi) else 0
max_weight=max(rem_val+wi,rem_val)
K[i]=max_weight
return K[W]
def main():
weights=[2,2,3,4]
values=[10,40,30,100]
print("Weight\tValue")
for w,v in zip(weights,values):
print(str(w)+"\t"+str(v))
W=int(input("Enter weight"))
print(knapsack(W,weights,values))
if __name__ == '__main__':
main() |
4b3ce42dde5e951efe9620bfce24c01f380715e7 | gauravtatke/codetinkering | /leetcode/LC110_balanced_bintree.py | 2,087 | 4.3125 | 4 | # Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as:
# a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Example 1:
# Given the following tree [3,9,20,null,null,15,7]:
# 3
# / \
# 9 20
# / \
# 15 7
# Return true.
# Example 2:
# Given the following tree [1,2,2,3,3,null,null,4,4]:
# 1
# / \
# 2 2
# / \
# 3 3
# / \
# 4 4
# Return false
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution1:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
hleft = self.height(root.left)
hright = self.height(root.right)
if abs(hleft - hright) > 1 and self.isBalanced(
root.left) and self.isBalanced(root.right):
return True
return False
def height(self, root):
if root is None:
return 0
return max(self.height(root.left), self.height(root.right)) + 1
class Solution2:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# another way is to return height at each recursion and -1 if it is un-balanced.
# no need to traverse tree twice, once for height and once for isBalance as in above solution
height = self.heightBalance(root)
if height == -1:
return False
return True
def heightBalance(self, root):
if root is None:
return 0
left_height = self.heightBalance(root.left)
if left_height == -1:
return -1
right_height = self.heightBalance(root.right)
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
|
b58fc479c49beea872b3e36ad186884341a00d28 | gauravtatke/codetinkering | /leetcode/LC72_edit_distance.py | 3,594 | 3.859375 | 4 | # Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
#
# You have the following 3 operations permitted on a word:
#
# a) Insert a character
# b) Delete a character
# c) Replace a character
class Solution1(object):
# this is my solution - DOES NOT WORK
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
# calculate max index and length of maximum contiguous match in word1
# and word2. Then calculate number of prefix and suffix operations
# needed to convert. Total operation = prefix_op + suffix_op
len1 = len(word1)
len2 = len(word2)
grid = [[0 for i in range(len1 + 1)] for j in range(len2 + 1)]
maxi = maxj = 0
max_cnt = 0
for i, char2 in enumerate(word2):
for j, char1 in enumerate(word1):
if char1 == char2:
# match occurs. see if total match is greater than max_cnt
if grid[i][j] + 1 > max_cnt: # grid[i][j] is prev row,col
max_cnt = grid[i][j] + 1
maxi, maxj = i, j
# grid has extra row and column
grid[i + 1][j + 1] = max_cnt
if max_cnt:
# if there is a match
prefix1_char = maxj - max_cnt + 1 # num of characters before the start of match
prefix2_char = maxi - max_cnt + 1
prefix_op = max(prefix1_char, prefix2_char)
suffix1_char = len1 - maxj - 1
suffix2_char = len2 - maxi - 1
suffix_op = max(suffix2_char, suffix1_char)
return prefix_op + suffix_op
# if no match, then largest length is ans
return max(len1, len2)
class Solution2(object):
# DP solution
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
# let dp[i][j] is min step required to convert word1[0..i-1] to word2[0..j-1].
# i, j start from 1 in this notation
# boundary condition -
# case 1: convert empty string to a string -> j insertions
# case 2: convert string to an empty string -> i deletions
# non-edge case - convert word1[0..i-1] to word2[0..j-1]. suppose we
# know how to convert word1[0..i-2] to word2[0..j-2] i.e. dp[i-1][j-1]
# then following cases arise
# 1. if word1[i-1] == word2[j-1], then dp[i][j] = dp[i-1][j-1].
# 2. if word1[i-1] != word2[j-1], then we can either -
# 2a. replace word1[i-1] with word2[j-1], dp[i][j] = dp[i-1][j-1] + 1, or
# 2b. delete word1[i-1] and just convert word1[0..i-2] to word2[0..j-1], dp[i][j] = dp[i-1][j] + 1, or
# 2c. insert word2[j-1] to word1[0..i-1] such that word1[0..i-1] +
# word2[j-1] = word2[0..j-1], dp[i][j] = dp[i][j-1] + 1
m, n = len(word1), len(word2)
dp = [[0 for j in range(n + 1)] for i in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i # boundary case 2
for j in range(n + 1):
dp[0][j] = j # boundary case 1
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1]
[j], dp[i][j - 1]) + 1
return dp[m][n]
|
c28bff4e76406f1c4742988db3b90ddcf792bc65 | gauravtatke/codetinkering | /leetcode/singlenumber.py | 611 | 3.8125 | 4 | #!/usr/bin/env python3
# Given an array of integers, every element appears twice except for one. Find
# that single one.
#
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it
# without using extra memory?
def singleNumber(nums):
nu = 0
for n in nums:
nu = nu ^ n
return nu
def singleNumber2(nums):
adict = {}
for nu in nums:
if nu in adict:
del adict[nu]
else:
adict[nu] = None
return adict.popitem()[0]
def main():
print(singleNumber([4,5,6,7,3,2,1,4]))
if __name__ == '__main__':
main()
|
32a89094e2c55e2a5b13cf4a52a1cf6ef7206894 | gauravtatke/codetinkering | /leetcode/LC98_validate_BST.py | 798 | 4.21875 | 4 | # Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a 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.
def isValidBST(root):
def isValid(root, minNode, maxNode):
# define the min and max between which the node val should be
if root is None:
return True
if (minNode and minNode.val >= root.val) or (maxNode and maxNode.val <= root.val):
return False
return isValid(root.left, minNode, root) and isValid(root.right, root, maxNode)
return isValid(root, None, None)
|
996e3858f7eb3c4a8de569db426c2f9cdd5fd71a | gauravtatke/codetinkering | /dsnalgo/firstnonrepeatcharinstring.py | 1,292 | 4.15625 | 4 | #!/usr/bin/env python3
# Given a string, find the first non-repeating character in it. For
# example, if the input string is “GeeksforGeeks”, then output should be
# ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.
def findNonRepeatChar(stri):
chlist = [0 for ch in range(256)]
for ch in stri:
chlist[ord(ch)] += 1
for ch in stri:
if chlist[ord(ch)] == 1:
return ch
return None
def findNonRepeatCharFromCount(str1):
# store count of char and index at which it first occured in count list
count = [[0, None] for i in range(256)]
for i, ch in enumerate(str1):
count[ord(ch)][0] += 1
if not count[ord(ch)][1]:
# if index is None, set it else leave as it is
count[ord(ch)][1] = i
# now only traverse count list i.e. 256 elements instead of whole string
# again which could be very long
maxi = 257
result = None
for cnt, indx in count:
if cnt == 1 and indx < maxi:
result = str1[indx]
maxi = indx
return result
def main(argv):
print(findNonRepeatChar(argv[0]))
print(findNonRepeatCharFromCount(argv[0]))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv[1:]))
|
f0e6eaf2e6f2d0eb0b1cc41b04bee13afdda08ef | gauravtatke/codetinkering | /dsnalgo/matrixchain.py | 2,582 | 3.5 | 4 | #!/usr/bin/env python3
'''
Matrix chain = <A1 A2 A3 .... Ai .... An>
Each Ai matrix has dimension = Pi-1 X Pi
So index chain = <P0 P1 P2...Pi-1 Pi....Pn>
cost[i, j] = array cost[1..n-1, 1..n-1], cost of multiplying Ai to Aj
sol[i, j] = array sol[1..n-1, 2...n] is array where value of 'K' is stored. K
is index where to parenthesize for a given i, j
P.length = n+1
'''
def recur_mat_chain_mult(p, i, j):
#print(i, j)
if i == j:
return 0
cost[i][j] = float('inf')
for k in range(i, j):
q = recur_mat_chain_mult(p, i, k) + \
recur_mat_chain_mult(p, k+1, j) + p[i-1]*p[k]*p[j]
if q < cost[i][j]:
cost[i][j] = q
return cost[i][j]
def matrix_chain_order(p):
cost = [[0 for i in p] for j in p]
sol = [[0 for i in p] for j in p]
n = len(p)-1
#for i in range(1, n+1):
# cost[i][i] = 0
for length in range(2, n+1):
#for len = 2, calculate cost[1, 2], cost[2, 3] ...
#for len = 3, calculate cost[1, 3], cost[2, 4] ...
for i in range(1, n-length+2): #add xtra 1 cuz range excludes last num
j = i+length-1
cost[i][j] = float('inf')
for k in range(i, j):
min_val = cost[i][k] + cost[k+1][j] + p[i-1]*p[k]*p[j]
if min_val < cost[i][j]:
cost[i][j] = min_val
sol[i][j] = k
return cost, sol
def print_optimal_parens(sol, i, j):
if i == j:
print('A'+str(i), end='')
else:
print('(', end='')
print_optimal_parens(sol, i, sol[i][j])
print_optimal_parens(sol, sol[i][j]+1, j)
print(')', end='')
def memoized_matrix_chain(p):
n = len(p)-1
cost = [[float('inf') for i in p] for j in p]
return lookup_chain(p, cost, 1, n)
def lookup_chain(p, cost, i, j):
if cost[i][j] < float('inf'):
return cost[i][j]
if i == j:
cost[i][j] = 0
else:
for k in range(i, j):
min_val = lookup_chain(p, cost, i, k) + \
lookup_chain(p, cost, k+1, j) + p[i-1]*p[k]*p[j]
if min_val < cost[i][j]:
cost[i][j] = min_val
return cost[i][j]
if __name__ == '__main__':
p1 = [10, 100, 5, 50]
p2 = [30, 35, 15, 5, 10, 20, 25]
cost = [[0 for i in p2] for j in p2]
#print(cost)
print(recur_mat_chain_mult(p2, 1, len(p2)-1))
print(memoized_matrix_chain(p2))
#print(cost)
#cost, sol = matrix_chain_order(p1)
#print('cost = ', cost[1][len(p1)-1])
#print_optimal_parens(sol, 1, len(p1)-1)
print()
|
c106671082f8f393f73ebad1a355929e142cfdc6 | gauravtatke/codetinkering | /leetcode/LC345_reverse_vowelsof_string.py | 739 | 4.28125 | 4 | # Write a function that takes a string as input and reverse only the vowels of a string.
#
# Example 1:
# Given s = "hello", return "holle".
#
# Example 2:
# Given s = "leetcode", return "leotcede".
#
# Note:
# The vowels does not include the letter "y".
def reverseVowels(s):
lstr = list(s)
i = 0
j = len(lstr) - 1
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
while i < j:
while i < j and lstr[i] not in vowels:
i = i + 1
while i < j and lstr[j] not in vowels:
j = j - 1
lstr[i], lstr[j] = lstr[j], lstr[i]
# print(i, j)
i = i + 1
j = j - 1
return ''.join(lstr)
if __name__ == '__main__':
print(reverseVowels('hello'))
|
67deb25bab0acaf56f9cd127c47627afda9b8f11 | gauravtatke/codetinkering | /leetcode/LC456_pattern321.py | 1,928 | 3.84375 | 4 | # Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj.
# Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
# Note: n will be less than 15,000.
# Example 1:
# Input: [1, 2, 3, 4]
# Output: False
# Explanation: There is no 132 pattern in the sequence.
# Example 2:
# Input: [3, 1, 4, 2]
# Output: True
# Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
# Example 3:
# Input: [-1, 3, 2, 0]
# Output: True
# Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
return self.find132pattern_smarter_bruteforce(nums)
def find132pattern_bruteforce(self, nums: List[int]) -> bool:
# consider all triplets and find
if len(nums) < 3:
return False
for i in range(len(nums)-2):
for j in range(i+1, len(nums)-1):
for k in range(j+1, len(nums)):
if nums[k] > nums[i] and nums[k] < nums[j]:
return True
return False
def find132pattern_smarter_bruteforce(self, nums: List[int]) -> bool:
# chances of finding num[k] such that its between num[i] & num[j]
# increase if the range of i and j is large. So instead of finding i,j, k
# we can just find num[j] and num[k] but keep a minimum num[i] for
# each num[j]. In other words for each j, store num[i] which is min in range
# 0 to j
if len(nums) < 3:
return False
min_i = nums[0]
for j in range(1, len(nums)-1):
min_i = min(min_i, nums[j])
for k in range(j+1, len(nums)):
if nums[k] < nums[j] and nums[k] > min_i:
return True
return False |
0d37f87ebde2412443f7fefbf53705ac0f03b019 | gauravtatke/codetinkering | /dsnalgo/lengthoflongestpalindrome.py | 2,308 | 4.1875 | 4 | #!/usr/bin/env python3
# Given a linked list, the task is to complete the function maxPalindrome which
# returns an integer denoting the length of the longest palindrome list that
# exist in the given linked list.
#
# Examples:
#
# Input : List = 2->3->7->3->2->12->24
# Output : 5
# The longest palindrome list is 2->3->7->3->2
#
# Input : List = 12->4->4->3->14
# Output : 2
# The longest palindrome list is 4->4
class SllNode:
def __init__(self, val=None):
self.key = val
self.nextp = None
def __str__(self):
return str(self.key)
def createlist(alist):
head = tail = None
for val in alist:
if tail:
tail.nextp = SllNode(val)
tail = tail.nextp
else:
head = tail = SllNode(val)
tail.nextp = SllNode() # just put dummy node at end so that comparisons are easy.
return head
def printlist(head):
curr = head
while curr.key:
print(curr, end='->')
curr = curr.nextp
print(None)
def findMaxPalindromeLen(head):
# reverse the linked list at each node and traverse from that node in opp
# directions.
curr = head
prev = SllNode()
maxlen = 0
while curr.key:
nxt = curr.nextp
curr.nextp = prev
# now from curr traverse back and forward and check if palindrome exists. if exists then get the length.
# first check for odd length palindrome from curr
i = prev
j = nxt
currmax = 1
while i.key == j.key:
# print('i == j for odd')
currmax += 2
i = i.nextp if i else None
j = j.nextp if j else None
maxlen = max(maxlen, currmax)
# now check for even length palindrome starting at curr and nxt
i = curr
j = nxt
currmax = 0
while i.key == j.key:
currmax += 2
i = i.nextp if i else None
j = j.nextp if j else None
maxlen = max(maxlen, currmax)
prev = curr
curr = nxt
return maxlen
def main():
alist1 = [2, 3, 7, 3, 2, 12, 24]
alist2 = [12, 4, 4, 3, 14]
alist3 = [1,2,3,6,3,9,6,6,9,3]
head = createlist(alist3)
printlist(head)
print(findMaxPalindromeLen(head))
if __name__ == '__main__':
main()
|
24d9612dd09f954cad68397e915827d60daedc91 | gauravtatke/codetinkering | /dsnalgo/Inversion.py | 2,160 | 3.59375 | 4 | def find_inversion_brute(numlist, beg, end):
#This counts inversion and also stores indices where it occurs.
#This is brute force and solves all problem space
i = beg-1
count = 0
inver_indice = []
for index1, elem1 in enumerate(numlist[beg:end+1], start=beg):
i = i+1
for index2, elem2 in enumerate(numlist[i+1:end+1], start=i+1):
if elem1 > elem2:
count = count+1
inver_indice.append((index1, index2))
#print(elem1, elem2)
return (count, inver_indice)
#print('Count = {0}, Inversion = {1}'.format(count, inver_indices))
def count_inversion(numlist, beg, mid, end):
l = numlist[beg:mid+1]
n1 = len(l)
l.append(float('inf'))
r = numlist[mid+1:end+1]
r.append(float('inf'))
i = j = 0
count_inversion = 0
counted = False
for k in range(beg,end+1):
while not counted and l[i] > r[j]:
#To remove inversion involving inf, count inversion as soon new
#value of r[j] is exposed
count_inversion = count_inversion+n1-i
counted = True
if l[i] <= r[j]:
#No inversion
numlist[k] = l[i]
i = i+1
else:#Inversion occurs
numlist[k] = r[j]
j = j+1
counted = False #set to False once new value is exposed
return count_inversion
def find_inversion_merge(numlist, beg, end):
#This algo only counts the inversion and is based on merge sort algo
inv_count = 0
if beg < end:
mid = (beg+end)//2
inv_count = inv_count + find_inversion_merge(numlist, beg, mid)
inv_count = inv_count + find_inversion_merge(numlist, mid+1, end)
inv_count = inv_count + count_inversion(numlist, beg, mid, end)
return inv_count
if __name__ == '__main__':
numlist = [3, 4, 2, 5, 9, 7, 1, 6]
count, indice = find_inversion_brute(numlist, 1, 6)
print('Count = {0}, \nInversion = {1}'.format(count, indice))
count = find_inversion_merge(numlist, 1, 6)
print('Count = {0}'.format(count))
|
8d9bb6926f1bd85ef8da53778229913d6ac4bc86 | gauravtatke/codetinkering | /dsnalgo/sort_pile_of_cards.py | 1,047 | 4.125 | 4 | #!/usr/bin/env python3
# We have N cards with each card numbered from 1 to N. All cards are randomly shuffled. We are allowed only operation moveCard(n) which moves the card with value n to the top of the pile. You are required to find out the minimum number of moveCard() operations required to sort the cards in increasing order.
def minMove(arr):
# start iterating from back and count number of elements already in descending order.
# minimum movement to sort will be n-(num of elem in desc ord) because only those elem need to move
# for e.g. 4, 2, 5, 1, 6, 3 item in desc ord are 3 i.e.{6, 5, 4} so 6 - 3 = 3 movement to sort.
# moveCard(3) -> moveCard(2) -> moveCard(1)
n = len(arr)
count = 0
for i in arr[-1::-1]:
if i == n:
count += 1
n -= 1
return len(arr)-count
def main():
arr1 = [4, 2, 5, 1, 6, 3]
arr2 = [5, 1, 2, 3, 4]
arr3 = [3, 4, 2, 1]
print(minMove(arr1))
print(minMove(arr2))
print(minMove(arr3))
if __name__ == '__main__':
main()
|
8eb6703ee0ed6b69c41c76997764704beca2b6cb | gauravtatke/codetinkering | /leetcode/LC13_roman_to_int.py | 792 | 3.515625 | 4 | from __future__ import annotations
roman_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
class Solution:
def romanToInt(self, s: str) -> int:
result_int = 0
prev = None
for curr in s[-1::-1]:
if (prev in ('V', 'X') and curr == 'I') or (prev in ('L', 'C') and curr == 'X') or (prev in ('D', 'M') and curr == 'C'):
result_int = result_int - roman_dict[curr]
else:
result_int = result_int + roman_dict[curr]
prev = curr
return result_int
if __name__ == '__main__':
roman = 'MCMXCIV'
solution = Solution()
print(f'Roman {roman} to int {solution.romanToInt(roman)}') |
0a8c8f7a39093295d7a28db592033996006ad7a8 | gauravtatke/codetinkering | /leetcode/LC26_remove_duplicates_sorted_array.py | 1,576 | 3.84375 | 4 | #Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
#
#Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#
#Example 1:
#
#Given nums = [1,1,2],
#
#Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
#
#It doesn't matter what you leave beyond the returned length.
#
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
return self.removeDuplicates_sol2(nums)
def removeDuplicates_sol1(self, nums: List[int]) -> int:
if nums == None or len(nums) == 0:
return 0
unik = nums[0]
i = 1
while i < len(nums):
if nums[i] == unik:
# remove ith number and don't increment i
nums.pop(i)
else:
unik = nums[i]
i += 1
return len(nums)
def removeDuplicates_sol2(self, nums: List[int]) -> int:
if nums == None or len(nums) == 0:
return 0
next_uniq_loc = 1
for curr_loc in range(1, len(nums)):
if nums[curr_loc] != nums[curr_loc-1]:
# means nums[curr_loc] is next uniq element
# should be copied to next_uniq_loc
nums[next_uniq_loc] = nums[curr_loc]
next_uniq_loc += 1
# next_uniq_loc is the length of the uniq array
# we don't need to remove other elements
return next_uniq_loc
|
a783b4053b012143e18b6a8bd4335a8b84b5d031 | gauravtatke/codetinkering | /leetcode/LC433_min_gene_mut.py | 2,495 | 4.15625 | 4 | # A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
# Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
# Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
# Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.
# Note:
# Starting point is assumed to be valid, so it might not be included in the bank.
# If multiple mutations are needed, all mutations during in the sequence must be valid.
# You may assume start and end string is not the same.
# Example 1:
# start: "AACCGGTT"
# end: "AACCGGTA"
# bank: ["AACCGGTA"]
# return: 1
# Example 2:
# start: "AACCGGTT"
# end: "AAACGGTA"
# bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
# return: 2
# Example 3:
# start: "AAAAACCC"
# end: "AACCCCCC"
# bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
# return: 3
from collections import deque
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
bankset = set(bank)
visited = set()
dq = deque()
dq.append(start)
level = 0
while dq:
size = len(dq)
while size:
gene = dq.popleft()
if gene == end:
return level
gene_list = list(gene)
for i, ch in enumerate(gene_list):
# oldchar = ch
for repch in ('A', 'C', 'G', 'T'):
gene_list[i] = repch
# print(gene_list)
mut_gene_str = ''.join(gene_list)
if mut_gene_str in bankset and mut_gene_str not in visited:
visited.add(mut_gene_str)
dq.append(mut_gene_str)
gene_list[i] = ch
size -= 1
level += 1
return -1
def main():
retval = Solution().minMutation("AACCGGTT", "AACCGGTA", ["AACCGGTA"])
print(retval)
if __name__ == '__main__':
main() |
a673b6f976960ce66dbaa76ccefeb71d0f423ca1 | gauravtatke/codetinkering | /leetcode/LC141_linked_list_cycle.py | 2,520 | 4.09375 | 4 | #Given a linked list, determine if it has a cycle in it.
#
#To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
#
#Example 1:
#
#Input: head = [3,2,0,-4], pos = 1
#Output: true
#Explanation: There is a cycle in the linked list, where tail connects to the second node.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
return self.hasCycle_sol3(head)
def hasCycle_sol1(self, head: ListNode) -> bool:
# brute force approach
# in case cycle is at head, we need to create dummy node
# which points head and start from there
curr = head
while curr is not None:
# if list has no cycle then curr reaches end
# start a runner from head always. If there is a point
# where runner.next == curr.next and runner != curr then
# there is cycle
runner = head
while runner.next != head and runner.next != curr.next and runner.next != runner:
runner = runner.next
if runner.next == head or runner.next == runner or runner != curr:
# cycle at head or tail
return True
else:
# no cycle, just move curr and continue loop
curr = curr.next
return False # when curr reaches end, no cycle found
def hasCycle_sol2(self, head: ListNode) -> bool:
# using hash set
visited = set()
while head is not None:
if head in visited:
return True
else:
visited.add(head)
head = head.next
return False
def hasCycle(self, head: ListNode) -> bool:
# using 2 pointers
# fast and slow pointer. If fast becomes None
# then there is no cycle otherwise fast and slow
# will meet somewhere
if head is None or head.next is None:
return False
slow = head
fast = head.next
while (slow != fast):
if fast is None or fast.next is None:
return False
slow = slow.next
fast = fast.next.next
#if loop finishes then slow == fast
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.