text
stringlengths 37
1.41M
|
---|
# Faça um programa que pede para o usuário digitar uma palavra e cria uma nova string igual, porém com espaço entre cada letra, depois imprima a nova string:
# Exemplo: se o usuário digitar "python" o programa deve imprimir "p y t h o n "
import re
# string de entrada
string = input('Digite uma palavra:')
# quebra a string, mas inclui strings vazias
lista = re.split("(\S{1})", string)
# remove strings vazias, deixa apenas o que interessa
final = list(filter(None, lista))
x = ' '.join(final)
print(final)
print(x)
|
# Super Desafio! - Repita o exercício anterior usando recursão, ou seja,
# uma função que chame ela mesma, lembrando que 3! = 3*2!, que 2! = 2*1!, que 1! = 1*0! e que 0! = 1.
n = int(input('Digite um número para que seu fatorial seja calculado:\n'))
def fatorial(n):
if n < 2:
return 1
else:
return n * fatorial(n-1)
print(fatorial(n))
|
# Crie uma classe ControleRemoto cujo atributo é televisão
# (isso é, recebe um objeto da classe do exercício 4).
# Crie métodos para aumentar/diminuir volume, trocar o canal
# e sintonizar um novo canal, que adiciona um novo canal à lista
# de canais (somente se esse canal não estiver nessa lista).
class Televisor:
def __init__(self, fabricante, modelo, canal_atual, lista_de_canais, volume):
self.fabricante = fabricante
self.modelo = modelo
self.canal_atual = canal_atual
self.lista_de_canais = lista_de_canais
self.volume = volume
class controleRemoto:
def aumentar_diminuir_volume(self):
vol = int(input('Qual o volume que você deseja?\n'))
if vol > 0 and vol < 101:
self.volume = vol
return print(f'O novo volume é {self.volume}')
else:
print('Tente selecionar um valor entre 0 até 100 para continuar...')
def trocar_canal(self):
canal = input('Qual o canal que você deseja ver agora?\n').upper()
if canal in self.lista_de_canais:
self.canal_atual = canal
return print(f'O novo canal é {self.canal_atual}')
else:
self.canal_atual = canal
self.lista_de_canais.append(canal)
print(f'Novo canal adicionado em sua lista: {self.lista_de_canais}...')
casa1 = Televisor('TCL', 'Smart TV 4K', 'SBT', ['SBT', 'GLOBO', 'SPORTV', 'DISNEY'], 20)
casa1.controleRemoto().trocar_canal()
|
# Faça uma função que sorteia 10 números aleatórios entre 0 e 100 e retorna o maior entre eles.
from random import randint
lista = []
count = 0
while count < 11:
num = randint(0,100)
lista.append(num)
count += 1
def aleatorio(lista):
maximo = max(lista)
print(num)
aleatorio(lista)
|
"""
[Final Quiz]
Date: 2021-08-23
Design at least 3 major features for a text editor
Do a quick research on the Internet if you need some ideas or references
Save your project as 'mytexteditor'
Share your project to github
Post your URL of your remote git repository to SLACK
Due date: 2021-08-31
Hints:
Self-study on font family, size, weight of text widget in Tkinter
"""
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import Separator
from tkinter import font
def newfile():
messagebox.showinfo("File", "New File")
def font():
messagebox.showinfo("Font", "")
def countlines(event):
(line, c) = map(int, event.widget.index("end-1c").split("."))
# print(line, c)
status_text1 = f"Status: INSERT MODE ROW:{line},COL:{c}"
var.set(status_text1)
def cut():
str_status = var.get()
status_text2 = ' '*5+"cut."
var.set(status_text1+status_text2)
status_text2 = ''
def copy():
str_status = var.get()
status_text2 = ' '*5+"copy."
var.set(status_text1 + status_text2)
status_text2 = ''
def paste():
str_status = var.get()
status_text2 = ' '*5+"paste."
var.set(status_text1 + status_text2)
status_text2 = ''
def font_type():
str_status = var.get()
status_text2 = ' '*5+"Arial."
var.set(status_text1 + status_text2)
status_text2 = ''
def plus():
str_status = var.get()
status_text2 = ' '*5+"+ 1."
var.set(status_text1 + status_text2)
status_text2 = ''
def moin():
str_status = var.get()
status_text2 = ' '*5+"- 1."
var.set(status_text1 + status_text2)
status_text2 = ''
root = Tk()
root.title("Athensoft Python Course | Menu")
root.geometry("640x480+300+300")
# main bar
menubar = Menu(root)
# main bar item
filemenu = Menu(menubar, tearoff=False)
menubar.add_cascade(label="File", menu=filemenu)
# Level 2 menu option
filemenu.add_command(label="New File")
filemenu.add_command(label="Open File")
filemenu.add_command(label="Save")
filemenu.add_command(label="Save as")
filemenu.add_command(label="Exit", command=root.destroy)
# second bar item
filemenu = Menu(menubar, tearoff=False)
menubar.add_cascade(label="Edit", menu=filemenu)
# Level 2 menu option
filemenu.add_command(label="cut")
filemenu.add_command(label="copy")
filemenu.add_command(label="paste")
# third bar item
filemenu = Menu(menubar, tearoff=False)
menubar.add_cascade(label="Help", menu=filemenu)
# Level 2 menu option
filemenu.add_command(label="web")
filemenu.add_command(label="search")
# toolbar frame
frame_toolbar = Frame(root, height=30)
frame_toolbar.pack(anchor=W)
btn1 = Button(frame_toolbar, text="cut", command=cut)
btn1.pack(side=LEFT)
btn2 = Button(frame_toolbar, text="copy", command=copy)
btn2.pack(side=LEFT)
btn3 = Button(frame_toolbar, text="paste", command=paste)
btn3.pack(side=LEFT)
size = 12 # default size
size_var = IntVar()
size_var.set(size)
size_label = Label(frame_toolbar, textvariable=size_var) # font size label
add_size = Button(frame_toolbar, text="+", width=7, font=(None, 8), command=plus) # add size button
sub_size = Button(frame_toolbar, text="-", width=7, font=(None, 8), command=moin) # sub size button
add_size.pack(side=LEFT, padx=5) # first pack + button
size_label.pack(side=LEFT, padx=5) # second pack label showing current size
sub_size.pack(side=LEFT, padx=5) # finally pack - button
btn3 = Button(frame_toolbar, text="Arial", command=font_type)
btn3.pack(side=LEFT, padx=5)
# text widget
text = Text(root, height=5, width=30)
text.pack(fill=BOTH, expand=Y)
text.bind("<KeyRelease>", countlines)
# separator
sep = Separator(root, orient=HORIZONTAL)
sep.pack(fill=X, padx=1)
# status bar
var = StringVar()
# for mode and position
status_text1= "Status: INSERT MODE"
statusbar = Label(root, textvariable=var)
statusbar.pack(anchor=S + W)
var.set(status_text1)
# # for function button clicked
# status_text2 = ""
root.config(menu=menubar)
root.mainloop()
|
"""
Sandpile arithmetics.
The Sandpile class is used to construct a sandpile grid.
S is a virtual set that elements can be checked to be contained in.
"""
from itertools import zip_longest
__all__ = ['Sandpile', 'S']
class Sandpile(object):
"""A sandpile grid"""
TL = '┏'
V = '┃'
TR = '┓'
BL = '┗'
BR = '┛'
H = '━'
null_cache = {}
def __init__(self, *args, topple=True):
"""
Initializes a sandpile grid from its arguments.
The values are automatically toppled, unless the keyword argument
topple=False is provided.
>>> Sandpile([9,9,9], [9,9,9], [9,9,9])
Sandpile([1, 3, 1], [3, 1, 3], [1, 3, 1])
>>> Sandpile([9,9,9], [9,9,9], [9,9,9], topple=False)
Sandpile([9, 9, 9], [9, 9, 9], [9, 9, 9])
"""
self.num_of_cols = None
array = []
for row in args:
array.append([])
for col in row:
array[-1].append(col)
if self.num_of_cols is None:
self.num_of_cols = len(array[-1])
elif self.num_of_cols != len(array[-1]):
raise ValueError("All rows must have the same amount of values")
self.data = array
if topple:
self.topple(verbose=False)
def __str__(self):
"""Printing a sandpile grid leads to fancy display"""
return '{tl}{h}{tr}\n{lines}\n{bl}{h}{br}'.format(
tl=Sandpile.TL,
tr=Sandpile.TR,
bl=Sandpile.BL,
br=Sandpile.BR,
h=Sandpile.H*(2*self.num_of_cols+1),
lines='\n'.join(
'{v} {cols} {v}'.format(
v=Sandpile.V,
cols=' '.join(str(col) for col in row)
)
for row in self.data
)
)
def __repr__(self):
return "Sandpile({})".format(", ".join(map(repr, self.data)))
def __add__(self, other):
"""Add two sandpiles or a sandpile to a list of int lists"""
if not isinstance(other, Sandpile):
if isinstance(other, list):
other = Sandpile(*other)
else:
return NotImplemented
elif len(self.data) != len(other.data) or self.num_of_cols != other.num_of_cols:
raise RuntimeError("Can't add sandpiles with different dimensions.")
def add(x, y):
for xr, yr in zip(x, y):
yield map((lambda X: X[0]+X[1]), zip(xr,yr))
return Sandpile(*add(self.data, other.data))
__radd__ = __add__
def topple(self, verbose=True):
"""Topple a sandpile grid. By default, prints intermediary states."""
if verbose:
print(self)
while True:
changed=False
for row in range(len(self.data)):
for col in range(self.num_of_cols):
if self.data[row][col] > 3:
changed = True
self.data[row][col] -= 4
if row > 0:
self.data[row-1][col] += 1
if row < len(self.data)-1:
self.data[row+1][col] += 1
if col > 0:
self.data[row][col-1] += 1
if col < self.num_of_cols-1:
self.data[row][col+1] += 1
if not changed:
break
if verbose:
print(self)
def __eq__(self, other):
"""
Test for equality.
A sandpile is equal to another sandpile if its values are equal.
A sandpile is equal to a list l if it is equal to Sandpile(*l).
"""
if not isinstance(other, Sandpile):
if isinstance(other, list):
other = Sandpile(*other)
else:
return NotImplemented
for xr, yr in zip_longest(self.data, other.data):
for xc, yc in zip_longest(xr, yr):
if xc != yc:
return False
return True
def order(self):
"""
Return the order of the sandpile grid.
This is the integer n such that self * n == identity.
"""
identity = self.get_null()
x = self
value = 1
while True:
if x == identity:
return value
value += 1
x += self
def inverse(self):
"""
Return the inverse of the sandpile grid.
This is the sandpile grid g such that g + self == identity.
"""
identity = self.get_null()
x = self
while True:
y = x + self
if y == identity:
return x
x = y
def get_null(self):
dims = len(self.data), self.num_of_cols
if dims in Sandpile.null_cache:
return Sandpile.null_cache[dims]
else:
raise NotImplementedError(f"Unable to get the identity element for something of dimensions {dims}.")
Sandpile.null_cache[4,4] = Sandpile([2,1,1,2], [1,0,0,1], [1,0,0,1], [2,1,1,2])
Sandpile.null_cache[3,3] = Sandpile([2,1,2], [1,0,1], [2,1,2])
Sandpile.null_cache[2,2] = Sandpile([2,2], [2,2])
class SandpileSetS(object):
"""
For a given identity, construct an object that, given an element x,
returns True iff x + identity == x, i.e. if it is in S.
"""
def __contains__(self, other):
return other.get_null() + other == other
S = SandpileSetS()
|
"""Find the most frequent num(s) in nums.
Return the set of nums that are the mode::
>>> mode([1]) == {1}
True
>>> mode([1, 2, 2, 2]) == {2}
True
If there is a tie, return all::
>>> mode([1, 1, 2, 2]) == {1, 2}
True
"""
def mode(nums):
"""Find the most frequent num(s) in nums."""
num_dict={}
num_set = set()
for i in nums:
if i in num_dict:
num_dict[i] = num_dict[i] + 1
else:
num_dict[i] = 1
value_max = max(num_dict.values())
for key in num_dict:
if num_dict[key] == value_max:
num_set.add(key)
return num_set
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. HOORAY!\n")
|
def natural_number(data):
data=data[::-1]
Sum=0
for i in range(len(data)):
Sum+=int(data[i])*(2**i)
return Sum
def signed_integer(data):
n=data[0]
data=data[1::][::-1]
Sum=0
for i in range(len(data)):
Sum+=int(data[i])*(2**i)
if n=="1":
return Sum-128
return Sum
def character(data):
return chr(natural_number(data))
def Hex(data):
Sum=""
Get = { "0":"0","1" : "1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","10":"A","11":"B","12":"C","13":"D","14":"E","15":"F"}
for i in range(len(data)//4):
Sum+=Get[str(natural_number(data[(i)*4:(i+1)*4:]))]
return "0x"+Sum
data=input("Input 8Bit Binary: ")
print("Output1 natural number: %d"%natural_number(data))
print("Output2 signed integer: %d"%signed_integer(data))
print("Output3 character: %s"%character(data))
print("Output4 HEX: %s"%Hex(data))
|
from functools import reduce
left = 1
right = 22
def checker (count, num):
for c in str(num):
if (int(c) == 0 or (num % int(c) != 0)):
return count
count.append(num)
return count
s = reduce(checker,
[i for i in range(left, right + 1)],
[])
print (s) |
#Programa23: Dado el promedio obtenido en 5to de secundaria
import os
#Declaraciones
alumno=" "
prom=0.0
#Input vis os
alumno=str(os.sys.argv[1])
prom=int(os.sys.argv[2])
#Processing
#Si su promedio es mayor o igual a 17 (Ganó una beca)
if(prom>=17):
print(alumno,"SE GANO UNA BECA")
#Si su promedio es menor a 17 (No alcanzo la beca)
if(prom<=15):
print(alumno,"No alcanzo la beca")
#Si su promedio es menor < 14
if(prom<14):
print(alumno,"Siga intentando")
#Si su promedio es menor < 11
if(prom<11):
print(alumno,"Su promedio es muy bajo")
#fin_if
|
# Programa 11
import os
#Declaracion
nombre,edad=" ",0
#INPUT
nombre=str(os.sys.argv[1])
edad=int(os.sys.argv[2])
#PROCESSING
#Si el usuario es menor de edad no podra entrar al cine
#mostrar "¡Hasta la proxima!"
menor_edad=(edad < 18)
if (edad < 18):
print(nombre , "¡Hasta la proxima!")
else:
print(nombre, "¡Puede ingresar!")
#fin_if
|
# Programa 17
import os
#Declaracion
nombre,cantidad="",0
#INPUT
nombre=str(os.sys.argv[1])
cantidad=int(os.sys.argv[2])
#PROCESSING
#Si la compra es mayor de 3 panetones
#mostrar "¡Ganaste una tableta de chocolate!"
premio=( cantidad > 3 )
if (cantidad > 3):
print(nombre, "¡Ganaste una tableta de chocolate!")
else:
print(nombre, "Gracias por su compra")
#fin_if
|
#Programa7:Dado un número
import os
#Declaración
num=0
#Input vis os
num=int(os.sys.argv[1])
#Processing
#mostrar: El número es impar
if (num%2 != 0):
print("El número es impar")
#fin_if
|
# Programa 03
import os
#Declaracion
alumno,nota=" ",0
#INPUT
alumno=str(os.sys.argv[1])
nota=int(os.sys.argv[2])
#PROCESSING
#Si la nota del alumno es mayor a 14
#mostrar "¡Estas aprobado!"
aprobado=(nota >= 14)
if (nota >= 14):
print(alumno , "¡Estas aprobado!")
|
def Menu(): ##菜单主界面
print('*' * 22)
print("* 查看毕业生列表输入: 1 *")
print("* 添加毕业生信息输入: 2 *")
print("* 修改毕业生信息输入: 3 *")
print("* 删除毕业生信息输入: 4 *")
print("* 退出系统请输入 0 *")
print('*' * 22)
def CheckIdisRight(StudentList, id): ##检查学号是否在列表中
for i in range(0, len(StudentList)):
if ((id in StudentList[i]) == True):
return True
return False
def PrintStudentList(StudentList): # 打印学生信息列表
for i in range(0, len(StudentList)):
print(StudentList[i])
def AddStudent(StudentList): ##添加学生信息
number = int((input("请输入学号:")))
if (number < 1000000000 and CheckIdisRight(StudentList, number) == False): ##学号判断
print("学号输入错误&学号已存在!请重新输入:")
number = (input("请输入学号:"))
name = input("请输入你的名字:")
tell = input("请输入你的电话:")
if (len(tell) != 11):
print("请输入正确的电话号码(11)位:")
tell = input()
college = input("请输入你的学院名称:")
grade = input("请输入你的年级:")
isjob = int(input("是否就业?:是填 1 否则填0: "))
if (isjob == 1):
company = input("请输入你公司的名称:")
else:
company = 0
arry = [number, name, tell, college, grade, isjob, company]
StudentList.append(arry) ##将新建的学生信息进行插入
PrintStudentList(StudentList) ##打印学生信息列表
def StudentPersonalMsg(): ##修改信息界面选择
print('*' * 22)
print("* 修改姓名请输入: 1 *")
print("* 修改电话号码请输入: 2 *")
print("* 修改是否就业请输入: 3 *")
print("* 修改就业公司请输入: 4 *")
print("* 退出修改请输入:0 *")
print('*' * 22)
def ChangeStudent(StudentList): ##修改学生信息模块
##默认学号 年级 等信息不可修改
def changename(StudentList, arry, i): # 修改姓名
print(arry)
name = input("请输入修改后的名字:")
StudentList[i][1] = name
print("修改后为:")
PrintStudentList(StudentList)
def changetell(StudentList, arry, i): # 修改电话号码
print(arry)
tell = input("请输入修改后的电话号码:")
StudentList[i][2] = tell
print("修改后为:")
PrintStudentList(StudentList)
def changeisgob(StudentList, arry, i): # 修改是否就业情况
print(arry)
isgob = int(input("请输入修改后的 是否工作:"))
StudentList[i][5] = isgob
print("修改后为:")
PrintStudentList(StudentList)
def changcompany(StudentList, arry, i): # 修改就业公司信息
print(arry)
company = input("请输入修改后的公司为:")
StudentList[i][6] = company
print("修改后为:")
PrintStudentList(StudentList)
print("请输入要修改的学生的学号:")
id = int(input())
i = 1
if ((CheckIdisRight(StudentList, id)) == False): ##判断学号是否存在
print("学号不存在!")
if (CheckIdisRight(StudentList, id) == True):
while (i < len(StudentList)): # 通过循环找到该学生的信息列表
if (StudentList[i][0] == id):
StudentPersonalMsg() ##显示出修改的菜单选项
while (1):
a = int(input("请输入:"))
while (a):
if (a == 1):
##姓名修改
changename(StudentList, StudentList[i], i)
break
if (a == 2):
##电话号码修改
changetell(StudentList, StudentList[i], i)
break
if (a == 3):
##是否就业状态修改
changeisgob(StudentList, StudentList[i], i)
break
if (a == 4 and StudentList[i][5] == 1):
##就业公司修改
changcompany(StudentList, StudentList[i], i)
break
if (a == 4 and StudentList[i][5] == 0):
print("学生尚未就业,请先修改是否就业信息!")
break
if (a == 0):
##按0 退出修改信息功能
break
##返回到主界面的菜单选项
break
i = i + 1
def DeleteStudent(StudentList): ##删除学生信息
print("请输入要删除的学生的学号:输入0退出!")
id = int(input())
i = 1
if ((CheckIdisRight(StudentList, id)) == False):
print("学号不存在!")
if (CheckIdisRight(StudentList, id) == True):
##同样先判断学号学号是否存在
while (i < len(StudentList)):
if (StudentList[i][0] == id):
del StudentList[i]
print("删除成功!")
break
if (id == 0):
break
i = i + 1
PrintStudentList(StudentList) # 打印学生信息列表
def main():
Menu()
StudentInfo = ['学号', '姓名', '电话', '学院', '年级', '是否就业', "就业公司"]
##先默认插入一个用于显示的列表的列表
StudentList = [StudentInfo]
while (1):
a = int(input("请输入:"))
while (a):
if (a == 1):
PrintStudentList(StudentList)
Menu()
break
if (a == 2):
AddStudent(StudentList)
Menu()
break
if (a == 3):
ChangeStudent(StudentList)
Menu()
break
if (a == 4):
DeleteStudent(StudentList)
Menu()
break
if (a == 0): ##按0退出进程
exit()
main() |
arr = [1,12,2, 11, 13, 5, 6,18,4,9,-5,3,11]
def insertionSort(arr):
#从要排序的列表第二个元素开始比较
for i in range(1,len(arr)):
j = i
#从大到小比较,直到比较到第一个元素
while j > 0:
if arr[j] < arr[j-1]:
arr[j-1],arr[j] = arr[j],arr[j-1]
j -= 1
return arr
print(insertionSort(arr)) |
#!/usr/bin/env python3
class Stack:
def __init__(self):
self.list = []
def isEmpty(self):
return True if len(self.list) == 0 else False
def size(self):
return len(self.list)
def pop(self):
return self.list.pop()
def push(self,data):
self.list.append(data)
def top(self):
return self.list[len(self.list)-1] if len(self.list)>0 else None
def clear(self):
self.list.clear()
def __str__(self):
return "{}".format(self.list)
def pre(c):
if c=="*" or c=="/":
return 2
elif c=="+" or c=="-":
return 1
return 0
def isOperand(c):
if c=="+" or c=="-" or c=="*" or c=="/":
return True
else:
False
def InToPost(infix):
postfix = ""
stk = Stack()
stk.push(' ')
for c in infix:
if not(isOperand(c)):
postfix += c
else:
if pre(c)>pre(stk.top()):
stk.push(c)
else:
postfix += stk.pop()
while not(stk.isEmpty()):
postfix += stk.pop()
return postfix
if __name__ == "__main__":
infix = "2+1*1-4/2"
postfix = InToPost(infix)
print(postfix) |
from Tkinter import *
import random
import math
# Graphics Commands
def random_color():
'''Returns a random color in the hexadecimal format.'''
options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
options.extend(['a', 'b', 'c', 'd', 'e', 'f'])
x = 0
color = '#'
while (x < 6):
color += random.choice(options)
x += 1
return color
def draw_line(canvas, pt1, pt2):
'''This function draws a line from pt1 to pt2 on a given canvas.'''
x1, y1 = pt1
x2, y2 = pt2
line = canvas.create_line(x1, y1, x2, y2, fill = color)
return line
def draw_star(canvas, xc, yc):
'''This function draws a star using the draw_line function. The star
is drawn on the given campus about the inputted center points.'''
radius = random.randrange(50,101)
theta = 2*math.pi/N
points = []
star = []
for i in range(N):
x = radius*math.cos(theta*i)
y = radius*math.sin(theta*i)
point = (xc + y, yc - x)
points.append(point)
for i, pt in enumerate(points):
nextI = (i + (N-1)/2)%N
line = draw_line(canvas, pt, points[nextI])
star.append(line)
return star
# Event Handlers
def key_handler(event):
'''This function handles key presses.'''
global stars
global color
global N
key = event.keysym
if key == 'q':
quit()
elif key == 'c':
color = random_color()
elif key == 'plus':
N = N + 2
elif key == 'minus':
if ((N-2) < 5):
N = 5
else:
N = N - 2
elif key == 'x':
for star in stars:
for line in star:
canvas.delete(line)
stars = []
def button_handler(event):
'''This function handles button presses.'''
star = draw_star(canvas, event.x, event.y)
stars.append(star)
if __name__ == '__main__':
root = Tk()
root.geometry('800x800')
canvas = Canvas(root, width = 800, height = 800)
canvas.pack()
stars = []
color = random_color()
N = 5
# Bind events to handlers.
root.bind('<Key>', key_handler)
canvas.bind('<Button-1>', button_handler)
# Start it up.
root.mainloop()
|
# Définition des variables
import os
from random import randrange
from math import ceil
argent = 100
roulette = randrange(50)
# Proposer à l'utilisateur de miser sur un numéro entre 0 et 49 (pairs = noir, impairs = rouge)
# Si c'est gagné, le joueur gagne 3* sa mise
# Sinon, on vérifie si la couleur est bonne. Si oui, le joueur gagne mise / 2. Si non il perd tout
# On entend par là qu'il gagne mise + récompense, ajouté à son argent
print("Bienvenue dans le casino, le but du jeu est simple, faire péter la banque !")
print("Pour se faire vous disposez d'un montant initial de 100 jetons. Misez et choisissez une case et le croupier se chargera du reste.")
print("Si votre choix est correct, vous gagnez 3 fois la mise, sinon si votre votre chiffre est de la même couleur que la case,\nvous gagnez 1,5 fois votre mise.")
print("Votre objectif est d'obtenir 1000 jetons ou plus, bonne chance.")
while argent < 999 and argent > 1:
print("Argent actuel :", ceil(argent))
mise = -1
while mise < 0 or mise > argent:
mise = -1
mise = input("Combien voulez vous miser ? ")
try:
mise = int(mise)
except ValueError:
print("Vous n'avez pas entré de nombre")
mise = -1
continue
if mise < 0:
print("Nombre négatif")
if mise > argent:
print("Vous n'avez pas autant d'argent (", argent,"jetons)")
argent = argent - mise
choisir_numero = -1
while choisir_numero < 0 or choisir_numero > 49:
choisir_numero = -1
choisir_numero = input("Sur quel numéro entre 0 et 49 voulez-vous parier ? ")
try:
choisir_numero = int(choisir_numero)
except ValueError:
print("Vous n'avez pas entré de nombre")
choisir_numero = -1
continue
if choisir_numero < 0:
print("Nombre négatif")
if choisir_numero > 49:
print("Nombre trop élevé")
print("La roulette se lance et tombe sur", roulette)
if roulette == choisir_numero:
print("Vous avez gagné ! Vous recevez", ceil(mise*3), "jetons !")
argent += mise*3
elif choisir_numero % 2 == 0 and roulette % 2 == 0:
print("Vous n'avez pas gagné mais votre chiffre est noir ! Vous recevez", ceil(mise + (mise/2)), "jetons !")
argent += mise + (mise/2)
elif choisir_numero % 2 != 0 and roulette % 2 != 0:
print("Vous n'avez pas gagné mais votre chiffre est rouge ! Vous recevez", ceil(mise + (mise/2)), "jetons !")
argent += mise + (mise/2)
else:
print("Vous avez perdu, vous ne gagnez rien !")
if argent > 999:
print("Vous repartez riche du casino ! Bien joué !")
elif argent < 1:
print("Le vigile vous met dehors, vous êtes sans le sou !")
os.system("pause") |
class Cat:
def __init__(self, name, preferred_food, meal_time):
self.name = name
self.preferred_food = preferred_food
self.meal_time = meal_time
def __str__(self):
return "{}, {} and {}".format(self.name, self.preferred_food, self.meal_time)
def eats_at(self):
if self.meal_time > 12:
return self.meal_time - 12 + "PM"
elif self.meal_time == 12:
return self.meal_time + "PM"
else:
return self.meal_time + "AM"
def meow(self):
if self.meal_time > 12:
return "My name is {} and I eat {} at {} PM".format(self.name, self.preferred_food, self.meal_time - 12)
elif self.meal_time == 12:
return "My name is {} and I eat {} at {} PM".format(self.name, self.preferred_food, self.meal_time)
else:
return "My name is {} and I eat {} at {} AM".format(self.name, self.preferred_food, self.meal_time)
cora = Cat("Cora", "gravy chicken entree", 11)
mia = Cat("Mia", "salmon", 14)
print(cora.meow())
print(mia.meow()) |
import unittest
class TestDemoExecution(unittest.TestCase):
def test_demo_result_true(self):
"""
This is an example of how to write a boolean unit test
Ex: 4==4 -> True
"""
some_function = lambda x : x==4
self.assertTrue(some_function(4))
def test_demo_results_equals(self):
"""
This is an example of how to write a unit test that checks for equality
Ex: 4**2 = 16
"""
some_function = lambda x : x**2
self.assertEqual(some_function(4), 16)
|
#secondlargest
def secondlargest(n,data):
sh,fh=data[0],data[0]
for i in data[1:]:
if i>fh:
sh=fh
fh=i
if i>sh and i<fh:
sh=i
return sh
n=int(input())
data=list(map(int,input().split()))
print(secondlargest(n,data))
'''
4
1 2 7 8
7
'''
|
#second largest element
def secondlargest(n,data):
sh,lh=data[0],data[0]
for i in data[1:]:
if data[i]>fh:
sh=fh
fh=data[i]
if data[i]>sh and data[i]fh:
sh=i
return sh
n=int(input())
data=list(map(int,input().split()))
print(secondlargest(n,data))
|
'''
def findmin(n,data):
s,c=data[0],0
for i in data:
if s==i:
c+=1
if s>i:
s=i
c=1
ind=[s,c]
for i in range(n):
if s==data[i]:
ind.append(i)
return ind
n=int(input())
data=list(map(int,input().split()))
minval=findmin(n,data)
print(*minval)
'''
or
'''
def findmin(n,data):
s=min(data)
c=data.count(s)
ind=[s,c]
for i in range(n):
if s==data[i]:
ind.append(i)
return ind
n=int(input())
data=list(map(int,input().split()))
minval=findmin(n,data)
print(*minval)
'''
=============================================
10
45 13 431 171 184 13 21 13 33 13
13 4 1 5 7 9
|
def linear_search(data,key):
count=0
for i in range(0,len(data)):
count+=1
if data[i]==key:
print("Element found")
return count
else:
print("Not found")
return count
def binary_search(data,key):
l=0
h=len(data)-1
count=0
while(l<=h):
count+=1
m=(l+h)//2
if data[m]==key:
print("Element found")
return count
elif data[m]>key:
h=m-1
else:
l=m+1
else:
print("Not found")
return count
data=list(map(int,input().split()))
key=int(input())
#print(linear_search(data,key))
print(binary_search(data,key))
|
from random import randint
from flask import Flask, request
app = Flask(__name__)
rules = """
<h3>Rules: Pick one number and I will try to guess it in 10 tries.</h3>
"""
@app.route('/')
def guess_number():
min_num, max_num = 1, 1000
answer = 0
tried = 1
form = """
<p>
<form>
<p>Input your number in range 1-1000:<br><input type='number' name='a'></p>
<p><input type='submit'></p>
</form>
</p>
"""
answ_list = """
<select type="select" name ="answer">
<option>Too big</option>
<option>Too small</option>
<option>Correct</option>
</select>
<input type="submit" value="Oblicz">
"""
odp = """
<p>
<input type="button" name="big" value="Too big">
<input type="button" name="small" value="Too small">
<input type="button" name="hit" value="Correct">
</p>
"""
answer = request.args.get('big')
# to_small = request.args.get('small')
# correct = request.args.get('hit')
a = request.args.get('a', 0)
if a != None:
a = int(a)
if a < 1 or a > 1000:
out_of_range = f"{a} is out of range. Try again."
return rules + form + out_of_range
else:
answer = str(request.args.get("answer"," "))
show_number = f"<p>Your number is {a}</p>"
return rules + show_number + answer + answ_list + answer
else:
return rules + form + "Podaj liczbę z zakresu"
if __name__ == '__main__':
app.run()
|
# -*- coding: utf-8 -*-
'''
P3 Assignment
Derek Nguyen
Created: 2019-02-11
Modified: 2019-02-11
Due: 2019-02-11
'''
# %% codecell
#P3
import numpy as np
import scipy.integrate as integrate
import matplotlib # used to create interactive plots in the Hydrogen package of the Atom IDE
matplotlib.use('Qt5Agg') # used to create interactive plots in the Hydrogen package of the Atom IDE
import matplotlib.pyplot as plt
def pendulum(thetaZero = 30, damp = 0, timeSpan = 20, length = 0.45, gravity = 9.80, wZero = 0):
'''
Pendulum Comparison Simulation of a Simple and Real Pendulum
Uses solve_ivp to integrate a numerical solution for the two first-order ODEs
Parameter values for the generator depend on the specified:
thetaZero, float
damp, float > 0
timeSpan, float > 0
length, float > 0
gravity, float > 0
wZero, float
Derek Nguyen
Created: 02/11/2020
Last revised: 02/11/2020
'''
# Establish Animation time span
refreshRate = 60 # Hz
runTimeStep = 1/refreshRate # seconds
realTimeStep = runTimeStep
t = np.arange(0, timeSpan, realTimeStep) # t0 and tf in seconds
# Check to ensure that damp, timeSpan, length, and gravity are all positive floats
if damp < 0:
raise Exception('Error - damp is a negative value')
elif damp >= 0:
pass
else:
raise Exception('Error - damp is not a float')
if timeSpan < 0:
raise Exception('Error - timeSpan is a negative value')
elif timeSpan >= 0:
pass
else:
raise Exception('Error - timeSpan is not a float')
if length < 0:
raise Exception('Error - length is a negative value')
elif length >= 0:
pass
else:
raise Exception('Error - length is not a float')
if gravity < 0:
raise Exception('Error - gravity is a negative value')
elif gravity >= 0:
pass
else:
raise Exception('Error - gravity is not a float')
# Convert degrees to radians for variables thetaZero and wZero
thetaZero_rads = np.radians(thetaZero)
wZero_rads = np.radians(wZero)
# Calculate the Analytical Solution
sol_analytical = thetaZero_rads * np.cos(np.sqrt(gravity/length) * t)
# Calculate the Numerical Solution with Jacobian using solve_ivp
def dydt(t,theta):
dy = np.array((theta[1], -damp * theta[1] - gravity/length * np.sin(theta[0])))
return dy
def jacob(t,theta):
jacobian = np.array([[0,1],[-np.cos(theta),0]])
sol_numerical = integrate.solve_ivp(fun = dydt, t_span = [np.min(t), np.max(t)], y0 = [thetaZero_rads, wZero_rads], t_eval = t, jac = jacob)
theta1 = sol_numerical.y[0,:]
# Plot the Animation of a moving ball and rod utilzing point, and line, and a forloop utilizing the set_data function
x_analytical = length * np.sin(sol_analytical)
y_analytical = -length * np.cos(sol_analytical)
x_numerical = length * np.sin(theta1)
y_numerical = -length * np.cos(theta1)
plt.cla() # clear current axes
plt.axes(xlim = (-2*length,2*length), ylim = (-2*length,length)) # draw x and y limits
pointa, = plt.plot([], [], 'ro', label = 'Simple')
pointn, = plt.plot([], [], 'bo', label = 'Real')
linea, = plt.plot([], [], 'r-', lw = 1)
linen, = plt.plot([], [], 'b', lw = 1)
plt.title('Comparing Motions of a Simple and Real Pendulum')
plt.xlabel('Horizontal Position (m)')
plt.ylabel('Vertical Position (m)')
plt.legend()
for xapoint, yapoint, xnpoint, ynpoint in zip(x_analytical, y_analytical, x_numerical, y_numerical): # forloop to create the animation of moving pendulums
pointa.set_data(xapoint, yapoint)
pointn.set_data(xnpoint, ynpoint)
linea.set_data([0, xapoint], [0, yapoint])
linen.set_data([0, xnpoint], [0, ynpoint])
plt.pause(runTimeStep)
|
# https://leetcode.com/problems/longest-palindromic-substring/
"""
Longest Palindromic Substring
Medium
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters (lower-case and/or upper-case),
"""
def longest_palindrome(s: str) -> str:
sub = ""
start = 0
end = 1
while end < len(s):
pass
return sub
if __name__ == "__main__":
print(longest_palindrome("babad"))
|
# https://leetcode.com/problems/two-sum/
"""
Given an array of integers nums and an integer target,
return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
"""
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = sorted(nums) if sorted(nums) != nums else nums
left = 0
right = len(n) - 1
while left < right:
curr = n[left] + n[right]
if curr < target:
left += 1
elif curr > target:
right -= 1
else:
if sorted(nums) != nums:
return [nums.index(n[left]), nums.index(n[right])]
else:
return [left, right]
return [-1, -1]
|
# https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/python
"""
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array.
If the list is made up of only negative numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
"""
def max_sequence(arr: list) -> int:
rer = arr[::-1]
if not arr or max(arr) <= 0:
return 0
sub = [arr[i : (-e) + 1] for e, _ in enumerate(rer) for i, _ in enumerate(arr)]
return max(sum(s) for s in sub)
|
# https://www.codewars.com/kata/56882731514ec3ec3d000009/train/python
"""
Take a look at wiki description of Connect Four game:
Wiki Connect Four
The grid is 6 row by 7 columns, those being named from A to G.
You will receive a list of strings showing the order of the pieces which dropped in columns:
pieces_position_list = ["A_Red",
"B_Yellow",
"A_Red",
"B_Yellow",
"A_Red",
"B_Yellow",
"G_Red",
"B_Yellow"]
The list may contain up to 42 moves and shows the order the players are playing.
The first player who connects four items of the same color is the winner.
You should return "Yellow", "Red" or "Draw" accordingly.
"""
import time
from itertools import groupby
from typing import Any
from typing import Dict
from typing import List
from typing import Tuple
COLUMNS = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6}
LAYOUT = {"A": 0, "B": 0, "C": 0, "D": 0, "E": 0, "F": 0, "G": 0}
class ConnectFour:
def __init__(self, moves: List[str], layout: Dict[str, int] = LAYOUT) -> None:
self.moves = moves
self.layout = layout.copy()
self.board = [["_"] * 7 for _ in range(6)]
def who_is_winner(self) -> str:
self.draw = "Draw"
print("starting board \n")
print(*self.board, sep="\n")
for m in self.moves:
self.col, self.piece = m.split("_")
self.row = self.layout[self.col] + 1
print(f"\n{self.piece} played in column {self.col}\n")
self.board[self.layout[self.col]][COLUMNS[self.col]] = self.piece[0]
print(*self.board, sep="\n")
self.layout[self.col] += 1
if not self._winning(self.piece[0]) and self.piece != "_":
time.sleep(1)
else:
return (
f"\n***{self.piece} wins in column {self.col} row {self.row}!***\n"
)
return self.draw
def _winning(self, color: str) -> bool:
self.color = color
self.board_transposed = list(zip(*self.board))
return any(self._check_row(b, self.color) for b in self.board) or any(
self._check_col(b, self.color) for b in self.board_transposed # type:ignore
)
def _key_func(self, x: Any) -> Any:
self.x = x
return self.x[0]
def _check_row(self, b: List[str], color: str, target: int = 4) -> bool:
self.b = b
self.color = color
self.target = target
self.groups = [list(g) for _, g in groupby(self.b, self._key_func)]
return any(len(i) == target and i[0] == color for i in self.groups)
def _check_col(self, b: Tuple[str], color: str, target: int = 4) -> bool:
self.b = b # type:ignore
self.color = color
self.target = target
self.groups = [list(g) for _, g in groupby(b, self._key_func)]
return any(len(i) == target and i[0] == color for i in self.groups)
col_check = [
"A_Red",
"G_Yellow",
"A_Red",
"B_Yellow",
"A_Red",
"C_Yellow",
"A_Red",
"B_Yellow",
"C_Green",
"C_Blue",
"D_Orange",
"B_Purple",
]
row_check = [
"A_Red",
"G_Yellow",
"B_Red",
"E_Yellow",
"C_Red",
"G_Yellow",
"D_Red",
"B_Yellow",
"C_Green",
"C_Blue",
"D_Orange",
"B_Purple",
]
if __name__ == "__main__":
c = ConnectFour(col_check)
print(c.who_is_winner())
r = ConnectFour(row_check)
print(r.who_is_winner())
|
# https://www.codewars.com/kata/51fda2d95d6efda45e00004e/train/python
"""
Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar
to the one Codewars uses.
Business Rules:
A user starts at rank -8 and can progress all the way to 8.
There is no 0 (zero) rank. The next rank after -1 is 1.
Users will complete activities. These activities also have ranks.
Each time the user completes a ranked activity the users rank progress is updated based off of the activity's rank
The progress earned from the completed activity is relative to what the user's current rank is compared to the rank of the activity
A user's rank progress starts off at zero, each time the progress reaches 100 the user's rank is upgraded to the next level
Any remaining progress earned while in the previous rank will be applied towards the next rank's progress
(we don't throw any progress away).
The exception is if there is no other rank left to progress towards (Once you reach rank 8 there is no more progression).
A user cannot progress beyond rank 8.
The only acceptable range of rank values is -8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8. Any other value should raise an error.
The progress is scored like so:
Completing an activity that is ranked the same as that of the user's will be worth 3 points
Completing an activity that is ranked one ranking lower than the user's will be worth 1 point
Any activities completed that are ranking 2 levels or more lower than the user's ranking will be ignored
Completing an activity ranked higher than the current user's rank will accelerate the rank progression.
The greater the difference between rankings the more the progression will be increased.
The formula is 10 * d * d where d equals the difference in ranking between the activity and the user.
Logic Examples:
If a user ranked -8 completes an activity ranked -7 they will receive 10 progress
If a user ranked -8 completes an activity ranked -6 they will receive 40 progress
If a user ranked -8 completes an activity ranked -5 they will receive 90 progress
If a user ranked -8 completes an activity ranked -4 they will receive 160 progress, resulting in the user being upgraded to rank -7 and having earned 60 progress towards their next rank
If a user ranked -1 completes an activity ranked 1 they will receive 10 progress (remember, zero rank is ignored)
Code Usage Examples:
user = User()
user.rank # => -8
user.progress # => 0
user.inc_progress(-7)
user.progress # => 10
user.inc_progress(-5) # will add 90 progress
user.progress # => 0 # progress is now zero
user.rank # => -7 # rank was upgraded to -7
"""
ALLOWED_RANKS = [-8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8]
class User:
def __init__(self) -> None:
self.rank = -8
self.progress = 0
def __repr__(self):
return f"<User> {self.rank=} and {self.progress=}"
def _inc_rank(self, activity: int, user: int) -> None:
if user - activity >= 2:
return
if (
activity == user
and self.rank == -3
or activity != user
and user - activity == 1
and self.rank == -1
):
self.rank = 1
elif activity == user:
if self.rank + 3 not in ALLOWED_RANKS:
raise ValueError(f"rank {self.rank} is not valid!")
else:
self.rank += 3
else:
if self.rank + 1 not in ALLOWED_RANKS:
raise ValueError(f"rank {self.rank} is not valid!")
else:
self.rank += 1
def inc_progress(self, activity_points: int) -> None:
d = activity_points - self.rank
self.progress += 10 * d * d
if self.progress >= 100:
self._inc_rank(activity_points, self.rank)
self.progress -= 100
if __name__ == "__main__":
user = User()
print(user.rank) # => -8
print(user.progress) # => 0
user.inc_progress(-7)
print(user.progress) # => 10
user.inc_progress(-5) # will add 90 progress
print(user.progress) # => 0 # progress is now zero
print(user.rank) # => -7 # rank was upgraded to -7
|
import numpy as np
class SequentialData(object):
def __init__(self, data_size, num_classes, batch_size, num_steps):
"""Set the parameters for generating the data using a predefined rule
"""
self.batch_size = batch_size
self.data_size = data_size
self.num_classes = num_classes
self.num_steps = num_steps
def gen_data(self):
"""Return the X and Y sequence generated according a predefined rule
"""
x = np.random.choice(2, size=(self.data_size,))
y = []
for i in xrange(self.data_size):
threshold = 0.5
if x[i - 3] == 1:
threshold += 0.5
if x[i - 4] == 1:
threshold -= 0.25
if np.random.rand() > threshold:
y.append(0)
else:
y.append(1)
return x, np.array(y)
def gen_batch(self, data):
"""Return a generator for producing the input sequence and
target sequence for rnn
"""
x, y = data
column_size = self.data_size // self.batch_size
data_x = np.zeros((self.batch_size, column_size), dtype = np.int32)
data_y = np.zeros((self.batch_size, column_size), dtype = np.int32)
for i in xrange(self.batch_size):
data_x[i] = x[i * column_size:(i + 1) * column_size]
data_y[i] = y[i * column_size:(i + 1) * column_size]
num_epochs = column_size // self.num_steps
for i in xrange(num_epochs):
x = data_x[:, i * self.num_steps:(i + 1) * self.num_steps]
y = data_y[:, i * self.num_steps:(i + 1) * self.num_steps]
yield (x, y)
def gen_epoch(self, n):
"""Return a generator that gives data for N epochs
"""
data = self.gen_data()
for _ in xrange(n):
yield self.gen_batch(data)
|
"""
用Spyder運行,命令行參數在 Run-Configuration per file-Command line options 設置
e.g. do.txt doc.txt
"""
import sys
import os
import re
def get_file_name(c):
res = []
prefix = input_filename.split(c)[0]
dirPath = os.getcwd() # 獲取當前工作路徑
for root, dirs, files in os.walk(dirPath):
for file in files:
# 用正則表達式匹配文件名 *和?會按要求重複匹配[0-9a-zA-Z]
res += re.findall('^('+prefix+'[0-9a-zA-Z]'+c+'\.txt)',file)
print(res)
return res
input_filename = sys.argv[1] # 獲取命令行輸入的參數,0是當前文件路徑
output_filename = sys.argv[2]
if '*' in input_filename:
file_list = get_file_name('*')
flag = True
elif '?' in input_filename:
file_list = get_file_name('?')
flag = True
else:
file_list = [input_filename]
flag = False
if len(file_list) == 0:
print("No matching!")
else:
try:
res = ''
for file in file_list:
with open(file, 'r') as f1:
article = f1.read()
if flag:
res += "Name of file: " + file + '.\n'
# 統計字母的數量
res += "Number of characters: "+str(len([x for x in article if x.isalpha()]))+'.\n'
res += "Number of words: "+str(len(article.split()))+'.\n'
res += "Number of lines: "+str(len(article.split('\n')))+'.\n'
with open(output_filename, 'w') as f2:
f2.write(res)
except:
print('Opening file ' + input_filename + ' failed!')
|
a = int(input())
total = 1
for i in range(1,a+1):
total *= i
print(total) |
# ------------- Machine Learning - Topic 2: Logistic Regression
# You will need to complete the following functions
# in this exercise:
# sigmoid
# costFunction
# predict
# plotData
# plotDecisionBoundary
## Initialization
import numpy as np
from scipy.optimize import fmin, fmin_bfgs
import os, sys
sys.path.append(os.getcwd() + os.path.dirname('/ml/ex2/'))
from helpers import sigmoid, costFunction, predict, plotData, plotDecisionBoundary
# Load Data
# The first two columns contains the exam scores and the third column
# contains the label.
data = np.loadtxt('ml/ex2/ex2data1.txt', delimiter=",")
X = data[:, :2]
y = data[:, 2]
## ==================== Part 1: Plotting ====================
# We start the exercise by first plotting the data to understand the
# the problem we are working with.
print('Plotting data with + indicating (y = 1) examples and o indicating (y = 0) examples.')
plt, p1, p2 = plotData(X, y)
# # Labels and Legend
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.legend((p1, p2), ('Admitted', 'Not Admitted'), numpoints=1, handlelength=0)
plt.show(block=False) # prevents having to close the graph to move forward with ex2.py
input('Program paused. Press enter to continue.\n')
# plt.close()
## ============ Part 2: Compute Cost and Gradient ============
# In this part of the exercise, you will implement the cost and gradient
# for logistic regression. You neeed to complete the code in
# costFunction.m
# Setup the data matrix appropriately, and add ones for the intercept term
m, n = X.shape
X_padded = np.column_stack((np.ones((m,1)), X))
# Initialize fitting parameters
initial_theta = np.zeros((n + 1, 1))
# Compute and display initial cost and gradient
cost, grad = costFunction(initial_theta, X_padded, y, return_grad=True)
print('Cost at initial theta (zeros): {:f}'.format(cost))
print('Gradient at initial theta (zeros):')
print(grad)
input('Program paused. Press enter to continue.\n')
## ============= Part 3: Optimizing using fmin (and fmin_bfgs) =============
# In this exercise, you will use a built-in function (fmin) to find the
# optimal parameters theta.
# Run fmin and fmin_bfgs to obtain the optimal theta
# This function will return theta and the cost
# fmin followed by fmin_bfgs inspired by stackoverflow.com/a/23089696/583834
# overkill... but wanted to use fmin_bfgs, and got error if used first
myargs=(X_padded, y)
theta = fmin(costFunction, x0=initial_theta, args=myargs)
theta, cost_at_theta, _, _, _, _, _ = fmin_bfgs(costFunction, x0=theta, args=myargs, full_output=True)
# Print theta to screen
print('Cost at theta found by fmin: {:f}'.format(cost_at_theta))
print('theta:'),
print(theta)
# Plot Boundary
plotDecisionBoundary(theta, X_padded, y)
plt.hold(False) # prevents further drawing on plot
plt.show(block=False)
input('Program paused. Press enter to continue.\n')
## ============== Part 4: Predict and Accuracies ==============
# After learning the parameters, you'll like to use it to predict the outcomes
# on unseen data. In this part, you will use the logistic regression model
# to predict the probability that a student with score 45 on exam 1 and
# score 85 on exam 2 will be admitted.
#
# Furthermore, you will compute the training and test set accuracies of
# our model.
#
# Predict probability for a student with score 45 on exam 1
# and score 85 on exam 2
prob = sigmoid(np.dot(np.array([1,45,85]),theta))
print('For a student with scores 45 and 85, we predict an admission probability of {:f}'.format(prob))
# Compute accuracy on our training set
p = predict(theta, X_padded)
print('Train Accuracy: {:f}'.format(np.mean(p == y) * 100))
input('Program paused. Press enter to continue.\n')
|
import numpy as np
from matplotlib import pyplot as plt
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def main():
x = np.arange(-10, 10, 0.2) # -10-10的数组,间隔为0.2数值
# 非调库实现方法
y = [sigmoid(i) for i in x]
plt.grid(True)
plt.plot(x, y)
plt.show()
if __name__ == '__main__':
main()
|
#print ("Input the number of characters in line: ")
w = int(input("Input the number of characters in line: "))
my_string_list = ['Hello I am Phoebe!',
'I know you, you feed me.',
'You are Helen and Anton.']
def split_lines_into_words(line_list):
new_words_list = []
for line in line_list:
new_words_list.extend(line.split(' '))
return new_words_list
def generate_lines_with_new_length(accepted_lines_list, new_length):
new_words_list = split_lines_into_words(accepted_lines_list)
new_lines_list = []
letters_count = 0
current_line = ''
for word in new_words_list:
word_length = len(word)
if (letters_count + word_length) < new_length:
current_line += word + ' '
letters_count += word_length + 1
else:
new_lines_list.append(current_line)
current_line = word + ' '
letters_count = word_length + 1
new_lines_list.append(current_line)
return new_lines_list
print("\n".join(generate_lines_with_new_length(my_string_list, w)))
#def cut_string(string_list, char_number):
# i_in_curr_line = 0
# new_string_list = []
# new_word = ''
# i_in_old_line = 0
# i_in_new_line = 0
#
# for curr_line in my_string_list:
# len_curr_line = len(my_string_list[i_in_old_line])
#
# if (len_curr_line <= char_number) & (new_string_list[i_in_new_line] = ' '):
# new_string_list[i_in_new_line] = curr_line
# i_in_old_line += 1
#
# else:
# if new_string_list[i_in_new_line] != ' '):
# i = len_curr_line
# while (i_in_curr_line < len_curr_line) & (i_in_curr_line < char_number):
# len_word = 0
#
# while (curr_line[i_in_curr_line] != ' '):
# i_in_curr_line +=1
# new_word += curr_line[i_in_curr_line]
# len_word +=1
#
# if i_in_curr_line < char_number:
# new_string_list[i_in_new_line] += new_word
# i_in_new_line += 1
#
# return new_string_list
# def cut_words(line_list):
# words_list = []
# #j = 0
#
# for line in line_list:
# len_line = len(line)
# i = 0
#
# while i < len_line:
# new_word = ''
#
# while (i < len_line) and (line[i] != ' '):
# new_word += line[i]
# i += 1
# words_list.append(new_word)
# #print words_list
# i += 1
# #j += 1
# return words_list |
s = 'betty bought a bit of butter but the butter was bitter'
wordlist = s.split()
wordfreq = [wordlist.count(w) for w in wordlist]
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
d = dict(zip(wordlist,wordfreq))
aux = [(d[key],key) for key in d]
from operator import itemgetter, attrgetter, methodcaller
aux = sorted(aux, key=itemgetter(0), reverse=True)
print aux
freq = [pair[0] for pair in aux]
print freq
m = len(freq)
n = 3
for i in range(0,m-1):
if freq[i] != freq[i+1]:
print i
list1 = aux[0:i+1]
list2 = aux[i+1:m]
list2 = sorted(list2, key=itemgetter(1), reverse=True)
list2 = list2[::-1]
list2 = list2[0:n]
# TODO: Return the top n words as a list of tuples (<word>, <count>)
list3 = list1 + list2
print list3
|
def coin(N, K):
if K > N and (K >= 1 and K <= 500):
a = (N**2 - N)/2
if K == a:
return 'Y'
else:
return 'N'
else:
return 'N'
N = 0
K = 5
res = coin(N, K)
print(res)
|
class Node:
def __init__(self, obj, next):
self.object=obj
self.next=next
class LinkedList:
def __init__(self, obj=None, next=None):
self.node = None
def add(self, obj):
if self.node == None:
self.node = Node(obj,None)
else:
p=self.node.next
#self.node=Node(obj,p) # Wrong
self.node = Node(obj, self.node)
def addLast(self, obj):
i=self.node
if i == None:
self.add(obj)
return
while i.next != None:
i=i.next
i.next=Node(obj=obj,next=None)
def getLast(self):
i=self.node
while i != None:
i=i.next
return i.object
def remove(self):
if self.node == None:
return
i=self.node.next
self.node=i
def removeElement(self, obj):
prev = self.node
i=self.node
while i != None:
if i.object == obj and self.node.object == obj:
self.node = self.node.next
if i.object == obj:
prev.next= i.next
prev=i
i=i.next
def removeLast(self):
if self.node == None:
return
i=self.node
prev=i
while i.next != None:
prev=i
i=i.next
prev.next=None
def contains(self,obj):
i = self.node
while i != None:
if i.object == obj:
return True
i = i.next
return False
def __len__(self):
i = self.node
count =0
while i != None:
count +=1
i = i.next
return count
def __str__(self):
ss=str()
i = self.node
while i != None:
ss += str(i.object) + " ==> "
i=i.next
return ss + "None"
if __name__ == "__main__":
ll = LinkedList()
ll.add(5)
ll.add(4)
ll.add(3)
ll.add(2)
ll.add(1)
ll.addLast(6)
print(ll)
ll.removeLast()
print(ll)
ll.removeElement(1)
print(ll)
ll.removeElement(5)
print(ll)
ll.remove()
print(ll)
ll.remove()
print(ll)
ll.remove()
print(ll)
ll.remove()
print(ll)
ll.addLast("a")
ll.addLast("b")
ll.addLast("c")
print(ll) |
"""
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
For example,"egg" and "add" are isomorphic, "foo" and "bar" are not.
"""
def isIsomorphic(word1, word2):
if len(word1) != len(word2):
return False
d={}
for i in range(len(word1)):
idem = d.get(word1[i], None)
if idem == None :
d[word1[i]] = word2[i]
else:
if idem != word2[i]:
return False
return True
inputs = [("egg", "add"), ("foo", "bar")]
for e in inputs:
print(e, end = " : ")
print(isIsomorphic(*e)) |
import random
def quickSort(s, e , _list):
if s > e:
return
print("{!r}".format( _list), end = " ")
pp = partition_origin(s, e, _list)
print("{}: {} PP:{} {!r}".format(s, e ,pp, _list))
quickSort(s, pp - 1 , _list)
quickSort(pp +1, e, _list)
# This does not find right index for pivot
def partition(s, e, _l):
i, j = s, e
pivot = _l[(s+e)//2]
while i < j:
while i < e and _l[i] < pivot :
i += 1
while j > s and _l[j] > pivot:
j -= 1
if i <= j:
_l[i] , _l[j] = _l[j], _l[i]
i += 1
j -= 1
return i
def partition_origin(low, high, arr):
i = (low - 1) # index of smaller element
pivot = arr[high] # pivot
for j in range(low, high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return (i + 1)
l =[7, 6,5,4,3,2,1]
l =[4, 7, 6,5,4,3,2,1]
l1=[1, 1]
quickSort(0, len(l)-1, l)
#a =partition(0, len(l)-1, l)
print(l)
|
import threading, time
class BankAccount:
def __init__(self):
self.bal = 0
self.lock = threading.Lock()
def deposit(self, amt):
with self.lock:
#DEADLOCK
#self.lock.acquire()
balance = self.bal
time.sleep(2)
self.bal = balance + amt
#self.lock.release()
def withdraw(self, amt):
with self.lock:
balance = self.bal
if balance - amt < 0:
raise Exception("Not enoug balance: {}".format(self.bal))
time.sleep(2)
self.bal = balance - amt
b = BankAccount()
t1 = threading.Thread(target= b.deposit, args =(100,))
t2 = threading.Thread(target= b.withdraw, args =(50,))
t1.start()
t2.start()
t1.join()
t2.join()
print(b.bal)
|
"""
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array.
"""
def binarySearch(nums, target):
return _binarySearch(nums, target, 0, len(nums)-1)
def _binarySearch(nums, target, start, end):
if start > end:
return -1
mid = (start + end)//2
if nums[mid] == target:
return mid
if nums[start] < nums[mid]:
if nums[start] <= target < nums[mid]:
return _binarySearch(nums, target, start, mid -1)
else:
return _binarySearch(nums, target, mid + 1, end)
else:
if nums[mid] < target <= nums[end]:
return _binarySearch(nums, target, mid + 1, end)
else:
return _binarySearch(nums, target, start, mid -1)
l= [i for i in range(10)]
for i in range(10):
t = l+l
t = t[i:len(l)+i]
index = binarySearch(t, 5)
print("{} : {} : {}".format(t, 5, index)) |
def consecutive(num):
count = 0
L = 1
while (L * (L + 1) < 2 * num):
a = (num - (L * (L + 1)) / 2) / (L + 1)
print("{} {}".format(a, int(a)))
if (a - int(a) == 0.0):
count += 1
L += 1
print(count)
return count
consecutive(15) |
import time, timeit
from datetime import timedelta
# O(n)
def fibonacci(n):
init_1 = 1
init_2 = 1
if n < 3:
return init_1
for i in range (2, n):
temp = init_2
init_2 = init_1 + init_2
init_1 = temp
return init_2
# O(2^n)
def fibonacci_rec(n):
if n == 1 or n == 2:
return 1
return fibonacci_rec(n-1) + fibonacci_rec(n-2)
# O(n)
def fibonacci_rec2(n,lib=[0,1]):
if n == 0 or n == 1:
return lib[n]
try:
return lib[n]
except:
lib.append(fibonacci_rec2(n-1, lib) + fibonacci_rec2(n-2, lib))
return lib[n]
n=50
start_time = time.clock()
a=fibonacci(n)
elapsed = time.clock() - start_time
print("Bottom-up {} : {} : {}".format(n,a,str(timedelta(seconds=elapsed))))
start_time = timeit.timeit()
#a=fibonacci_rec(n)
elapsed = timeit.timeit() - start_time
print("Top-down O(n^2) {} : {} : {}".format(n,a,str(timedelta(elapsed))))
start_time = time.time()
a=fibonacci_rec2(n)
elapsed = time.time() - start_time
print("Top-Down O(n) {} : {} : {}".format(n,a,str(timedelta(elapsed)))) |
from queue import Queue
'''
This is shortest path when its edges has same factor
'''
class Graph:
def __init__(self, n):
self.g = {}
self.n = n
for i in range(1, n + 1):
nodes = self.g.get(i, set())
self.g[i] = nodes
def connect(self, s, e):
self.g[s].add(e)
self.g[e].add(s)
def find_all(self, s):
q = Queue()
q.put(s)
distance = [-1] * (self.n + 1)
distance[s] = 0
while not q.empty():
node = q.get()
for n in self.g[node]:
if distance[n] == -1 and n != s:
q.put(n)
distance[n] = distance[node] + 6
for i in range(1, self.n + 1):
if s != i:
print(distance[i], end=" ")
print()
graph = Graph(4)
graph.connect(1,4)
graph.connect(1,3)
graph.connect(1,2)
#print(graph.g)
graph.find_all(1)
graph = Graph(3)
graph.connect(2,3)
#print(graph.g)
graph.find_all(2)
graph = Graph(70)
with open("input.txt", mode = "rt") as f:
for line in f:
a, b = line.strip().split()
graph.connect(int(a), int(b))
print("#"*100)
graph.find_all(16)
print("#"*30 + " ANSWER " + "#"*30)
with open("expected.txt", mode = "rt") as f:
print("".join(f.readlines()))
print("#" * 100)
|
class ExampleIterator:
def __init__(self, sequence):
self.index = 0
self.data=sorted(sequence, reverse=True)
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration()
result = self.data[self.index]
self.index += 1
return result
class ExampleIterable:
def __init__(self):
self.data = [1,2,3]
def __iter__(self):
return ExampleIterator(self.data)
for i in ExampleIterator([1,2,3]):
print(i)
for i in ExampleIterable():
print(i)
"""
The Alterative iterable protocaol works with any object that supports consecutive integer indexing via __getitem__()
"""
class AlternativeIterable:
def __init__(self):
self.data =[5,6,7]
def __getitem__(self, index):
return self.data[index]
for i in AlternativeIterable():
print(i)
print()
l = [1,2,3,4,5,6,7]
myiter = iter(l)
for i in myiter:
print(i)
import datetime
t = iter(datetime.datetime.now, None)
j = 0
for i in t:
print(i)
if j == 10:
break
j +=1
def p():
return 1
j = 0
for i in iter(p, None):
print(i)
if j == 10:
break
j +=1 |
from LinkedList import LinkedList
def remove(ll, k):
h1 = ll.head
if h1 == None:
return
p = h1
pp = p.next
f = h1
while f != None and k != 0:
f = f.next
k -= 1
if f == None:
ll.head = ll.head.next
return
while f.next != None:
f = f.next
p =pp
pp=pp.next
p.next = pp.next
linkelist1 = LinkedList()
linkelist1.add(15)
linkelist1.add(10)
linkelist1.add(5)
linkelist1.add(4)
linkelist1.p()
print("#"*100)
remove(linkelist1, 3)
linkelist1.p()
|
def maxSubArray(nums):
n = len(nums)
memo = [0] * n
memo[0] = nums[0]
submax = nums[0]
for i in range(1, n):
t_max = max(memo[i - 1] + nums[i], nums[i])
if t_max > submax:
submax = t_max
memo[i] = submax
else:
if t_max < 0:
memo[i] = 0
else:
memo[i] = t_max
return submax
inputs = [[1, 0 ,3, 0, 4], [-1,-2,-3,-4,-5], [-2,1,-3,4,-1,2,1,-5,4]]
for i in inputs:
print(i, end = " : ")
print(maxSubArray(i)) |
from LinkedList import LinkedList
"""
def reverse(ll):
h1 = ll.head
if h1 == None or h1.next == None:
return
else:
p = h1
pp = h1.next
p.next = None
while pp != None:
next_pp = pp.next
pp.next = p
p = pp
pp = next_pp
ll.head = p
"""
#recurive_way
def _reverse(p , pp):
if pp == None:
return p
next_pp = pp.next
pp.next = p
p = pp
pp = next_pp
return _reverse(p, pp)
def reverse(ll):
if ll.head == None or ll.head.next == None:
return ll
p = ll.head
pp = p.next
p.next = None
new_head = _reverse(p, pp)
ll.head = new_head
linkelist1 = LinkedList()
linkelist1.add(15)
linkelist1.add(10)
linkelist1.add(5)
linkelist1.add(4)
linkelist1.p()
print("#"*100)
reverse(linkelist1)
linkelist1.p() |
"""
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
"""
## This should be taken as a cautious aproach
#Does this have lowercase and uppercase
#case1 : s
#case2 : ss
#case : abc
#case : abcdabc
#case : abccba
#1 Solution of O(n)
def firstUniqueChar(s):
data = dict()
for i, c in enumerate(s):
indexies = data.get(c, [])
indexies.append(i)
data[c] = indexies
unique_indexes=[]
for v in data.values():
if len(v) == 1:
unique_indexes.extend(v)
if len(unique_indexes) == 0:
return -1
else:
return min(unique_indexes)
#print(firstUniqueChar("aas"))
#2 Solution of O(n^2)
def firstUniqueChar2(s):
for i in range(len(s)):
no_dup = True
for j in range(len(s)):
if i == j:
continue
if s[i] == s[j]:
no_dup = False
break;
if no_dup:
return i
return -1
print(firstUniqueChar2("cc")) |
def numOf1_bits(num):
n = 0
for i in range(32):
bit = num & 0x01 << i
if bit == 1:
n+=1
print(n)
inputs = [5,6,7,8]
for input in inputs:
numOf1_bits(input)
|
"""
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
"""
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j].isdigit() and not self.check(board, i, j):
return False
return True
def check(self, board, row, col):
return self.check_row(board, row, col) and self.check_col(board, row, col) and self.check_block(board, row, col)
def check_row(self, board, row, col):
target = board[row][col]
for i in range(len(board)):
if i != row and target == board[i][col]:
return False
return True
def check_col(self, board, row, col):
target = board[row][col]
for i in range(len(board[row])):
if i != col and target == board[row][i]:
return False
return True
def check_block(self, board, row, col):
col_range = col // 3
row_range = row // 3
target = board[row][col]
dic = {0: range(0, 3), 1: range(3, 6), 2: range(6, 9)}
for i in dic[row_range]:
for j in dic[col_range]:
if (i != row or j != col) and target == board[i][j]:
return False
return True
#b =[[".","8","7","6","5","4","3","2","1"],["2",".",".",".",".",".",".",".","."],["3",".",".",".",".",".",".",".","."],["4",".",".",".",".",".",".",".","."],["5",".",".",".",".",".",".",".","."],["6",".",".",".",".",".",".",".","."],["7",".",".",".",".",".",".",".","."],["8",".",".",".",".",".",".",".","."],["9",".",".",".",".",".",".",".","."]]
b= [["7",".",".",".","4",".",".",".","."],[".",".",".","8","6","5",".",".","."],[".","1",".","2",".",".",".",".","."],[".",".",".",".",".","9",".",".","."],[".",".",".",".","5",".","5",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".","2",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."]]
s = Solution()
print(s.isValidSudoku(b)) |
#memory bound implimataion
def remove_deuplicate(nums):
single, i = 0, 1
while i < len(nums):
if not isDuplicate(nums, single, nums[i]):
single += 1
nums[single], nums[i] = nums[i], nums[single]
i += 1
return nums, single
def isDuplicate(nums, k, target):
i = 0;
while ( i <= k):
if nums[i] == target:
return True
i += 1
return False
input = [-1, 2, 4, 2, 4]
print(input, end= " : ")
print(remove_deuplicate(input))
input = [2, 2, 4, 2, 4]
print(input, end= " : ")
print(remove_deuplicate(input))
input = [0,0,0,0,0,0]
print(input, end= " : ")
print(remove_deuplicate(input))
input = [i for i in range(21)]
print(input, end= " : ")
print(remove_deuplicate(input)) |
"""
Insert a cha
remove a cha
replace a cha
pale, Ple => true
pales,pale => True
pale, bale => True
pale, bake => False
write a function to check if they are one edit (or zero) away
Note 1: Only one character difference
Solution 1 ( Logical Error: because the order matters)
: using dictionary. if there are the following values in dictionary, then True
-1, +1 , -1 +1 (everything else should be 0 in values
Q1: uppercase and lowercase are same?
Q2: how about space?
"""
def oneway(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if len(s1) == len(s2):
counter = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
counter += 1
if counter > 1:
return False
else:
min_len = min(len(s1), len(s2))
counter = 0
for i in range(min_len):
if s1[i + counter] != s2[i]:
if len(s1) > len(s2):
counter = counter - 1
else:
counter = counter + 1
if counter > 1 and counter < -1:
return False
return True
s1="pale"
s2="ale"
print(oneway(s1, s2))
|
def readchars(filename):
with open(filename, mode='rt') as f:
for four in f:
print(four, end="")
def readchars1(filename):
with open(filename, mode='rt') as f:
print(f.read())
def readchars2(filename):
with open(filename, mode='rt') as f:
lines = f.readlines()
print("".join(lines))
def readchars3(filename):
with open(filename, mode='rt') as f:
four = f.read(4)
while four:
print(four, end="")
four = f.read(4)
filename = "language/files/b.txt"
readchars3(filename) |
#longest palindromic sequence
# Complete the longestPalindrome function below.
#https://www.youtube.com/watch?v=_nCsPn7_OgI
def longestPalindrome(n, s):
L = [[0 for x in range(n)] for x in range(n)]
for i in range(n):
L[i][i] = 1
for cl in range(2, n + 1):
for i in range(n - cl + 1):
j = i + cl - 1
if s[i] == s[j] and cl == 2:
L[i][j] = 2
elif s[i] == s[j]:
L[i][j] = L[i + 1][j - 1] + 2
else:
L[i][j] = max(L[i][j - 1], L[i + 1][j]);
return L[0][n - 1]
def longestPalandromicSubsequence(s):
n = len(s)
memo = [[1]*n for _ in range(n)]
for i in range(1, n):
for j in range(n - i):
I = j
J = I + i
if s[I] == s[J]:
memo[I][J] = memo[I+1][J-1] + 2
else:
memo[I][J] = max(memo[I+1][J], memo[I][J-1])
return memo[0][n-1]
inputs =["agbbsba", "ssgbnss"]
for i in inputs:
print(i, end=" : ")
print(longestPalindrome(len(i), i), end = " : ")
print(longestPalandromicSubsequence(i))
|
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
def maxProduct(nums):
_max = nums[0]
_can = 1
for i in range(1, len(nums)):
if _max < 0 and nums[i] < 0 :
_can = _max*nums[i]
_max = _max *nums[i]
elif _max < 0 and nums[i] > 0 :
temp = _max* nums[i]
_max = max(_max*nums[i], _can*nums[i])
_can = temp
elif _max > 0 and nums[i] < 0:
temp = 1
if _can < 0:
temp = _max * nums[i]
_max = max(_max, _can * nums[i])
_can = temp
elif _max > 0 and nums[i] > 0:
temp = 1
if _can < 0:
temp = _can * nums[i]
_max = _max * nums[i]
_can = temp
elif nums[i] == 0:
_max = max(0, _max)
_can = _ma
return _max
l =[ 2,2,-2,-2,-2, -2, -2]
print(maxProduct(l)) |
"""
Given two words (start and end), and a dictionary,
find the length of shortest transformation sequence from start to end, such that only one letter can be changed at a time and each intermediate word must exist in the dictionary. For example, given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", the program should return its length 5.
"""
def isOneCharDiff(w1, w2):
if w1 == w2:
return False
if len(w1) == len(w2):
return isOneCharDiff_len(w1, w2)
_max = w1 if len(w1) > len(w2) else w2
_min = w1 if len(w1) < len(w2) else w2
for i in range(0, len(_max)):
substr = _max[:i]+_max[i+1:]
if substr == _min:
return True
return False
def isOneCharDiff_len(w1, w2):
same = 0;
for i in range(len(w1)):
if w1[i] == w2[i]:
same+=1
if same == len(w1) -1:
return True
return False
def ladder(start, end, d):
l = []
l.append(start)
val=[]
_ladder(start, end, d, l, val)
return val
def _ladder(start, end, d, l, val):
if isOneCharDiff(l[-1], end):
l.append(end)
val.append(l[:])
l.remove(end)
return
p = l[-1]
for e in d:
if isOneCharDiff(p, e) and e not in l:
l.append(e)
_ladder(start, end, d, l, val)
l.remove(e)
return
start = "hit"
end = "cog"
d = ["hot","dot","dog","lot","log"]
pathes = ladder(start, end, d)
for p in pathes:
print(p)
print("#"*100)
start = "hit"
end = "cog"
d = ["kit","dot","dog","got","log", "git", "gut", "hot"]
pathes = ladder(start, end, d)
for p in pathes:
print(p)
print("#"*100)
start = "hit"
end = "dogg"
d = ["kit","dot","dog","got","log", "git", "gut", "hot"]
pathes = ladder(start, end, d)
for p in pathes:
print(p) |
"""
if an element in an MxN matrix is 0,
its entire row and column are set to 0
"""
def MxN_zero_matrix(mxn):
c_zeros, l_zeros = set(), set()
for i in range(len(mxn)):
for j in range(len(mxn[0])):
if mxn[i][j] == 0:
c_zeros.add(j)
l_zeros.add(i)
for i in range(len(mxn)):
for j in range(len(mxn[0])):
if i in l_zeros or j in c_zeros:
mxn[i][j] = 0
return mxn
def mxnprint(mxn):
print("="*len(mxn[0])*2)
for i in range(len(mxn)):
for j in range(len(mxn[0])):
print(mxn[i][j], end = " ")
print(" ")
print("=" * len(mxn[0])*2)
input = [ [i for i in range(1, 5)] for i in range(5) ]
input[3][3] = 0
mxnprint(input)
MxN_zero_matrix(input)
mxnprint(input)
input = [ [i for i in range(-5, 1)] for i in range(5) ]
input[3][3] = 0
mxnprint(input)
MxN_zero_matrix(input)
mxnprint(input) |
def get_summ(one,two,delimiter='and'):
return(str(one)+delimiter+str(two))
a= get_summ('Learn','python')
print(a.upper())
|
########### Set up simple RSA-Environment:
p = 11 # prime
q = 13 # prime
m = 42 # message
###############################################################################
########### Calculate simple RSA-Environment:
N = p * q
phi = (p-1) * (q-1)
e = 23 # Coprime of phi -> ggt(e, phi) = 1
# TODO: "generate" by iterating down from phi and check for ggt
d = 47 # e * d = 1 mod phi(N)
# TODO: implement extended euclidean algorithm to find d (and k)
# e * d + k * phi = 1 = ggt(e, phi)
# pubkey: e, N
# privkey: d, N
print "calculated pubkey:"
print " e = ", e, "N = ", N
print "calculated privkey:"
print " d = ", d, "N = ", N
########### Crypt:
c = pow(m, e) % N
print "encrypted message:"
print " c = ", c
########### Decrypt:
m2 = pow(c, d) % N
print "decrypted message:"
print " m2 = ", m2
########### Cracking (calcluating d only knowing e and N, maybe some c): RSAP*
# to calculate d, I need e and phi
# (e is the coprime of phi!)
# phi is Euler's totient function of N -> count the relative primes to N
# => phi = (p-1) * (q-1) where p and q are the two (!) primes
# because N = p*q and phi(p*q) = phi(p) * phi(q) and phi(p) = p-1
# => Integer factorization! :(
|
import requests
api_key = '177590d4ced1c92728f2563be3fa6f12'
# function which makes a call to the API and returns the status code it receives. All data is hard coded so the return status
# should always be 200
def api_test():
try:
test_request = 'http://api.openweathermap.org/data/2.5/weather?q=san%20diego&appid=177590d4ced1c92728f2563be3fa6f12'
response = requests.get(test_request).json()
return response
except:
print('An error has occured')
response_status = api_test()
# Main function:
# function which retrieves the API data, and is called after the API test has passed.
def get_weather_data(city, key):
if len(city) < 2:
print('Please enter the name of a real city')
api_url = 'http://api.openweathermap.org/data/2.5/weather?q='+user_city+'&appid='+api_key
json_data_response = requests.get(api_url).json()
weather_desc = json_data_response.get('weather')
weather_temp = json_data_response.get('main')
# store some of the json data into variablse
weather_description = str(weather_desc[0].get('description'))
weather_tempurature = str(weather_temp.get('temp'))
weather_temp_feels_like = str(weather_temp.get('feels_like'))
# print weather data to the console
print('The weather forcast for ' + city + ' is: ' + '1. Weather description: ' + weather_description + ', ' + '2. Tempurature: ' + weather_tempurature + ', ' + '3. Feels like: ' + weather_temp_feels_like )
# if else statement to check connectivity to API
if response_status.get('cod') == '404':
print('Status code: 404, connection to API was unsuccessful')
else:
print('Status code: 200, connection to API was successful')
user_city = input('City Name: ')
get_weather_data(user_city, api_key)
|
Number1=int(input("The First Number is : "))
Number2=int(input("The Second Number is : "))
print(Number1,"+",Number2,"=",Number1+Number2)
print(Number1,"-",Number2,"=",Number1-Number2)
print(Number1,"*",Number2,"=",Number1*Number2)
print(Number1,"/",Number2,"=",int(Number1/Number2)) |
"""
Platform: CodeSignal
You need to sum up a bunch of fractions that have different denominators.
In order to do this, you need to find the least common denominator of all the
fractions. As a professional programmer, you know that the least common denominator is in fact their LCM.
For the given list of denominators, find the least common denominator by finding their LCM.
"""
from fractions import gcd
def leastCommonDenominator(denominators):
return functools.reduce(lambda x, y: x * y / gcd(x, y), denominators)
print(leastCommonDenominator([2, 3, 4, 5, 6]))
|
'''
Platform: CodeSignal
Here's how permutation cipher works: the key to it consists of all the letters of the alphabet written up in some order.
All occurrences of letter 'a' in the encrypted text are substituted with the first letter of the key, all occurrences
of letter 'b' are replaced with the second letter from the key, and so on, up to letter 'z' replaced with the last symbol of the key.
Given the password you always use, your task is to encrypt it using the permutation cipher with the given key.
For password = "iamthebest" and
key = "zabcdefghijklmnopqrstuvwxy", the output should be
permutationCipher(password, key) = "hzlsgdadrs"
'''
import string
def permutationCipher(password, key):
# method to create a mapping table
table = password.maketrans(string.ascii_lowercase,key) # If a character is not specified in the dictionary/table, the character will not be replaced
# returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table
return password.translate(table)
|
"""
Platform: CodeSignal
You don't have time to investigate the problem, so you need to
implement a function that will fix the given array for you. Given result,
return an array of the same length, where the ith element is equal to the
ith element of result with the last digit dropped.
"""
def fixResult(result):
def fix(x):
return x // 10
return list(map(fix, result))
|
import numpy
'''
Platform: HackerRank
You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array.
'''
a=numpy.array(list(map(int,input().split())))
print(numpy.reshape(a,(3,3))) |
#lass SortingRobot:
# def __init__(self, l):
# """
# SortingRobot takes a list and sorts it.
# """
# self._list = l
# self._item = None
# self._position = 0
# self._light = "OFF"
# self._time = 0
class SortingRobot:
def __init__(self, l):
"""
SortingRobot takes a list and sorts it.
"""
self._list = l # The list the robot is tasked with sorting
self._item = None # The item the robot is holding
self._position = 0 # The list position the robot is at
self._light = "OFF" # The state of the robot's light
self._time = 0 # A time counter (stretch)
def can_move_right(self):
"""
Returns True if the robot can move right or False if it's
at the end of the list.
"""
return self._position < len(self._list) - 1
def can_move_left(self):
"""
Returns True if the robot can move left or False if it's
at the start of the list.
"""
return self._position > 0
def move_right(self):
"""
If the robot can move to the right, it moves to the right and
returns True. Otherwise, it stays in place and returns False.
This will increment the time counter by 1.
"""
self._time += 1
if self._position < len(self._list) - 1:
self._position += 1
return True
else:
return False
def move_left(self):
"""
If the robot can move to the left, it moves to the left and
returns True. Otherwise, it stays in place and returns False.
This will increment the time counter by 1.
"""
self._time += 1
if self._position > 0:
self._position -= 1
return True
else:
return False
def swap_item(self):
"""
The robot swaps its currently held item with the list item in front
of it.
This will increment the time counter by 1.
"""
self._time += 1
# Swap the held item with the list item at the robot's position
self._item, self._list[self._position] = self._list[self._position], self._item
def compare_item(self):
"""
Compare the held item with the item in front of the robot:
If the held item's value is greater, return 1.
If the held item's value is less, return -1.
If the held item's value is equal, return 0.
If either item is None, return None.
"""
if self._item is None or self._list[self._position] is None:
return None
elif self._item > self._list[self._position]:
return 1
elif self._item < self._list[self._position]:
return -1
else:
return 0
def set_light_on(self):
"""
Turn on the robot's light
"""
self._light = "ON"
def set_light_off(self):
"""
Turn off the robot's light
"""
self._light = "OFF"
def light_is_on(self):
"""
Returns True if the robot's light is on and False otherwise.
"""
return self._light == "ON"
def sort(self):
"""
Sort the robot's list.
"""
# if can't move right and light is off
#if self.can_move_right() == False and self.light_is_on() == False:
# return self
# I NEED TO ESTABLISH A BASE CASE TO TERMINATE THE RECURSION. How do I know the sorting is done. That is the main problem. How Do i check the sort is complete. That is the base case
# if the lights off, then terminate
if self.light_is_on == False:
return self.l
self.set_light_on() # turn light on
# set light is on
if self.light_is_on() == True:
# pick up item by swapping none with the item at position 0
while self.can_move_right() == True:
self.swap_item()
# move to the right and then compare and then swap
self.move_right()
if self.compare_item() == 1:
self.swap_item()
# turn the light off at this location.
#self.set_light_off()
# repeat the entire process
#return self.sort()
# if we can't swap here, then keep moving right.
# decided to use while loop
#else:
# # turn light off
# self.set_light_off()
# # repeat theprocess
# return self.sort()
#if self.can_move_right() == False and selfcompare_item() == None:
# self.set_light_off()
#if we can't move right anymore, then goleft.
if self.can_move_right == False and self.can_move_left == True:
while self.can_move_left == True:
self.move_left()
if self.compare_item() == 1:
self.swap_item()
# once the while loop condition becomes false, repeat the function
return self.sort()
#return self.sort() + self.set_light_off()
#def sort(self):
# """
# Sort the robot's list.
# """
# #for i in self.l:
# for i in self.l:
# # define the current item
# self._item = self.l[i]
# if self.compare_item() == 1:
# self.swap_item()
# while self.move_right == True:
# for i in self.l:
# # define the current item
# self._item = self.l[i]
#
# if self.compare_item() == #1:
# self.swap_item()
# # what happens if no swap
#else:
# self._item = self.l[self._position]
# recursively repeat this process until when? How do we know the list is fully sorted.
#sort()
#for i in range(len(l)):
# # define the current item
# self._item = l[i]
#
# if move_right() == True:
# if compare_item() == 1:
# swap_item()
# # what happens if no #swap
# else:
# # compare it to what is in front
# if compare_item() == 1:
# # swap items if the one in #front is smaller
# swap_item()
# if move_right() == True:
# if move robot to the right is true,
# drop current item
# then repeat the process and the new item is what is at position 2
# if move robot right is false
# Fill this out
# beginning at index 0 and Index 1
# if the item at index 1 > index 0,
# then swap them. if not, move on and compare index 1 and index 2
# if you swap index 1 & 0, then move right and compare index 2 to index 3.
# repeat this process recursively until all items are sorted.
# robot at position 0, then picks up item at position 0.
# it then compares that item to the item in front of it.
# if the held item is greater than the item in front of it which means result is 1, then swap
# perform swap.
# then move right and pick up the next item
# and repeat the process.
#for i in range(len(l)):
# # define the current item
# self._item = l[i]
# # define the position to refer to
# self._position = l[i + 1]
#
# # compare it to what is in front
# if compare_item() == 1:
# # swap items if the one in #front is smaller
# swap_item()
# if move_right() == True:
# if move robot to the right is true,
# drop current item
# then repeat the process and the new item is what is at position 2
# if move robot right is false
if __name__ == "__main__":
# Test our your implementation from the command line
# with `python robot_sort.py`
l = [15, 41, 58, 49, 26, 4, 28, 8, 61, 60, 65, 21, 78, 14, 35, 90, 54, 5, 0, 87, 82, 96, 43, 92, 62, 97, 69, 94, 99, 93, 76, 47, 2, 88, 51, 40, 95, 6, 23, 81, 30, 19, 25, 91, 18, 68, 71, 9, 66, 1, 45, 33, 3, 72, 16, 85, 27, 59, 64, 39, 32, 24, 38, 84, 44, 80, 11, 73, 42, 20, 10, 29, 22, 98, 17, 48, 52, 67, 53, 74, 77, 37, 63, 31, 7, 75, 36, 89, 70, 34, 79, 83, 13, 57, 86, 12, 56, 50, 55, 46]
robot = SortingRobot(l)
robot.sort()
print(robot._list) |
print("this is an if elif and else code")
day=input("choose a day")
if day=="monday":
print("i do not have football today")
elif day=="tuesday":
print("i have football today")
elif day=="wednesday":
print("i do not have football today")
elif day=="thursday":
print("i do not have football today")
elif day=="friday":
print("i do not have football today")
elif day=="saturday":
print("i do not have football today")
elif day=="sunday":
print("i do not have football today")
else:
print("this is not a day of the week")
#and this is how to do an if elif and else code
|
import sqlite3
import csv
# Open csv file
readfile=open('20200318_account_snapshot.csv','r', newline='')
readfile=csv.reader(readfile, delimiter=',')
conn = sqlite3.connect('accounts.db')
cur = conn.cursor()
cur.execute('CREATE TABLE EOS (id INTEGER PRIMARY KEY AUTOINCREMENT, Account TEXT, Balance FLOAT)')
conn.commit()
count = 0
# read second row
for row in readfile:
account = row[1]
balance = row[2]
count = count + 1
# add to database
cur.execute('INSERT INTO EOS (id, Account, Balance) VALUES (NULL, ?, ?)', ('{}'.format(account) , '{}'.format(balance)))
# Delete first row
cur.execute("DELETE FROM EOS WHERE id = 1")
conn.commit()
conn.close()
print(count, 'entries addes to the database')
|
fname = input("Enter file name: ")
try:
fh = open(fname)
except FileNotFoundError:
print("File not found")
quit()
text = []
for line in fh:
add_text = line.split()
for word in add_text:
# print("Add ", word, "?")
# if word in text:
# print("Nope, not adding: ", word)
if word not in text:
text.append(word)
# print(word, " added")
text.sort()
print(text)
|
import re
name = input("Enter file:") # get file name from user
if len(name) < 1: # give a default if no file is given
name = "sample_text.txt"
handle = open(name)
sum = 0
for line in handle:
line = line.rstrip()
# print('line', line)
x = re.findall('[0-9]+', line)
# print('x:', x)
for xs in x:
# print('xs: ', xs)
try:
xs = int(xs)
except ValueError as err:
continue
sum += xs
print('sum: ', sum)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Some documentation"""
class Board:
def __init__(self, w, h):
self.width = w
self.height = h
self.grid = [[False] * w for i in range(h)]
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n < self.width * self.height:
y = int(self.n / self.width)
x = self.n % self.width
self.n += 1
return x, y, self.get_square(x, y)
else:
raise StopIteration
def set_square(self, x, y, state):
self.grid[y][x] = state
def get_square(self, x, y):
return self.grid[y][x]
def get_square_neighbors(self, x, y):
def _wrapped_point_(coordinate, limit):
if coordinate < 0:
return limit - abs(coordinate)
if coordinate >= limit:
return limit - coordinate
return coordinate
xl = _wrapped_point_(x-1, self.width) # XL
xm = _wrapped_point_(x+0, self.width) # XM
xr = _wrapped_point_(x+1, self.width) # XR
yt = _wrapped_point_(y-1, self.height) # YT
ym = _wrapped_point_(y+0, self.height) # YM
yb = _wrapped_point_(y+1, self.height) # YB
return [self.get_square(xl, yt),
self.get_square(xm, yt),
self.get_square(xr, yt),
self.get_square(xl, ym),
self.get_square(xr, ym),
self.get_square(xl, yb),
self.get_square(xm, yb),
self.get_square(xr, yb)]
def copy(self):
new_board = Board(self.width, self.height)
new_board.grid = list([i for i in self.grid])
return new_board
|
#tuple
tuple = ('Gerardo', 'Manrique', 19, 25, 'Nose')
#print("Todos los elementos de lista:", lista)
#print("Todos los elementos del tuple son:", tuple)
lista = ['Armando', 'Ruelas', 18, 'Mexicana', 'Sinaloa', 'Los Mochis']
nombre = lista[0]
apellido = lista[1]
edad = str(lista[2])
nacionalidad = lista[3]
estado = lista[4]
ciudad = lista[5]
a = nombre[0:3]
b = apellido[0:2]
c = edad[0:1]
d = nacionalidad[1:4]
token = a + "gaxAggQetaGAahH" + d + "12GaggaHcczxnjlku" + c + b
print(token)
|
#Variables
space = "---------------------"
string = "Hola soy un String"
print(string)
string = "Ahora soy otro valor"
print(string)
print(space)
a, b, c = "Hola", "Soy", "Armando"
print("El valor de las variables son:", a, b, c)
del a, b, c
#print("El valor actual de las variables son:", a, b, c)
#conversion de variables explicitamente
nombre = "Armando"
edad = 19
estatura = 1.80
concatenar = nombre + str(edad) + str(estatura)
print(space)
print("Mis datos son:", "Nombre:", nombre, "Edad:", ed
ad, "Estatura:", estatura)
#conversion de variables explicitamente de string a entero
print(space)
n = '5'
m = 2
suma = int(n) + m
print(suma)
print(space)
#Finalizacion
|
from re import compile, X
class Robot():
"""Simulate a robot moving on a 5x5 grid"""
def __init__(self):
self._x = 0
self._y = 0
self._f = None
def init_place(self):
"""if the first command to the robot is a PLACE command"""
if self._f == None:
return False
else:
return True
def parse(self, line):
"""Parse one command line and return valid components. An exception is raised if the line does not correspond to a valid command
string.
"""
if len(line) == 0:
raise ValueError('InvalidCommand')
tokens = line.strip().split()
# print ("tokens=", tokens)
cmd = tokens[0]
if cmd not in {'MOVE', 'LEFT', 'RIGHT', 'REPORT', 'PLACE'}:
raise ValueError('InvalidCommand')
coords = None
if cmd == 'PLACE':
if len(tokens) < 2:
raise ValueError('InvalidCommand')
PATTERN = compile(
r"""
(?P<x>\d+), # x coord
(?P<y>\d+), # y coord
(?P<f>NORTH|EAST|SOUTH|WEST) # facing
""", X
)
valid = PATTERN.search(tokens[1])
# print ("valid=", valid)
if not valid:
raise ValueError('InvalidCommand')
coords = dict(
x=int(valid['x']), # regexp ensures the str is a digit
y=int(valid['y']),
f=valid['f'],
)
# print ("return=", cmd, coords)
return cmd, coords
def get_position(self):
return dict(x=self._x, y=self._y, f=self._f)
def valid_position(self, c):
"""verify the position"""
X_RANGE = {0, 1, 2, 3, 4}
Y_RANGE = {0, 1, 2, 3, 4}
F_RANGE = {'NORTH', 'EAST', 'SOUTH', 'WEST'}
if c['x'] in X_RANGE and c['y'] in Y_RANGE and c['f'] in F_RANGE:
return True
else:
return False
def update_position(self, c):
"""set position"""
self._x = c['x']
self._y = c['y']
self._f = c['f']
def move(self):
"""Move the robot one unit in the direction it is currently facing"""
c = self.get_position()
f = c['f']
if f == 'NORTH':
c['y'] += 1
elif f == 'EAST':
c['x'] += 1
elif f == 'SOUTH':
c['y'] -= 1
elif f == 'WEST':
c['x'] -= 1
if self.valid_position(c):
self.update_position(c)
else:
raise ValueError('InvalidPosition')
def __str__(self):
return "{},{},{}".format(self._x, self._y, self._f)
def report(self):
print ("{},{},{}".format(self._x, self._y, self._f))
def turn(self, cmd):
COMPASS = {
'NORTH': {
'left': 'WEST',
'right': 'EAST'
},
'WEST': {
'left': 'SOUTH',
'right': 'NORTH'
},
'SOUTH': {
'left': 'EAST',
'right': 'WEST'
},
'EAST': {
'left': 'NORTH',
'right': 'SOUTH'
},
}
c = self.get_position()
f = c['f']
if cmd == 'LEFT':
c['f'] = COMPASS[f]['left']
else:
c['f'] = COMPASS[f]['right']
self.update_position(c) |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 16:31:45 2019
@author: Olli
--- Day 1: The Tyranny of the Rocket Equation ---
--- Part One ---
Santa has become stranded at the edge of the Solar System while delivering
presents to other planets! To accurately calculate his position in space,
safely align his warp drive, and return to Earth in time to save Christmas,
he needs you to bring him measurements from fifty stars.
Collect stars by solving puzzles. Two puzzles will be made available on each
day in the Advent calendar; the second puzzle is unlocked when you complete the
first. Each puzzle grants one star. Good luck!
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper.
They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based on its mass. Specifically, to
find the fuel required for a module, take its mass, divide by three, round
down, and subtract 2.
The Fuel Counter-Upper needs to know the total fuel requirement. To find it,
individually calculate the fuel needed for the mass of each module (your puzzle
input), then add together all the fuel values.
What is the sum of the fuel requirements for all of the modules on your
spacecraft?
Module masses (input values) are saved in file input.txt
"""
import numpy as np
mass = np.loadtxt('input.txt')
temp = [np.floor(x/3)-2 for x in mass]
print(int(sum(temp))) |
# Make a function that takes a sequence (like a list, string, or tuple) and a number n and returns
# the last n elements from the given sequence, as a list.
#
# Bonus 1
#
# As a bonus, make your function return an empty list for negative values of n.
#
# Bonus 2
#
# As a second bonus, make sure your function works with any iterable, not just sequences.
#
# See if you can make your function relatively memory efficient (if you're looping over a very long
# iterable, don't store the entire thing in memory).
# TODO Finish test_iterator
def tail(seq, num: int):
sequence_len = len(list(seq))
print(f"sequence_len, num: {sequence_len, num}")
if num <= 0:
return []
elif num > sequence_len:
return list(seq)
else:
# print(f"sequence_len: {sequence_len}")
return list(seq[(sequence_len - num):])
# self.assertEqual(tail(nums, 2), [9, 16]) # Consuming the generator
if __name__ == '__main__':
print(tail([1, 2], 1))
print()
print(tail([1, 2], 2))
print()
print(tail("hello", 0))
print(tail([1, 2, 3, 4, 5], 0))
print(tail((6, 7, 8, 9, 0), 0))
print()
print(tail("hello", 1))
print(tail([1, 2, 3, 4, 5], 1))
print(tail((6, 7, 8, 9, 0), 1))
print()
print(tail("hello", 2))
print(tail([1, 2, 3, 4, 5], 2))
print(tail((6, 7, 8, 9, 0), 2))
print()
print(tail("hello", -2))
print(tail([1, 2, 3, 4, 5], -2))
print(tail((6, 7, 8, 9, 0), -2))
print()
print(tail("hello", 7))
print(tail([1, 2, 3, 4, 5], 7))
print(tail((6, 7, 8, 9, 0), 7))
|
class Solution:
def isValid(self, s: str) -> bool:
# result = []
# dicts = {'(': ')', '{': '}', '[': ']'}
# if len(s) == 0:
# return True
# else:
# for paranthesis in s:
# print(paranthesis)
# try:
# if dicts[result[-1]] == paranthesis:
# result.pop()
# else:
# result.append(paranthesis)
# except:
# result.append(paranthesis)
# print(result)
# if len(result) == 0:
# return True
#
# return False
stack = []
# Hash map for keeping track of mappings. This keeps the code very clean.
# Also makes adding more types of parenthesis easier
mapping = {")": "(", "}": "{", "]": "["}
# For every bracket in the expression.
for char in s:
# If the character is an closing bracket
if char in mapping:
# Pop the topmost element from the stack, if it is non empty
# Otherwise assign a dummy value of '#' to the top_element variable
top_element = stack.pop() if stack else '#'
print(top_element, char, stack)
# The mapping for the opening bracket in our hash and the top
# element of the stack don't match, return False
if mapping[char] != top_element:
return False
else:
# We have an opening bracket, simply push it onto the stack.
stack.append(char)
print(stack)
# In the end, if the stack is empty, then we have a valid expression.
# The stack won't be empty for cases like ((()
return not stack
if __name__ == '__main__':
solution = Solution()
val = '()([]){}'
print(solution.isValid(val))
|
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
i = 0
while i < len(nums):
if nums[i] < target:
i = i + 1
elif nums[i] == target:
return i
else:
break
return i
if __name__ == '__main__':
solution = Solution()
lists = [1, 3, 5, 6]
lists1 = [1, 3, 4, 6]
val = 4
res = solution.searchInsert(lists1, val)
print(res)
|
import math
import os
import random
import re
import sys
from itertools import combinations
# Complete the countTriplets function below.
def countTriplets(arr, r):
# SLOW SOLUTION #1
# for index, number in enumerate(arr):
# for number in range(index, len(arr) - 1):
# triplets.append(triplet)
# indexes = [i for i in range(len(arr))]
# c = list(combinations(indexes, 3))
# print(c)
# clists = list(map(list, c))
# print(clists)
# for f, s, t in clists:
# check1 = arr[f] * r == arr[s]
# check2 = arr[s] * r == arr[t]
# if check1 and check2:
# triplets.append((f,s,t))
# return len(triplets)
# FASTER but still slow enough to fail 4 (runtime errors)
# d = {}
# for index, num in enumerate(arr):
# if num not in d:
# d[num] = [index]
# else:
# d[num].append(index)
# print(d)
# triplets = []
# for k, v in d.items():
# if k * r in d:
# indexes1 = d[k * r]
# if k * r * r in d:
# indexes2 = d[k * r * r]
# print(v, indexes1, indexes2)
# for i in range(len(v)):
# for j in range(len(indexes1)):
# for k in range(len(indexes2)):
# if v[i] < indexes1[j] and indexes1[j] < indexes2[k]:
# triplets.append((v[i], indexes1[j], indexes2[k]))
# print(triplets)
# return len(triplets)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
|
def is_pangram(sentence):
s=set(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t","u","v","w","x","y","z"])
sentence=sentence.lower()
for i in range(len(sentence)):
if sentence[i] in s:
s.remove(sentence[i])
return len(s)==0
|
# Python Program to replace all occurences of 'a' with $ in a String
name = input("Enter a name:")
print("Your entered name is:",name)
name = name.replace('a','$')
print(name)
|
#
# Project Euler Solution
# Problem ID: 2
#
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
#
def fibonacci():
x = 0
res = 0
n = 1
while n <= 4000000:
if n % 2 == 0:
res = res + n
x = x + n
n = x - n
return print(f'The sum of even Fibonacci whose values do not exceed four million is: {res}')
if __name__ == '__main__':
fibonacci()
|
#!/usr/bin/env python
# coding: utf-8
# In[22]:
import numpy as np
import scipy as sp
import scipy.stats
import matplotlib.pyplot as plt
text_file = open("/Users/rishika/Desktop/anomaly_detection.txt", "r+")
lines = text_file.readlines()
new_file=[]
text_file.close()
for item in lines:
new_file.append(item.strip())
string_array= np.array(new_file)
float_array= string_array.astype(np.float)
def mean_cal(array):
mean= np.mean(array)
return mean
def standard_deviation_cal(array):
standard_deviation= np.std(array)
return standard_deviation
def anomaly_detection(array):
index=0
array.sort()
while index < len(array):
item= array[index]
array1=np.delete(array,index,0)
if ((array[index]) < (mean_cal(array1)-(3* standard_deviation_cal(array1)))) or (array[index]) > ((3* standard_deviation_cal(array1))+ mean_cal(array1)):
cal_times=abs( ((array[index] - mean_cal(array1))/standard_deviation_cal(array1)))
print("Remove " + str(array[index]) +" from the list because it's "+ str(cal_times)+" times the standard deviation of the list without it " )
print(str(array[index])+" is removed from the list")
array=np.delete(array,index,0)
index=0
else:
index+=1
print("No more anomaly detected!")
# x=array
# v=sp.stats.norm.pdf(array,mean_cal(array),standard_deviation_cal(array))
# return plt.plot(x,v)
print(anomaly_detection(float_array))
|
# Developer: Wellington
# Data: 18/09/2021
# Description: Scrip developed to simulate a calculator by using methods and functions
# it's a part of course Python Fundamentos at DSA
# Create a calculator method
def operations(parameter):
# Here we have some simple function which will doing the math operations
def addtion(n1, n2):
return n1+n2
def subtraction(n1, n2):
return n1-n2
def multiplication(n1, n2):
return n1*n2
def division(n1, n2):
return n1/n2
# Create a serie of condition that will access the math optons
if parameter == 1:
print('\n')
print('----------You chose the addtion operation-------')
print('\n')
n1 = int(input("Informe the first number: "))
n2 = int(input("Informe the second number: "))
#addtion = lambda n1,n2: n1 + n2
#Call the function math which was create above
addtion = addtion(n1,n2)
print('\n')
print('The addtion will be %s'%(addtion))
elif parameter == 2:
print('\n')
print('----------You chose the subtraction operation-------')
print('\n')
n1 = int(input("Informe the first number: "))
n2 = int(input("Informe the second number: "))
#subtraction = lambda n1,n2: n1 + n2
subtraction = subtraction(n1,n2)
print('The subtraction will be %s'%(subtraction))
print('\n')
elif parameter == 3:
print('\n')
print('----------You chose the multiplication operation-------')
print('\n')
n1 = int(input("Informe the first number: "))
n2 = int(input("Informe the second number: "))
#multiplication = lambda n1,n2: n1 + n2
multiplication = multiplication(n1,n2)
print('\n')
print('The multiplication will be %s'%(multiplication))
elif parameter == 4:
print('\n')
print('----------You chose the division operation-------')
print('\n')
n1 = int(input("Informe the first number: "))
n2 = int(input("Informe the second number: "))
#division = lambda n1,n2: n1 + n2
division = division(n1,n2)
print('\n')
print('The division will be %s'%(division))
# Condition else create if the user did not type any of the options above
else:
print(' Option unvaliable. The program will be finish')
# Create a dictionary with key and value which means the operation that this program has.
collections_actions = {1:'addtion',
2:'subtraction',
3:'multiplication',
4:'division'}
# This loop will print the options on the screen
for i,j in collections_actions.items():
print(str(i) +" - "+ str(j))
print('\n')
# Ask for the user to enter oque option which had described above.
ope = int(input("Inform by type one number to start the calculation: "))
# Call the method by passing the option chose for the user.
operations(ope)
|
# -*- coding: utf8 -*-
class MyClass:
def __new__(cls, *args, **kwargs):
print("inside MyClass.__new__()")
return super(MyClass, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print("inside MyClass.__init__()")
def __call__(self, *args, **kwargs):
print("inside MyClass.__call__()")
print("defind class MyClass finished")
print("-" * 50)
x = MyClass()
print("-" * 50)
x()
|
"""
Single Responsibility Principle (Princípio da responsabilidade única)
'Uma classe deve ter apenas um motivo para mudar'
Uma classe deve ter apenas um trabalho, Se uma classe tem mais de uma
responsabilidade, vira acoplada. Uma mudança em uma responsabilidade
resulta na modificação de outra responsabilidade.
"""
"""
Uma forma de resolver o problema é desacoplar as responsabilidades em diferentes
classes, e essa classe tem apenas a responsabilidade de armazenar o registro no banco.
"""
class Book:
_author: str
_title: str
def __init__(self, author: str, title: str):
self._author = author
self._title = title
def get_author(self) -> str:
return self._author
def get_title(self) -> str:
return self._title
class BookDB:
def get_book(self, id: int) -> Book:
pass
def save(self, book: Book) -> Book:
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@author:JaNG
@email:[email protected]
'''
class Animal:
def __init__(self,name):
self.name = name
hobbie = 'meat'
@classmethod #类方法 只能通过 Animal.talk()不能访问实例变量
def talk(self):
print('{} is talking ...'.format(self.hobbie))
@staticmethod #静态方法 不能访问类变量 和实例变量!!
def walk():
print('is wolking ...')
@property #属性 把方法改为属性 不用()就可以调用
def habit(self):
print("{} habit is XXOO".format(self.name))
@habit.setter #如果特别想给 habit 赋值 可以这么用
def habit(self, num):
self.num = num
print(self.num)
@habit.deleter #如果想删除
def habit(self):
print('total player got deleted')
del self.num
#类方法
# Animal.talk()
# d = Animal('sanjiang')
# d.talk()
# d = Animal('Sanjiang')
# d.habit
# property 传值
d = Animal('Sanjiang')
d.habit = 3
print(d.habit)
|
"""
desc: Starter code for simple linear regression example using tf.data
线性拟合略显智障,我们在这里找到曲线拟合效果, Y = ax^2 + bx + c
author: LongYinZ
date: 2018.1.30
"""
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import utils
from advanced_util import huber_loss
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
DATA_FILE = '../data/birth_life_2010.txt'
# Step 1: 读数据
data, n_samples = utils.read_birth_life_data(DATA_FILE)
# Step 2: 创建 data set 和 iterator遍历器
data_set = tf.data.Dataset.from_tensor_slices((data[:, 0], data[:, 1]))
iterator = data_set.make_initializable_iterator()
X, Y = iterator.get_next()
# Step 3: create weight and bias, initialized to 0
w1 = tf.get_variable('weight1', initializer=tf.constant(0.0))
w2 = tf.get_variable('weight2', initializer=tf.constant(0.0))
b = tf.get_variable('bias', initializer=tf.constant(0.0))
# Step 4: build model to predict Y
Y_predicted = X**2 * w1 + X * w2 + b
# Step 5: use the square error as the loss function
# loss = tf.square(Y - Y_predicted, name='loss')
loss = huber_loss(Y, Y_predicted)
# Step 6: using gradient descent with learning rate of 0.001 to minimize loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)
start = time.time()
with tf.Session() as sess:
# Step 7: initialize the necessary variables, in this case, w and b
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('../graphs/Demo8', sess.graph)
# Step 8: train the model for 100 epochs
for i in range(100):
sess.run(iterator.initializer) # initialize the iterator
total_loss = 0
try:
while True:
_, loss_ = sess.run([optimizer, loss]) # 不需要feed_dict,因为数据在tensorflow中封装好了
total_loss += loss_
except tf.errors.OutOfRangeError:
pass
print('Epoch {0}: {1}'.format(i, total_loss / n_samples))
writer.close()
w1_out, w2_out, b_out = sess.run([w1, w2, b])
print('w1: %f,w2: %f, b: %f' % (w1_out, w2_out, b_out))
print('Took: %f seconds' % (time.time() - start))
# uncomment the following lines to see the plot
plt.plot(data[:, 0], data[:, 1], 'bo', label='Real data')
# 构建画图数据
x_arr = data[:, 0]
x_arr = np.sort(x_arr)
y_arr = []
for item in x_arr:
y_arr.append(item**2*w1_out + item*w2_out + b_out)
plt.plot(x_arr, y_arr, color='red', label='Predicted data')
plt.legend()
plt.show()
"""
tensorboard --logdir="graphs/Demo8" --port 6006
http://ArlenIAC:6006
"""
|
#Write the program to print vowels and consonant letters from "gnulinux"
#Vowels variables
Vowels=[
#defining empty lists
vowles1 = []
conatants = []
#giving input
string11 = "gnulinux"
#sepearating constants from vowels
for i in string11:
if i in Vowels:
vowles1.append(i)
else:
constants.append(i)
#Printing results
print("Constants : ")
print(constants)
print("vowels : ")
print(vowles1) |
def generate_powerset(input_set):
'''
Enumerate all subsets of a given string
input_set (list): an arbitrary list. Assume that it does not contain any duplicate elements.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of lists containing all the subsets of input_set
Example:
>>> generate_powerset([1, 2, 3])
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Note: depending on your implementation, you may return the susbsets in
a different order than what is listed here.
'''
pass #delete this line and replace with your code here |
import random
import math
import numpy as np
import matplotlib.pyplot as plt
def monte_method(N):#モンテカルロ法関数
point = 0
for i in range(N):
x = random.random()
y = random.random()
if x*x+y*y < 1.0:
point += 1
pi = 4.0 * point / N#円周率の近似値の計算
return pi
count=0#i回目計算のためのカウンタ
monte_method_1=0#18~27行目 i回目の計算結果の変数
monte_method_2=0
monte_method_3=0
monte_method_4=0
monte_method_5=0
monte_method_6=0
monte_method_7=0
monte_method_8=0
monte_method_9=0
monte_method_10=0
In_1=0#27~34行目 グラフ出力のための変数
In_3=0
In_5=0
In_7=0
σn_1=0
σn_3=0
σn_5=0
σn_7=0
def In():#πの推定値の算出関数
sum=(monte_method_1+monte_method_2+monte_method_3+monte_method_4+monte_method_5\
+monte_method_6+monte_method_7+monte_method_8+monte_method_9+monte_method_10)/10
return sum
def σn():#πの推定値の標準偏差の算出関数
sum2=math.sqrt(((((monte_method_1-In())**2)+((monte_method_2-In())**2)+((monte_method_3-In())**2)\
+((monte_method_4-In())**2)+((monte_method_5-In())**2)+((monte_method_6-In())**2)\
+((monte_method_7-In())**2)+((monte_method_8-In())**2)+((monte_method_9-In())**2)\
+((monte_method_10-In())**2))/9))
return sum2
N=10#乱数の数 10個
print("乱数の数:", 10)
for a in range(10):#独立に10回計算、出力
b = monte_method(N)
count+=1
if count==1:
monte_method_1=b
elif count==2:
monte_method_2=b
elif count==3:
monte_method_3=b
elif count==4:
monte_method_4=b
elif count==5:
monte_method_5=b
elif count==6:
monte_method_6=b
elif count==7:
monte_method_7=b
elif count==8:
monte_method_8=b
elif count==9:
monte_method_9=b
elif count==10:
monte_method_10=b
print(str(count)+"回目:π =",b)
print("πの推定値:",round(In(),4))
print("πの推定値の標準偏差:",round(σn(),4))
In_1=In()
σn_1=σn()
print("-------------------------------")
N=10**3#乱数の数 10**3個
count=0#カウンタの初期化
print("乱数の数:", 10**3)
for a in range(10):#独立に10回計算、出力
b = monte_method(N)
count+=1
if count==1:
monte_method_1=b
elif count==2:
monte_method_2=b
elif count==3:
monte_method_3=b
elif count==4:
monte_method_4=b
elif count==5:
monte_method_5=b
elif count==6:
monte_method_6=b
elif count==7:
monte_method_7=b
elif count==8:
monte_method_8=b
elif count==9:
monte_method_9=b
elif count==10:
monte_method_10=b
print(str(count)+"回目:π =",b)
print("πの推定値:",round(In(),4))
print("πの推定値の標準偏差:",round(σn(),4))
In_3=In()
σn_3=σn()
print("-------------------------------")
N=10**5#乱数の数 10**5個
count=0#カウンタの初期化
print("乱数の数:", 10**5)
for a in range(10):#独立に10回計算、出力
b = monte_method(N)
count+=1
if count==1:
monte_method_1=b
elif count==2:
monte_method_2=b
elif count==3:
monte_method_3=b
elif count==4:
monte_method_4=b
elif count==5:
monte_method_5=b
elif count==6:
monte_method_6=b
elif count==7:
monte_method_7=b
elif count==8:
monte_method_8=b
elif count==9:
monte_method_9=b
elif count==10:
monte_method_10=b
print(str(count)+"回目:π =",b)
print("πの推定値:",round(In(),4))
print("πの推定値の標準偏差:",round(σn(),4))
In_5=In()
σn_5=σn()
print("-------------------------------")
N=10**7#乱数の数 10**7個
count=0#カウンタの初期化
print("乱数の数:", 10**7) # 乱数の数: 10
for a in range(10):#独立に10回計算、出力
b = monte_method(N)
count+=1
if count==1:
monte_method_1=b
elif count==2:
monte_method_2=b
elif count==3:
monte_method_3=b
elif count==4:
monte_method_4=b
elif count==5:
monte_method_5=b
elif count==6:
monte_method_6=b
elif count==7:
monte_method_7=b
elif count==8:
monte_method_8=b
elif count==9:
monte_method_9=b
elif count==10:
monte_method_10=b
print(str(count)+"回目:π =",b)
print("πの推定値:",round(In(),4))
print("πの推定値の標準偏差:",round(σn(),4))
In_7=In()
σn_7=σn()
"""
left = np.array([10,10**3,10**5,10**7])#乱数の数と推定値の関係グラフ
height = np.array([In_1,In_3,In_5,In_7])
plt.plot(left, height)
plt.title('Relationship between random numbers and E-π')
plt.xlabel('Number of random numbers')
plt.ylabel('Estimated value of π')
plt.show()
left = np.array([10,20,30,40])#間隔を一定にしたバージョン
height = np.array([In_1,In_3,In_5,In_7])
plt.plot(left, height)
plt.title('Relationship between random numbers and E-π')
plt.xlabel('Number of random numbers')
plt.ylabel('Estimated value of π')
plt.show()
"""
"""
left = np.array([10,10**3,10**5,10**7])##乱数の数と推定値の標準偏差の関係グラフ
height = np.array([σn_1,σn_3,σn_5,σn_7])
plt.plot(left, height)
plt.title('Relationship between random numbers and S-π')
plt.xlabel('Number of random numbers')
plt.ylabel('Standard deviation of π')
plt.show()
left = np.array([10,20,30,40])#間隔を一定にしたバージョン
height = np.array([σn_1,σn_3,σn_5,σn_7])
plt.plot(left, height)
plt.title('Relationship between random numbers and S-π')
plt.xlabel('Number of random numbers')
plt.ylabel('Standard deviation of π')
plt.show()
"""
|
# -*- coding: utf-8 -*-
import Sort
#Sort.testAlgorithms([10, 20, 30, 40, 50, 60])
test = [3,2,3,4,45,66,1,22,42]
#Sort.Bubble(test)
Sort.QuickSort(test, 0, len(test) - 1, rand = True)
print(test) |
class node:
def __init__(self, data):
self.data=data;
def left_child(self,lc):
assert lc.data<self.data
self.left=lc
def right_child(seld,rc):
assert rc.data>self.data
self.right=rc
arr=eval(input("Enter BST data: "))
root=node(arr[0])
def add_node(n,e):
if e<n.data:
if not n.left:
n.left(node(e))
else:
add_node(n.left,e)
else:
if not n.right:
n.right(node(e))
else:
add_node(n.right,e)
for i in range(len(arr)):
add_element(root,i)
def print_tree(root):
print(root.data)
|
aa=input("Enter Your Name : ")
print("Hello", aa, "Welcome to Ankur's Calculator Programme")
a=int(input("Enter Your First Number : "))
b=int(input("Enter Your Secod Number : "))
c=int(input('''Press (1 for Addition)
(2 for Subtraction)
(3 for Multiplication)
(4 for Division) For your preffered result\n'''))
if c==1:
summ=a+b
print('On Adding',a,'and',b,'we get',summ)
elif c == 2:
minus=a-b
print("On Subtracting",a,'from',b,'we get',minus)
elif c == 3:
mul=a*b
print('On Multiplying',a,'with',b,'we get',mul)
elif c == 4:
div=a/b
print("On Dividing",a,"with",b,"We get",div)
print('''Thank You For Using Ankur's Calculator Programme
Have A Nice Day Ahead''') |
"""This example shows how to create a scatter plot using the `shell` package.
"""
# Major library imports
from numpy import linspace, random, pi
# Enthought library imports
from chaco.shell import plot, hold, title, show
# Create some data
x = linspace(-2*pi, 2*pi, 100)
y1 = random.random(100)
y2 = random.random(100)
# Create some scatter plots
plot(x, y1, "b.")
hold(True)
plot(x, y2, "g+", marker_size=2)
# Add some titles
title("simple scatter plots")
# This command is only necessary if running from command line
show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.