text stringlengths 37 1.41M |
|---|
N=int(input('Введите сколько прошло секунд с начала суток: '))
x = N % 3600
x = N // 60
if N > 3600:
x = x % 60
print('Количество полных минут, прошедших с начала последнего часа: ',x)
|
from math import*
x = float(input('Введите число: '))
if x >= 0.2 and x <= 0.9 :
f = sin(x)
else:
f = 1
print (round(f,3))
|
def Quatro (a,b,c):
Quat = (a+b+c)/3
return Quat
a,b,c = map(int,input('Введите три числа:').split())
print (Quatro (a,b,c))
|
import random
# THE PLANNING PHASE
# Dealer cards
dealer_cards = []
# Player cards
player_cards = []
# Deal the cards
# Display the cards
# Dealer Cards
while len(dealer_cards) != 2:
dealer_cards.append(random.randint(1, 11))
if len(dealer_cards) == 2:
print("Dealer has X &", dealer_cards[1])
# Player Cards
while len(player_cards) != 2:
player_cards.append(random.randint(1, 11))
if len(player_cards) == 2:
print("You have ", player_cards)
# Sum of the Dealer cards
if sum(dealer_cards) == 21:
print("Dealer has 21 and wins!")
elif sum(dealer_cards) > 21:
print("Dealer has busted!")
# Sum of the Player cards
while sum(player_cards) < 21:
action_taken = str(input("Do you want to stay or hit? "))
if action_taken == "hit":
player_cards.append(random.randint(1, 11))
print("You now have a total of " + str(sum(player_cards)) + " from these cards ", player_cards)
else:
print("The dealer has a total of " + str(sum(dealer_cards)) + " with ", dealer_cards)
print("You have a total of " + str(sum(player_cards)) + " with ", player_cards)
if sum(dealer_cards) > sum(player_cards):
print("Dealer wins!")
else:
print("You win!")
break
if sum(player_cards) > 21:
print("You BUSTED! Dealer wins.")
elif sum(player_cards) == 21:
print("You have BLACKJACK! You Win!! 21")
print (' cores used: %d' % cpus)
print (' total simulations: %d' % simulations)
print (' simulations/s: %d' % (float(simulations) / finish_time))
print (' execution time: %.2fs' % finish_time)
print (' win percentage: %.2f%%' % ((win / float(simulations)) * 100))
print (' draw percentage: %.2f%%' % ((draw / float(simulations)) * 100))
print (' lose percentage: %.2f%%' % ((lose / float(simulations)) * 100))
print |
# This is Exercise 6 : Strings and Text
# Variable including how many type of people with sentence.
x = "There are %d types of people." % 10
# Store strings in Variable
binary = "binary"
# Again store strings in variable.
do_not = "don't"
# Store a sentence with above two variables in variable.
y = "Those who know %s and those who %s." % (binary, do_not)
# Print a sentence of type of people as variable
print x
# Print a sentence which stored in variable
print y
# Print a sentence with varibel which stored sentence but using formatting
print "I said: %r" % x
# Again print another sentence with variable which stored sentence but using formatting
print "I also said: '%s'." %y
# Create Boolean
hilarious = False
# Store a sentence in a variable with formatting
joke_evaluation = "Isn't that joke so funny?! %r" # Here %r is used for debuging.
# Print Boolean and sentence which including formatting in a variable
print joke_evaluation % hilarious
# Create a variable including a sentence
w = "This is the left side of..."
# Again create a variable including a sentence
e = "a string with a right side."
# Print above two variables which includes sentences using '+' concatnation
print w + e |
# this is exercise 33: while loop
i = 0 # a variable storing "0"
numbers = [] # a variable storing empty arrays
# while runt till 6
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num |
# This is Exercise 15: Reading Files
# Import sys modules and argv is an argument variable
# which holds arguments that you pass on Pyhton script
from sys import argv
# Unpacking and assing value to variables
script, filename = argv
# A variable storing function to open file.
txt = open(filename)
# Printing a sentence saying filename
print "Here's your file %r:" % filename
# Printing a function to read file
print txt.read()
# Printing a sentence to read file again
print "Type the filename again:"
# A variable asking input
file_again = raw_input("> ")
# A variable to open a file
txt_again = open(file_again)
# A variable to read file
print txt_again.read() |
# This is Exercise 18 : Names, Variables, Code, Funcions
# this one is like your script with argv
def print_two(*args):
# two argv is equal to one argv
arg1, arg2 = args
# print both argv
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can to this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
# create funciton with one argument
def print_one(arg1):
# print the argument
print "arg1: %r" % (arg1)
# this one takes no arguments
# create function with no arguments
def print_none():
# print the argument in function
print "I got nothin'."
# Callback functions with two argument
print_two("Vaibhav", "Mule")
# Again Callback function with two argument
print_two_again("Vaibhav", "Mule")
# Callback the function with one argument
print_one("First!")
# Callback the function with no argument
print_none() |
import sys
import numpy
import math
chartext=list(input('Entr the text to be encrypted:')) #only capital letters. No spaces
print('the text entered is:',chartext)
asciitext=[]
for d in range(len(chartext)):
asciitext.append(ord(chartext[d]))
asciitext=numpy.asarray(asciitext)
asciitext=asciitext-65
print('the numeric form of text is:',asciitext)
length=len(chartext)
print('length of the text is:',length)
key=list(input('Enter key')) #only capital letters
for d in range(len(key)):
key[d]=ord(key[d])
key=numpy.asarray(key)
key=key-65
print('the numeric of key is:',key)
keylen=int(input('enter matrix dimension'))
keymatrix=numpy.asarray(key[0:keylen*keylen])
keymatrix=numpy.reshape(keymatrix,(keylen,keylen))
print('keymatrix:')
print(keymatrix)
detkeymatrix=numpy.linalg.det(keymatrix)
detkeymatrix=math.ceil(detkeymatrix%26)
print('det of keymatrix is:',detkeymatrix)
cokeymatrix=numpy.linalg.inv(keymatrix).T*numpy.linalg.det(keymatrix)
adjkeymatrix=numpy.matrix.transpose(cokeymatrix)
adjkeymatrix=adjkeymatrix%26
print('adjoint of keymatrix is:')
print(adjkeymatrix)
detinverse=-1
for z in range(1,25):
if (detkeymatrix*z)%26==1:
detinverse=z
break
if detinverse==-1:
print('detinversen not initialized')
exit()
print('det inverse is:',detinverse)
keyinverse=detinverse*adjkeymatrix
keyinverse=keyinverse%26
print('keyinverse is:')
print(keyinverse)
for x in range(0,length-keylen+1,keylen):
tempmatrix=numpy.asarray(asciitext[x:x+keylen])
tempmatrix=numpy.reshape(tempmatrix,(keylen,1))
alpha=numpy.array(tempmatrix).tolist()
print('temp matrix is:')
print(tempmatrix)
enc=numpy.matmul(keymatrix,tempmatrix)
enc=numpy.mod(enc,26)
print('encrypted text is:')
print(enc)
dec=numpy.matmul(keyinverse,enc)
dec=numpy.mod(dec,26)
print('decrypted text is:')
print(dec)
|
def make_matrix(A, matrix):
dummy_matrix = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
for k in range(N):
dummy_matrix[i][j] += (matrix[i][k] * A[k][j])
dummy_matrix[i][j] %= 1000
return dummy_matrix
def matmul(A, B):
if (B == 1):
for i in range(N):
for j in range(N):
A[i][j] %= 1000
return A
elif ((B % 2) == 1):
matrix = matmul(A, B - 1)
new_matrix = make_matrix(A, matrix)
return new_matrix
else:
matrix = matmul(A, B // 2)
new_matrix = make_matrix(matrix, matrix)
return new_matrix
import sys
sys.stdin = open('input.txt')
N, B = map(int, input().split())
A = []
for _ in range(N):
A.append(list(map(int, input().split())))
result = matmul(A, B)
for row in result:
print(*row) |
import sys
sys.stdin = open('input.txt')
n = int(input())
dic = dict()
for i in range(n):
a,b = map(str, input().split())
if b == "leave":
dic[a] = False
else:
dic[a] = True
dic = sorted(dic.items(),key = lambda x:x[0],reverse = True)
for name, check in dic:
if check:
print(name) |
import sys
sys.stdin = open('input.txt')
a = int(input())
operate = input()
b = int(input())
if(operate == '+'):
print(a+b)
elif(operate == '*'):
print(a*b) |
a = int(input())
result = 0
for i in range(1, a+1):
result = result + i
print(result) |
#coding:utf-8
#图形的缩放
import cv2 as cv
import numpy as np
img = cv.imread("D:/python_file/Opencv3_study_file/images/!face.png")
height,width = img.shape[:2]
res1 = cv.resize(img, (int(width/2), int(height/2)), interpolation=cv.INTER_CUBIC)
res2 = cv.resize(img,(2*width,2*height),interpolation = cv.INTER_CUBIC)
cv.imshow('img',res1)
cv.imshow('img2',res2)
cv.waitKey(0)
cv.destroyAllWindows()
|
from collections import OrderedDict
class CircularOrderedDict:
def __init__(self, maxsize):
"""A dictionary that never exceeds a given size. If the size limit is reached,
the least recently inserted element is removed.
Args:
maxsize (int): Maximum size of the dictionary.
Raises:
ValueError: Raised if maxsize argument is not a positve integer.
"""
if maxsize <= 0:
raise ValueError("Maxsize must be greater than zero")
self.dict = OrderedDict()
self.maxsize = maxsize
def pop_front(self):
"""Pop key, value pair from front of dictionary.
Returns:
tuple: (key, value)
"""
return self.dict.popitem(last=False)
def insert_end(self, key, value):
"""Insert key-value pair into end of dictionary. If the key already
exists, the key-value pair will be moved to the end of the dictionary
and the value will be updated.
Args:
key (pyobj): Key in key-value pair.
value (pyobj): Value in key-value pair.
"""
if key in self.dict:
self.dict.pop(key)
self.dict[key] = value
if len(self.dict) > self.maxsize:
self.dict.popitem(last=False)
def delete(self, key):
"""Delete an entry from the dictionary
Args:
key (pyobj): Key to delete.
"""
del self.dict[key]
def keys(self):
"""Retrieve all keys in the dictionary, from earliest to latest.
Returns:
odict_keys: Iterable object of keys.
"""
return self.dict.keys()
def __len__(self):
"""Number of key-value pairs in the dictionary.
Returns:
int: Number of k-v pairs.
"""
return len(self.dict)
def __setitem__(self, key, value):
"""Update a key-value pair, without changing its position in the
dictionary.
Args:
key (pyobj): Key in the key-value pair.
value (pyobj): Value in key-value pair.
Raises:
KeyError: Key was not found in the dictionary.
"""
if key not in self.dict:
raise KeyError(str(key) + " use insert_end to add an element")
self.dict[key] = value
def __getitem__(self, key):
"""Retrieve a value from the dictionary.
Args:
key (pyobj): Key in the key-value pair.
Returns:
pyobj: Value in the key-value pair, if the key exists.
"""
return self.dict[key]
def __repr__(self):
return self.dict.__repr__()
|
from random import randint
print('--- LOTTO simulator ---')
print('-- Pick 6 numbers in range of 1-49 --')
lotto_numbers = []
for _ in range(6):
n = randint(1, 49)
if n in lotto_numbers:
n = randint(1, 49)
lotto_numbers.append(n)
converting = True
while converting:
try:
player_numbers_str = input('Input your 6 numbers (separator is ",": ')
player_numbers = player_numbers_str.split(',')
int_list = []
for i in player_numbers:
if int(i) <= 49 and int(i) >= 1:
i = int(i)
int_list.append(i)
else:
raise ValueError('Not in range 1-49')
converting = False
except ValueError:
print('Number not in range or letter. Try again..')
int_list = sorted(int_list)
print(f"Numbers you've picked: {int_list}")
print(f'Winning numbers: {lotto_numbers}')
win_numbers = []
for number in int_list:
if number in lotto_numbers:
win_numbers.append(number)
print(f'Numbers that match: {len(win_numbers)}')
|
# Listelerin eleman sayısına ulaşmak için İngilizce uzunluk anlamına gelen
# length kelimesinin kısaltması olan len() fonksiyonu kullanılır
sayi=[20, 40, 60, 80]
print(len(sayi))
print('{0} adet sayı vardır'.format(len(sayi)))
listem=[5,9,10,"altan",82.5]
print(len(listem))
# eleman sayısının 1 eksiği son indisi verir, eleman sayısı:5, son indis:4
# Altan KARAALP yazıldığında
# A************ şeklinde yazsın
isim=input('isminiz:')
print(isim[0])
print ('Merhaba sayın ', isim[0]+'*'*(len(isim)-1)) |
# maaş zam hesaplama
yeniMaas=0
maas=float(input("Maaşı Gir : "))
zam=float(input("Zam Oranı(%) : "))
zamoranı=maas*(zam/100)
yeniMaas=maas+zamoranı
print("Zamlı Maaş :",yeniMaas)
|
a=6
b=4
print("karşılaştırma operatörleri:eşit değil mi?")
print (a!=b) # true döner
# Programlama dilinde gerçekleştirilen karşılaştırmalar
# doğru ise True yanlış ise False değerlerini döndürür.
|
sayi1=input("Birinci sayı:")
sayi2=input("İkinci sayı:")
toplam=sayi1+sayi2
print(toplam)
# ekrana sayıları bitişik yazar çünkü int kullanmadık!!!
#doğrusu
x=int(input("Birinci sayı:"))
y=int(input("İkinci sayı:"))
toplam2=x+y
print(toplam2)
|
""" C6H12O6 formülü şekerin formülüdür.
Buna göre ;
C=12.01
H=1.00
O=15.99
şekerin mole kütlesini hesapla """
C=12.01
H=1.00
O=15.99
molkutlesi=C*6+H*12+O*6
print("C6H12O6 formülünün mol kütlesi {0} dır".format(molkutlesi))
# diğer örnek
""" suyun fomülü H2O dur.
H=1.00
O=15.99
olduğuna göre molekül ağırlığı nedir? """
H=1.00
O=15.99
molkutlesi=H*2+O*1
print("suyun mol kütlesi {0} dır".format(molkutlesi)) |
# Listeden belli bir aralık almak
# liste[başlangıç indeksi:bitiş indeksi] yapısı kullanılır
asal_sayilar=[2, 3, 5, 7, 11, 13, 17, 19, 23]
print(asal_sayilar[0:3]) # [2, 3, 5]
print(asal_sayilar[1:4])
''' indeksi 1 olan elemandan başlayarak indeksi 4 olan elemana (4 dâhil değil) kadar ekrana yazdırır.
Dolayısıyla ekran çıktısı [3, 5, 7] olacaktır. '''
print(asal_sayilar[5:]) # 5ten sonraki hepsi demektir [13, 17, 19, 23]
print(asal_sayilar[:5]) # baştan 5.indise kadar demektir(5. dahil değildir) [2, 3, 5, 7, 11]
# ATLAYARAK ALMAK
asal_sayilar2=[2, 3, 5, 7, 11, 13, 17, 19, 23]
print(asal_sayilar2[0:6]) # [2, 3, 5, 7, 11, 13]
print(asal_sayilar2[0:6:2]) # baştan 6.ya kadar 2 atlayarak getirir (6.dahil değil)
# [2, 3, 5, 7, 11, 13] ELEMANLARINI 2 ADIM ATLAYARAK AL = [2, 5, 11]
print(asal_sayilar2[0:7:2]) # [2, 3, 5, 7, 11, 13, 17] -> [2,5,7,13]
|
negatifSay = 0
pozitifSay = 0
while True:
x = int(input("bir sayı gir: "))
if x ==0:
break
if x<0:
negatifSay = negatifSay + 1
else:
pozitifSay = pozitifSay + 1
print("Toplam negatif sayı:",negatifSay)
print("Toplam pozitif sayı:",pozitifSay)
|
#sayılar
#aşağıdaki komutları terminalde deneyiniz
>>> 23
23
>>> 4567
4567
#type komutu
>>> type(2.3)
<class 'float'>
>>> type("altan")
<class 'str'>
>>> type(23)
<class 'int'>
>>> type('karaalp')
<class 'str'>
>>> type(10+2j)
<class 'complex'>
>>>
# yukarıdakiler birer tamsayıdır. İngilizcede bu tür sayılara integer adı verilir.
>>> 2.3
2.3
# yukarıdakiler kayan noktalı sayıdır (floating point number veya kısaca float).
# Bu arada kayan noktalı sayılarda basamak ayracı olarak virgül değil,
# nokta işareti kullandığımıza dikkat edin.
>>> (10+2j)
(10+2j)
# karmaşık sayıdır (complex).
|
#!usr.bin/python3
# Accepts a .csv file (or list of tiles) and does the following:
# - Adds column TITLE_NAME, which contains organizations' names
# in title case with special cases addressed (special cases
# are outlined in function documentation and are easily edited)
# - Writes new dataframe back to .csv of same name
# Sample invocation: python3 name-casing.py path/to/file1.csv path/to/file2.csv path/to/file3.csv
import pandas as pd
from sys import argv
def title_case_name(df):
t_name = []
conj = ['a', 'an', 'and', 'at', 'by', 'for',
'from', 'in', 'of', 'on', 'the', 'to']
# List of words which, when found in the middle
# of an org's name, should be lowercased
abbrev = ['co', 'corp', 'inc']
# List of abbreviations that should be kept
# abbreviated and followed by a period
expand = {'amer': 'American', 'assoc': 'Association',
'cncl': 'Council', 'ctr': 'Center',
'fnd': 'Foundation', 'inst': 'Institute',
'soc': 'Society'}
# Dictionary of abbreviations we want to expand
caps = ['llc', 'ny', 'nyc', 'us', 'usa']
# List of abbreviations to keep capitalized
for item in df.NAME:
temp = item.lower().split()
new = []
for wd in temp:
if wd in conj:
new.append(wd)
continue
if wd in abbrev:
new.append(wd.title() + '.')
continue
if wd in expand.keys():
new.append(expand[wd])
continue
if wd in caps:
new.append(wd.upper())
continue
new.append(wd.title())
t_name.append(" ".join(new))
df['TITLE_NAME'] = t_name
return df
IN_FILES = argv[1:]
for curr_file in IN_FILES:
df = pd.read_csv(curr_file)
title_case_name(df)
df.to_csv(curr_file)
|
class Dog:
role = "dog"
def __init__(self, name, breed, attack_val):
self.name = name
self.breed = breed
self.attack_val = attack_val
self.life_val = 100
def bite(self, person):
person.life_val -= int(self.attack_val)
print("狗[%s]咬了人[%s],人掉血[%s], 还剩血量[%s]。。"%(self.name, person.name, self.attack_val, person.life_val))
class Person:
role = "person"
def __init__(self, name, sex, attack_val):
self.name = name
self.sex = sex
self.attack_val = attack_val
self.life_val = 100
def beat(self, dog):
dog.life_val -= int(self.attack_val)
print("人[%s]打了狗[%s],狗掉血[%s], 还剩血量[%s]。。"%(self.name, dog.name, self.attack_val, dog.life_val))
d = Dog("毛毛", "二哈", "60")
p = Person("Alex", "男", "20")
d.bite(p) # 对象交互
p.beat(d)
|
name = "小猿圈"
def change():
name = "小猿圈,自学编程"
def change2():
name = "小猿圈,自学编程不要钱"
print("第3层打印", name)
change2()
print("第2层打印", name)
change()
print("第1层打印", name)
print("----------------")
res = map(lambda x: x ** 2, [1, 5, 7, 4, 8]) # 匿名函数,省去指定函数名的过程
for i in res:
print(i)
print("----------------")
def get_abs(n):
if n < 0:
n = int(str(n).strip("-"))
return n
def add(x, y, f): # 低阶函数作为高阶函数的参数
return f(x) + f(y)
res = add(3, -6, get_abs)
print(res)
|
# 爬取肯德基餐厅查询http://www.kfc.com.cn/kfccda/index.aspx中指定地点的餐厅数据
import requests
if __name__ == "__main__":
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
}
data = {
'cname': '',
'pid': '',
'keyword': '北京',
'pageIndex': '1',
'pageSize': '10'
}
response = requests.post(url=url,headers=headers,data=data)
print(response.json()) |
class Dog:
def __init__(self, name, breed, attack_val):
self.name = name
self.breed = breed
self.attack_val = attack_val
self.life_val = int(100)
def bite(self, person):
person.life_val -= self.attack_val
print("狗[%s]咬了人[%s],人掉血[%s],还剩血量[%s]..." % (self.name, person.name, self.attack_val, person.life_val))
class Weapon:
def stick(self, obj):
"""打狗棒"""
self.name = "打狗棒"
self.attack_val = int(40)
obj.life_val -= self.attack_val
self.print_log(obj)
def knife(self, obj):
"""屠龙刀"""
self.name = "屠龙刀"
self.attack_val = int(80)
obj.life_val -= self.attack_val
self.print_log(obj)
def gun(self, obj):
"""AK47"""
self.name = "AK47"
self.attack_val = int(100)
obj.life_val -= self.attack_val
self.print_log(obj)
def print_log(self, obj):
print("[%s]被[%s]攻击了,掉血[%s],还剩血量[%s]..." % (obj.name, self.name, self.attack_val, obj.life_val))
class Person:
role = 'person'
def __init__(self, name, sex, attack_val):
self.name = name
self.sex = sex
self.attack_val = attack_val
self.life_val = int(100)
self.weapon = Weapon() # 在此处实例化一个Weapon对象
def attack(self, dog):
dog.life_val -= self.attack_val
print("人[%s]打了狗[%s],狗掉血[%s],还剩血量[%s]..." % (self.name, dog.name, self.attack_val, dog.life_val))
d = Dog("mjj", "二哈", 20)
p = Person("Alex", "Male", 60)
d.bite(p) # 对象交互,把p实例传递给d的方法
p.attack(d)
p.weapon.knife(d) # 通过组合的方式调用weapon实例下的具体武器
p.weapon.stick(d)
|
# 开启新线程开销远远小于开启新进程
from multiprocessing import Process
def work():
print('hallo')
if __name__ == '__main__':
# 在主进程下开启子进程
p = Process(target=work)
p.start()
print('主进程')
#
# from threading import Thread
#
#
# def work():
# print('hallo')
#
#
# if __name__ == '__main__':
# t = Thread(target=work)
# t.start()
# print('主线程')
|
# 写一个程序,要求用户输入用户名和密码,要求密码长度不少于6个字符,且必须以字母开头,
# 如果密码合法,则将该密码使用md5算法加密后的十六进制概要值存入名为password.txt的文件,超过三次不合法则退出程序
def start():
count = 3
while count > 0:
name = input(">>").strip()
pwd = input(">>").strip()
if len(pwd) >= 6 and pwd[0].isalpha():
pwd_md5 = hashlib.md5(pwd.encode("utf-8")).hexdigest()
print("输入成功")
obj = {"user_name:", name, "pass_word:", pwd_md5}
with open("password.txt", "a", encoding="utf-8") as f:
json.dump(list(obj), f)
exit()
else:
if count == 0:
print("三次错误")
exit()
count -= 1
print(f"输入错误,还有{count}次机会")
continue
if __name__ == '__main__':
import hashlib, json
start() |
import math
def area(item, *args):
def roundness(R):
dimension = math.pi * (R ** 2)
return dimension
def square(A):
dimension = A ** 2
return dimension
def rectangle(L, W):
dimension = L * W
return dimension
if item == "圆形":
print(roundness(*args))
if item == "正方形":
print(square(*args))
if item == "长方形":
print(rectangle(*args))
area("圆形", 3)
area("正方形", 3)
area("长方形", 4, 5)
def factorial(n):
fn = 1
for i in range(1, n + 1):
fn *= i
return fn
print(factorial(10))
|
# 写一个程序,包含十个线程,子线程必须等待主线程sleep 10秒钟之后才执行,并打印当前时间
from threading import Thread, Event, currentThread
import time, datetime
def task():
print(f"{currentThread().getName()}等待")
event.wait()
print(f"{currentThread().getName()}, {datetime.datetime.now()} is running")
if __name__ == "__main__":
event = Event()
for i in range(10):
t = Thread(target=task)
t.start()
time.sleep(10)
event.set() # 状态值设为True,阻塞的线程进入激活状态
|
# 逗号分隔值(Comma-Separated Values,CSV
# 有时也称为字符分隔值,因为分隔字符也可以不是逗号)
# 其文件以纯文本形式存储表格数据(数字和文本)
import csv
# f = open("ex4")
# reader = csv.reader(f)
# for line in reader:
# print(line)
# csv模块读取csv文件
with open("ex4") as f:
lines = list(csv.reader(f))
# 变成字典
header, values = lines[0], lines[1:] # 第一行变成列名
data_dict = {h: v for h, v in zip(header, zip(*values))}
print(data_dict)
# 自定义一个csv.Dialect来自定义风格
class my_dialect(csv.Dialect): # 自定义一个csv.Dialect来自定义风格
lineterminator = "\n" # 行终止符
delimiter = ";" # 字段分隔符
quotechar = '"' # 引号
quoting = csv.QUOTE_MINIMAL # 引用惯例
reader = csv.reader(lines, my_dialect)
# 写入csv文件
with open("mydata", "w") as m:
writter = csv.writer(m, dialect=my_dialect)
writter.writerow(("one", "two", "three"))
writter.writerow(("1", "2", "3")) |
from tkinter import *
from tkinter import ttk
import os
version = "v2.1"
Birthday_book = dict()
date_list = list()
def clear():
input_date.delete(0, END)
input_last_name.delete(0, END)
input_first_name.delete(0, END)
input_patronymic.delete(0, END)
def add():
date = input_date.get()
if date in Birthday_book:
label_info.config(text="! Такая дата рождения уже существует !", fg="red")
else:
value = list()
value.append(input_last_name.get())
value.append(input_first_name.get())
value.append(input_patronymic.get())
Birthday_book[date] = value
list_date.insert(END, date)
with open("BirthdayBook.csv", "w") as file:
for date in Birthday_book:
value = Birthday_book[date]
temp = date + ";" + value[0] + ";" + value[1] + \
";" + value[2] + ";" + "\n"
file.write(temp)
def select_list_date(event):
w = event.widget
i = int(w.curselection()[0])
date = w.get(i)
value = Birthday_book[date]
last_name = value[0]
first_name = value[1]
patronymic = value[2]
clear()
input_date.insert(0, date)
input_last_name.insert(0, last_name)
input_first_name.insert(0, first_name)
input_patronymic.insert(0, patronymic)
window = Tk()
window.title(f"DateBook {version}")
window.geometry("550x240")
label_date = Label(text="Дата рождения")
label_date.grid(row=0, column=0, padx=10, pady=10, sticky="w")
input_date = ttk.Entry()
input_date.grid(row=0, column=1)
label_last_name = Label(text="Фамилия")
label_last_name.grid(row=1, column=0, padx=10, pady=5, sticky="w")
input_last_name = ttk.Entry()
input_last_name.grid(row=1, column=1)
label_first_name = Label(text="Имя")
label_first_name.grid(row=2, column=0, padx=10, pady=5, sticky="w")
input_first_name = ttk.Entry()
input_first_name.grid(row=2, column=1)
label_patronymic = Label(text="Отчество")
label_patronymic.grid(row=3, column=0, padx=10, pady=5, sticky="w")
input_patronymic = ttk.Entry()
input_patronymic.grid(row=3, column=1)
label_info = Label(text="Программа готова к работе...")
label_info.grid(row=5, column=0, columnspan=4)
button_add = ttk.Button(text="Добавить", command=add)
button_add.grid(row=1, column=2, padx=38)
button_clear = ttk.Button(text="Удалить", command=clear)
button_clear.grid(row=3, column=2, padx=38)
label_list_date = Label(text="Список дней рождений")
label_list_date.grid(row=0, column=3)
list_date = Listbox()
list_date.grid(row=1, column=3, rowspan=5)
# <<ListboxSelect>> связывает Listbox и поля ввода
list_date.bind('<<ListboxSelect>>', select_list_date)
if os.path.exists("BirthdayBook.csv"):
with open("BirthdayBook.csv", "r") as file:
lines = file.readlines()
for line in lines:
elements = line.split(";") # split игнорирует ;
# (номер);(имя);(фамилия);(отчество);(адрес)
date = elements[0]
last_name = elements[1]
first_name = elements[2]
patronymic = elements[3]
value = list()
value.append(last_name)
value.append(first_name)
value.append(patronymic)
Birthday_book[date] = value
list_date.insert(END, date)
window.mainloop()
|
from datetime import datetime
import ast
class Restaurant:
"""
Authors: Dean, Tony and Hashir.
Class defining Restaurant object. Holds all relevant information.
Attributes:
name - string - name of restaurant
address - string - street address of restaurant
coordinates - tuple containing latitude and longitude
stars - average star rating for a restaurant
topReviews - multi-element tuple containing single string as review
hours - dictionairy for hours where key is string of the day of the week
"""
def __init__(self, name, address=None, coordinates=None, stars=None,
numberOfReviews=None, topReviews=None, hours=None, averageNearbyRating=None):
self.name = name
self.address = address[0][0] if address is not None else "unavailable"
self.coordinates = coordinates[0] if coordinates is not None else (0,0)
self.stars = stars[0][0] if stars is not None else "unavailable"
self.numberOfReviews = numberOfReviews[0][0] if numberOfReviews is not None else "unavailable"
self.topReviews = topReviews[0] if topReviews is not None else ""
try:
self.hours = ast.literal_eval(hours[0][0]) if hours is not None else ""
except ValueError:
self.hours = None
print("yikes hours valueerror for " + name)
self.averageNearbyRating = averageNearbyRating
def getHours(self):
"""
Returns the hours for the current day using current system time
Returns:
string - hours for the current day
"""
if not isinstance(self.hours, dict):
return "Hours unavailable"
return self.hours.get(datetime.today().strftime('%A'), "Hours unavailable")
|
'''
Effort to make this look similar to OSX calculator with equation string shown
'''
from tkinter import *
from tkinter import font
class App():
def __init__(self, master):
button_color = "gray27"
operator_color = "dark orange"
self.current_string = StringVar()
self.current_string.set("0")
self.answer = DoubleVar()
self.answer.set(0)
self.my_font = font.Font(family="Helvetica Light", size=45)
self.but_font = font.Font(family="Helvetica Light", size=23)
# key bindings
for i in range(10):
master.bind(str(i), self.concat_bind)
master.bind("+", self.concat_bind)
master.bind("-", self.concat_bind)
master.bind("x", self.concat_bind)
master.bind("/", self.concat_bind)
master.bind("<Return>", self.calc)
# add number buttons
Label(master, textvariable=self.current_string, width=10, bg="gray29", fg="white", font=self.my_font, anchor='e', pady=15).grid(column=1, row=1, columnspan=4)
but1 = Label(master, text="1", bg='light gray', font=self.but_font, pady=10)
but1.grid(column=1, row=5, sticky='nesw')
but1.bind("<Button-1>", self.concat)
but1.config(highlightbackground='dark gray', highlightthickness=1)
but2 = Label(master, text="2", bg='light gray', font=self.but_font, pady=10)
but2.grid(column=2, row=5, sticky='nesw')
but2.bind("<Button-1>", self.concat)
but2.config(highlightbackground='dark gray', highlightthickness=1)
but3 = Label(master, text="3",bg='light gray', font=self.but_font, pady=10)
but3.grid(column=3, row=5, sticky='nesw')
but3.bind("<Button-1>", self.concat)
but3.config(highlightbackground='dark gray', highlightthickness=1)
but4 = Label(master, text="4",bg='light gray', font=self.but_font, pady=10)
but4.grid(column=1, row=4, sticky='nesw')
but4.bind("<Button-1>", self.concat)
but4.config(highlightbackground='dark gray', highlightthickness=1)
but5 = Label(master, text="5",bg='light gray', font=self.but_font, pady=10)
but5.grid(column=2, row=4, sticky='nesw')
but5.bind("<Button-1>", self.concat)
but5.config(highlightbackground='dark gray', highlightthickness=1)
but6 = Label(master, text="6",bg='light gray', font=self.but_font, pady=10)
but6.grid(column=3, row=4, sticky='nesw')
but6.bind("<Button-1>", self.concat)
but6.config(highlightbackground='dark gray', highlightthickness=1)
but7 = Label(master, text="7",bg='light gray', font=self.but_font, pady=10)
but7.grid(column=1, row=3, sticky='nesw')
but7.bind("<Button-1>", self.concat)
but7.config(highlightbackground='dark gray', highlightthickness=1)
but8 = Label(master, text="8",bg='light gray', font=self.but_font, pady=10)
but8.grid(column=2, row=3, sticky='nesw')
but8.bind("<Button-1>", self.concat)
but8.config(highlightbackground='dark gray', highlightthickness=1)
but9 = Label(master, text="9",bg='light gray', font=self.but_font, pady=10)
but9.grid(column=3, row=3, sticky='nesw')
but9.bind("<Button-1>", self.concat)
but9.config(highlightbackground='dark gray', highlightthickness=1)
but0 = Label(master, text="0", anchor='w',padx=25,bg='light gray', font=self.but_font, pady=10)
but0.grid(column=1, row=6, columnspan=2, sticky='nesw')
but0.bind("<Button-1>", self.concat)
but0.config(highlightbackground='dark gray', highlightthickness=1)
butplus = Label(master, text="+",bg=operator_color, fg='white', font=self.but_font, pady=10)
butplus.grid(column=4, row=2, sticky='nesw')
butplus.bind("<Button-1>", self.concat)
butplus.config(highlightbackground='dark gray', highlightthickness=1)
butminus = Label(master, text="-",bg=operator_color, fg='white', font=self.but_font, pady=10)
butminus.grid(column=4, row=3, sticky='nesw')
butminus.bind("<Button-1>", self.concat)
butminus.config(highlightbackground='dark gray', highlightthickness=1)
butmult = Label(master, text="x",bg=operator_color, fg='white', font=self.but_font, pady=10)
butmult.grid(column=4, row=4, sticky='nesw')
butmult.bind("<Button-1>", self.concat)
butmult.config(highlightbackground='dark gray', highlightthickness=1)
butdiv = Label(master, text="/",bg=operator_color, fg='white', font=self.but_font, pady=10)
butdiv.grid(column=4, row=5, sticky='nesw')
butdiv.bind("<Button-1>", self.concat)
butdiv.config(highlightbackground='dark gray', highlightthickness=1)
butequal = Label(master, text="=",bg=operator_color, fg='white', font=self.but_font, pady=10)
butequal.grid(column=4, row=6, sticky='nesw')
butequal.bind("<Button-1>", self.calc)
butequal.config(highlightbackground='dark gray', highlightthickness=1)
butdot = Label(master, text=".",bg='light gray', font=self.but_font, pady=10)
butdot.grid(column=3, row=6, sticky='nesw')
butdot.bind("<Button-1>", self.concat)
butdot.config(highlightbackground='dark gray', highlightthickness=1)
butclr = Label(master, text="C",bg='light gray', font=self.but_font, pady=10)
butclr.grid(column=1, row=2, sticky='nesw')
butclr.bind("<Button-1>", self.clear)
butclr.config(highlightbackground='dark gray', highlightthickness=1)
butlpar = Label(master, text="(",bg='light gray', font=self.but_font, pady=10)
butlpar.grid(column=2, row=2, sticky='nesw')
butlpar.bind("<Button-1>", self.concat)
butlpar.config(highlightbackground='dark gray', highlightthickness=1)
butrpar = Label(master, text=")",bg='light gray', font=self.but_font, pady=10)
butrpar.grid(column=3, row=2, sticky='nesw')
butrpar.bind("<Button-1>", self.concat)
butrpar.config(highlightbackground='dark gray', highlightthickness=1)
#self.answerlabel = Label(master, textvariable=self.answer).grid(column=0, row=5, columnspan=3)
def concat(self, event):
if self.current_string.get() == "0" or self.current_string.get()=="E":
self.current_string.set("")
self.current_string.set(self.current_string.get() + event.widget.cget("text"))
def concat_bind(self, event):
if self.current_string.get() == "0" or self.current_string.get()=="E":
self.current_string.set("")
self.current_string.set(self.current_string.get() + event.char)
def calc(self, event):
eqn = self.current_string.get()
print(eqn)
eqn = eqn.replace('x', '*')
print(eqn)
try:
answer = str(eval(eqn))
except:
self.current_string.set("E")
if len(answer) > 10:
answer = answer[:10]
self.answer.set(answer)
self.current_string.set(str(answer))
def clear(self, event):
self.current_string.set("")
if __name__ == "__main__":
root = Tk()
root.title("Calculator")
app = App(root)
root.mainloop()
|
#!/usr/bin/env python3
"""
Author : lia
Date : 2020-02-17
Purpose: Accept input text from the command line or a file
Change strings to uppercase
Print output to command line or a file to be created
Make plain text behave like a file handle
"""
import argparse
import os
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Howler (upper-case input)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text',
metavar='str',
help='Input text or file')
parser.add_argument('-o',
'--outfile',
help='Output filename',
metavar='str',
type=str,
default='')
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read().rstrip()
return args
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
out_fh = open(args.outfile, 'wt') if args.outfile else sys.stdout
print(args.text.upper(), file=out_fh)
out_fh.close()
# --------------------------------------------------
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
# coding=utf-8
import sqlite3
# 连接
# 表
# 录入学生信息
# 选课
# 查询学生信息
# 按学生查询选课
# 按课程查询课程信息
# 查询选择课程的学生列表
class Student:
def __init__(self):
pass
def dbaccess(self):
connect = sqlite3.connect('studb.sqlite', timeout=3)
return connect
def createdb(self):
sql = ["""
CREATE TABLE Student(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
StuId INTEGER NOT NULL,
NAME TEXT NOT NULL,
CLASS INT NOT NULL);
""",
"""
CREATE TABLE Course(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
CourseId INT NOT NULL,
Name TEXT NOT NULL,
Teacher TEXT NOT NULL,
Classroom TEXT NOT NULL,
StartTime CHAR(11),
EndTime CHAR(11));
""",
"""
CREATE TABLE Xuanke(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
StuId INT NOT NULL,
CourseId INT NOT NULL);
"""]
conn = self.dbaccess()
for s in sql:
conn.execute(s)
conn.commit()
def insert(self):
conn = self.dbaccess()
stu_id = input("请输入学生编号: ")
cur = conn.execute("select stuid from student WHERE stuid = %s;" % stu_id)
row = cur.fetchone()
if row:
print("编号已存在, 请重新输入")
self.insert()
else:
stu_name = str(input("请输入学生姓名: "))
stu_class = input("请输入学生班级: ")
sql = "INSERT INTO student (stuid, name, class) values (%s, '%s', %s);" % (stu_id, stu_name, stu_class)
conn.execute(sql)
conn.commit()
print("学生信息登记完成")
def xuenke(self):
conn = self.dbaccess()
stu_id = input("请输入选课的学生编号: \n")
cur = conn.execute("select stuid from Student WHERE StuId = %s;" % stu_id)
if cur.fetchone():
print("课程列表: ")
cur = conn.execute("SELECT courseid, name, teacher, classroom, starttime, endtime FROM Course;")
for row in cur:
print("课程:", row)
cou_id = input("请输入选择的课程编号: \n")
cur1 = conn.execute("SELECT courseid FROM Course WHERE CourseId = %s;" % cou_id)
if cur1.fetchone():
cur2 = conn.execute(
"SELECT courseid FROM Xuanke WHERE CourseId = %s AND StuId = %s;" % (cou_id, stu_id))
if cur2.fetchone():
print("课程已选择, 不能重复选择")
else:
conn.execute("INSERT INTO Xuanke (StuId, CourseId) VALUES (%s, %s);" % (stu_id, cou_id))
conn.commit()
print("课程选择成功")
else:
print("所选课程不存在")
else:
print("该学生编号不存在, 请核对后输入")
self.xuenke()
def stu_id_search(self):
conn = self.dbaccess()
stu_id = input("请输入查询的学生编号: \n")
cur = conn.execute("SELECT * FROM Student WHERE StuId = %s;" % stu_id)
row = cur.fetchone()
if row:
print("学生信息如下: ")
print(row)
else:
print("该学生编号不存在, 请核对后输入")
self.stu_id_search()
def stu_id_course(self):
conn = self.dbaccess()
stu_id = input("请输入查询的学生编号: \n")
cur = conn.execute("SELECT * FROM Student WHERE StuId = %s;" % stu_id)
row = cur.fetchone()
if row:
cur1 = conn.execute(
"SELECT s.StuId,s.NAME, c.* FROM Student s, Xuanke x, Course c WHERE s.StuID = %s AND s.StuId = x.StuId and x.CourseId = c.CourseId;" % stu_id)
for row in cur1:
print(row)
else:
print("该学生编号不存在, 请核对后输入")
self.stu_id_course()
def course_stu_id(self):
conn = self.dbaccess()
course_id = input("请输出查询的课程编号: \n")
cur = conn.execute("SELECT courseid FROM Xuanke WHERE CourseId = %s;" % course_id)
if cur.fetchone():
cur1 = conn.execute(
"SELECT s.StuId, s.NAME, x.CourseId, s.CLASS FROM student s, xuanke x WHERE x.CourseId = %s and x.StuId = s.StuId;" % course_id)
for row in cur1:
print(row)
def menu(self):
print('1.进入学生信息系统(学生信息录入)')
print('2.进入学生选课系统(学生选课操作)')
print('3.进入学生选课信息系统(学生信息查询和选课情况查询)')
print('4.退出程序')
def student(self):
print('1.录入学生信息')
print('2.返回主菜单')
def Course(self):
print('1.开始选课')
print('2.返回主菜单')
def information(self):
print('1.按学号查询学生信息')
print('2.按学号查看学生选课课程列表')
print('3.按课程号查看选课学生列表')
print('4.返回主菜单')
if __name__ == "__main__":
student = Student()
# student.createdb()
# student.insert()
# student.xuenke()
# student.stu_id_course()
# student.course_stu_id()
while True:
student.menu()
x = input("请选择操作类型\n")
if x == "1":
student.student()
stu = input("学生信息录入菜单, 请继续选择\n")
if stu == "1":
student.insert()
continue
elif stu == "2":
continue
else:
print("非法选项, 请重新输入")
continue
elif x == "2":
student.Course()
cour = input("课程选择菜单\n")
if cour == "1":
student.xuenke()
continue
elif cour == "2":
continue
else:
print("非法选项, 请重新输入")
continue
elif x == "3":
student.information()
info = input("查询菜单\n")
if info == "1":
student.stu_id_search()
continue
elif info == "2":
student.stu_id_course()
elif info == "3":
student.course_stu_id()
continue
elif info == "4":
continue
else:
print("非法选项, 请重新输入")
continue
elif x == "4":
print("谢谢使用")
exit(0)
else:
print("非法选项, 请重新输入")
continue
|
import math
def binary_search(seq, target):
low = 0
high = len(seq) - 1
while low <= high:
mid = low + (high - low) / 2
mid = int(math.floor(mid))
if (seq[mid] == target):
return mid
elif (seq[mid] < target):
low = mid + 1
else:
high = mid - 1
A = [1, 3, 5, 7, 9, 11, 13, 14, 15, 16, 25, 43, 68, 71, 73, 75]
target = 68
target_index = binary_search(A, target)
print("Target: " + str(target))
print("Sequance: " + str(A))
print("Target_index: " + str(target_index))
print("Target in the array: " + str(A[target_index])) |
#coding=utf-8
'''
Created on 2016年3月10日
@author: makao
'''
class User_Relation(object):
'''
aapr | Marco Mike John Lily
'''
def __init__(self,name):
'''
Constructor
'''
self.name=name
self.follower=[]
def setFollower(self,follower):
self.follower=follower[:]
def formatFollower(self):
s = ''
for item in self.follower:
s += '%s ' % item
return s
def __str__(self):
return '%s | %s' % (self.name,self.formatFollower()) |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 12 21:10:55 2021
@author: ssing
"""
#count
numbers = (1, 8, 7, 8, 7, 5, 4, 6, 8, 5, 9)
cnt1 = numbers.count(5)
cnt2 = numbers.count(8)
cnt3 = numbers.count(7)
print(cnt1)
print(cnt2)
print(cnt3)
#index
x = numbers.index(9)
print(x) |
import pyttsx3 #text to speech
import datetime #for using datetime functions
import speech_recognition as sr #speech to text
import wikipedia #for using wikipedia
import webbrowser #for using webbrowser
import os # for using os releated calls
engine = pyttsx3.init("sapi5")#pyttsx3.init([driverName : string, debug : bool]) → pyttsx3.Engine
#Gets a reference to an engine instance that will use the given driver. If the requested driver is already in use by another
# engine instance, that engine is returned. Otherwise, a new engine is created.
voices = engine.getProperty("voices") #Queues a command to set an engine property. The new property value affects all utterances queued
# after this command.
#Parameters: 1)name – Name of the property to change.
# 2)value – Value to set.
#Properties:
#rate:Integer speech rate in words per minute.
#voice:String identifier of the active voice.
#volume:Floating point volume in the range of 0.0 to 1.0 inclusive.
#print(voices[0].id)
engine.setProperty("voice",voices[0].id)#for setting voice property
#it speaks the audio
def speak(audio):
'''#it speaks the audio'''
engine.say(audio) #Queues a command to speak an utterance. The speech is output according to the properties set before this
#command in the queue.
#Parameters: 1)text – Text to speak.
# 2)name – Name to associate with the utterance. Included in notifications about this utterance.
engine.runAndWait() #Blocks while processing all currently queued commands. Invokes callbacks for engine notifications appropriately.
# Returns when all commands queued before this call are emptied from the queue.
#function to wish the Boss
def wishMe():
'''#function to wish the Boss'''
hour = int(datetime.datetime.now().hour) #it will give the hour value from the current time
if hour>=0 and hour<12: #if hour value is between 0(inclusive) and 12 system will speak "Hi!Good Morning Boss!"
speak("Hi!Good Morning Boss!")
elif hour>=12 and hour<18: #if hour value is between 12(inclusive) and 18 system will speak "Hi!Good Afternoon Boss!"
speak("Hi!Good Afternoon Boss!")
else:
speak("Hi!Good Evening Boss!")
speak("Jarvis Here!Speed 1 terahertz!Memory 1 zetabyte!What you want me to do sir?")
#function to speak user defined text
def openingJarvis():
'''#function to speak user defined text '''
speak("Opening Jarvis")
os.startfile("C:\\Users\\vasu\\Documents\\Python projects\\Jarvis_chatbot\\jarvis_wallpaper.png")# open wallpaper file
speak("Collecting all remote servers!Establishing secure connection!Starting all system!Downloading and installing all required drivers!")
speak("Just a second Boss!Secure connection established! All systems have started!All drivers are securely installed in your private servers!")
speak("Please wait for a moment Boss!Now I am Online!")
#function to take command from user and interpret it to text
def takeCommand():
'''#function to take command from user and interpret it to text'''
r=sr.Recognizer() #creating a object of recognizer class of speech_recognition
with sr.Microphone() as source: #using microphone as source
print("Listening.....")
r.pause_threshold = 1 #it will inc the time limit for listening the voice of user
audio = r.listen(source) #it will listen the voice of user and save it into audio variable
try: #if sound is recognised properly
print("Recognizing.....")
query = r.recognize_google(audio,language="en-in") #uses google recognizer to decode the audio of user and convert it into text
print(f"User said:{query}\n")
except Exception as e:#For exception it will ask for speaking again
print("Say that again please....")
return "None"
return query #return query
#code runs from here
if __name__ == "__main__":
openingJarvis() #calling openingJarvis() function
wishMe() #calling wishMe() function
while True:#loop for executing again and again
query = takeCommand().lower() #convert query into lower case
if "wikipedia" in query:# id wikipedia in query
speak("Searching wikipedia....")
query = query.replace("wikipedia","")#replace wikipedia word from space so it will search only for special keyword
results = wikipedia.summary(query,sentences=2)#sumaary function stores the 2lines summary of keyword in result variable
speak("According to wikipedia")
#print(results)
speak(results)#speak the result
speak("What else you want me to do")
elif "notepad" in query: #if notepad in query
os.startfile("C:\\Windows\\system32\\notepad.exe") #start the notepad
speak("What else you want me to do")
elif "youtube" in query:#if youtube in query
webbrowser.open("https://www.youtube.com/") #start the youtube through link provide
speak("What else you want me to do")
elif " google" in query:#if google in query
webbrowser.open("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") #start the google in chrome
speak("What else you want me to do")
elif " stack" in query:#if stack in query
webbrowser.open("https://stackoverflow.com/") #opens stackoverflow link
speak("What else you want me to do")
elif " linkedin" in query:#if linkedin in query
webbrowser.open("https://www.linkedin.com/feed/") #opens linkedin in browser
speak("What else you want me to do")
elif " track" in query:#if track in query(work for only one track you can also use your system music library to play different songs)
webbrowser.open("https://www.youtube.com/watch?v=SmM0653YvXU") #start the notepad
speak("What else you want me to do")
elif "time" in query:#if time in query
strTime = datetime.datetime.now().strftime("%H:%M:%S")#it tells current time and strftime formats the time in H:M:S
speak(f"Boss,The Time is {strTime}")#will speak time
speak("What else you want me to do")
elif " vs code" in query:#if vs code in query
os.startfile("C:\\Users\\vasu\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe") #start the vs code
speak("What else you want me to do")
elif "leave" or "exit" in query:#if leave or exit in query
speak("Cool!I am leaving Boss!Good Bye!... ")
break #breaks the loops and code is exited |
b_amt = int(input("Enter the bill amt:\n"))
q = input("Do you have a membership?\n")
if q == "Y":
dis = b_amt * 0.1
n_amt = b_amt - dis
print(f"Thank You! Your total bill amount is Rs{b_amt}, discount is Rs{dis} and net amount payable is Rs{n_amt}")
elif q == "N":
dis = b_amt * 0.03
n_amt = b_amt - dis
print(f"Thank You! Your total bill amount is Rs{b_amt}, discount is Rs{dis} and net amount payable is Rs{n_amt}")
else:
print("enter appropriate input")
|
#!/usr/bin/python
# -- encoding: utf-8 --
if not "raw_input" in dir(__builtins__):
raw_input = input
def blocoToValue(b):
if not len(b): return []
r = []
for k in range(max(b.keys())+1):
if k in b.keys():
r.append(int(b[k]))
else:
r.append(3)
return r
'''
A simplificação de função booleana pelo método de Karnaugh se baseia no
agrupamento dos bits com valor Verdadeiro em blocos 'vizinhos'.
Para isso, devemos definir o que significa bloco vizinho:
Um bloco vizinho a outro bloco é aquele onde há a mudança de apenas
um bit de cada vez, quando comparado com cada item do bloco original.
Por exemplo:
Para o índice (0,0) (dois bits) os possíveis vizinhos são:
(0,1) e (1,0).
Para os índices (0,0,0) e (0,0,1) (três bits e já vizinhos pela definição), os possíveis vizinhos são:
([0, 1, 0], [1, 1, 0]) e ([0, 0, 1], [1, 0, 1]).
Ao colocarmos esses índices na tabela de Karnaugh, notamos que ao seguir a difinição
de vizinhos, formam-se blocos adjacentes. Se todos os índices adjacentes contém
o valor Verdadeiro, pode-se simplificar esse bloco para apenas
os índices que não foram modificados dentro do bloco.
Com essa definição, podemos criar o algorítmo da seguinte forma:
T = Tabela de entrada contendo uma lista de indices onde os valores são Verdadeiro
Ir = Tabela contendo uma lista de indice onde os valores são irrelevantes
F = Lista contendo os blocos simplificados
1. Tome um vetor I com o primeiro índice ainda não utilizado da tabela T
2. Crie uma lista V com os vizinhos desse vetor
3. Para cada vizinho v da lista V, verifique
4. Os indices contidos em v estão na tabela T ou na tabela Ir?
Sim: Faça I = I concatenado com v, volte para 2
Não: Volte para 3 e teste o próximo vizinho
5. Terminou a lista de vizinhos?
Sim: O bloco simplificado está em I agora, F = F concatenado com I
Marque todos os índices de I como já utilizados
Volte para 1.
Não: Volte para 3 e teste o próximo vizinho
6. Terminou a lista de índices originais?
Sim: A função simplificada está em F, imprima
Terminou
Não: Volte para 1
Note que esse algorítmo é o mesmo que fazemos manualmente,
mas o agrupamento é feito visualmente, enquanto programaticamente,
ele é feito recursivamente.
De acordo com Buchfuhrer, D.; Umans, C. (2011). "The complexity of Boolean formula minimization". Journal of Computer and System Sciences 77: 142,
o problema de simplificação de circuitos booleanos é NP completo. Uma simplificação
perfeita sempre terá um tempo de execução exponencial ao número de bits do problema: O(2^n).
'''
import math
TRACE=False
# Cria lista de vizinhos dos itens dados
def vizinhos(item):
lista_vizinhos = []
bits_fixos = lista_bits(item)
# Para cada bit que não muda, crie uma entrada nova
for bit_fixo in bits_fixos:
bloco = []
# Para cada valor, crie um vizinho
for valor in item:
n = []
# Mude apenas um bit por vez para cada entrada individual
for bit in range(len(valor)):
if bit == bit_fixo:
n.append(1-valor[bit])
else:
n.append(valor[bit])
# Agrupe por quantidade de itens
bloco.append(n)
# Monte a lista
lista_vizinhos.append(tuple(bloco))
return lista_vizinhos
# Lista os bits que não mudam de valor na lista de itens
def lista_bits(itens):
lista = []
# Para cada bit
for j in range(len(itens[0])):
igual = True
for k in range(len(itens)-1):
# Verifica se o bit do item atual é igual ao do proximo item
if itens[k][j] != itens[k+1][j]:
igual = False
break
if igual:
# Adiciona na lista somente se passar pelo teste
lista.append(j)
return lista
# transforma um indice em vetor de bits
def indiceEmVetor(valor, bits):
v = []
# Para cada bit do vetor
for i in range(bits):
# Divida o numero por 2^i e adicione o bit lsb do resultado no vetor
v.append((valor>>i) & 1)
return v
# transforma um vetor de bits em um indice
def vetorEmIndice(vetor):
v = 0
# Para cada bit do vetor, começando pelo último valor (MSB)
for i in reversed(vetor):
# Multiplique o valor atual por 2 e adicione o novo bit
v = (v << 1) + i
return v
# calcula o numero minimo de bits necessarios para o vetor de indices
def numeroMinimoDeBits(valores,irrelevante,fixo=0):
# maximo indice na tabela + 1 para evitar log2(0)
# concatene 0 a lista para evitar max([])
maxval=max(valores+irrelevante+[0])+1
# calcule log2(maxval), arredondando para o inteiro acima
bits = int(math.ceil(math.log(maxval)/math.log(2)))
# no caso onde maxval é 1, numero de bits é 0.
# o mínimo necessario deve ser 1, corrija
if bits < 1 : bits = 1
if fixo:
if fixo<bits:
print( "Numero de variaveis requisitado '%d' nao eh suficiente para definir a funcao, utilizando '%d' variaveis" % (fixo,bits) )
return bits
else:
return fixo
return bits
# Transforma a lista de vetores na funcao do bloco
def criarBloco(vetor):
funcao = dict()
# somente os bits fixos
bits = lista_bits(vetor)
# para cada bit da funcao
for i in bits:
# adicione seu valor ao dicionario
funcao[i] = vetor[0][i] == 1
return funcao
def blocoEmTexto(bloco):
f = []
char_a = ord('A')
# para cada bit do bloco
for i in sorted(bloco):
# sufixo = " "
prefixo = ""
# se o valor do bit é 0, adicione a barra
#if not bloco[i]: sufixo = u"\u0305"
# if not bloco[i]: sufixo = u"'"
if not bloco[i]: prefixo = u"/"
# adicione a variavel
# f.append(chr(char_a+i) + sufixo)
f.append(prefixo+chr(char_a+i))
if len(f) == 0 : return u"1"
return "".join(f)
def funcaoEmTexto(funcao):
ret = []
# para cada bloco da funcao
for bloco in sorted(funcao,key=blocoToValue):
# converte para texto
ret.append(blocoEmTexto(bloco))
if ret == []:
return u"0"
return u" + ".join(ret)
def calcularPeso(testados,irrelevante,vetores):
peso = 0
# para cada entrada nos vetores
for v in vetores:
k = vetorEmIndice(v)
# incremente o peso para cada entrada ainda nao utilizada, somente se não está no irrelevante
if not (k in testados.keys()) and not (k in irrelevante):
peso = peso+1
return peso
def agrupar(testados,tabela,irrelevante,vetores,identacao=">"):
otimo = False
if TRACE: print( identacao+"Vetores originais", vetores )
# pegar os vizinhos da lista de indices
blocos = vizinhos(vetores)
# inicialize o maior bloco com os vetores originais
maior_bloco = vetores
# inicialize o peso do bloco encontrado com 0
# peso é a contagem de itens ainda não utilizados
# Quanto maior o peso, mais próximo da melhor otimização possível
peso = 0
# para cada bloco de vizinhos
for bloco in blocos:
if TRACE: print( identacao+"Testando vizinho", bloco )
encontrado = True
# para cada vizinho
for v in bloco:
# verifique se o indice existe na tabela
indice = vetorEmIndice(v)
if not (indice in tabela or indice in irrelevante):
if TRACE: print( identacao+" Falhou" )
# nao existe o indice, vizinho inválido, tente o próximo
encontrado = False
break;
# se todos os items foram 1
if encontrado:
# tente agrupar mais um nível
if TRACE: print( identacao+" Funcionou, testar um nivel acima" )
bloco_encontrado,otimo = agrupar(testados,tabela,irrelevante,vetores+list(bloco),identacao+">")
# Calcular peso do bloco_encontrado
novo_peso = calcularPeso(testados,irrelevante,bloco_encontrado)
# se o novo bloco é maior que o original ou se o peso do novo bloco é maior substitua
if (len(bloco_encontrado) > len(maior_bloco) or (len(bloco_encontrado) == len(maior_bloco) and novo_peso > peso)):
if TRACE and peso > 0: print( (identacao+" Melhor bloco encontrado com peso %d, (anterior era %d), substituindo") % (novo_peso,peso))
maior_bloco = bloco_encontrado
peso = novo_peso
# otimização:
# foi buscado no ultimo nivel, nenhum vizinho tera mais que metade dos bits agrupados
# nao testar proximos vizinhos
if (otimo):
break;
# otimização:
# todos os bits foram agrupados, nao teste outros vizinhos
if (len(maior_bloco) == (1 << len(vetores[0]))):
break;
else:
# otimizacao:
if (len(vetores) == (1 << (len(vetores[0])-1))):
otimo = True
if TRACE: print( identacao+"Maior bloco encontrado" , maior_bloco, ", peso %d" % calcularPeso(testados,irrelevante,maior_bloco) )
return (maior_bloco,otimo)
# Tabela contém os itens que são 1
# ex.: 1,2,5,7
# Irrelevante contém os items irrelevantes
# ex.: 6
# 0,1,1,0,0,1,X,1
def simplificar(tabela,irrelevante,bits=0):
# calcule o maximo numero de variaveis
numbits = numeroMinimoDeBits(tabela,irrelevante,bits)
testados = dict()
funcao = []
# para cada entrada na tabela
for i in tabela:
if not i in testados.keys():
# agrupe os valores 1, se a entrada ainda não foi utilizada antes
if TRACE: print( "Testando entrada da tabela" )
g,_ = agrupar(testados,tabela,irrelevante,[ indiceEmVetor(i,numbits) ])
# minimize e adicione o bloco na lista de funcoes
funcao.append(criarBloco(g))
# para cada entrada do grupo
for v in g:
k = vetorEmIndice(v)
# adicione esse indice à lista de entradas já utilizadas
testados[k]=True
return funcao
def simplificarEmTexto(tabela,irrelevante,bits=0):
return funcaoEmTexto(simplificar(tabela,irrelevante,bits))
def avaliar(funcao, indice,bits):
numbits=numeroMinimoDeBits([indice],[],bits)
v = indiceEmVetor(indice,numbits)
valor = 0
for bloco in funcao:
valor_bloco = 1
for i in reversed(list(bloco.keys())):
if i>=numbits:
valor_bloco = valor_bloco and (0 == bloco[i])
else:
valor_bloco = valor_bloco and (v[i] == bloco[i])
if not valor_bloco:
break
valor = valor or valor_bloco
if valor:
break
return valor
def validar(tabela,irrelevante,bits=0):
numbits = numeroMinimoDeBits(tabela,irrelevante,bits)
f = simplificar(tabela,irrelevante,numbits)
for i in range(1<<numbits):
if not (i in irrelevante):
v = avaliar(f,i,numbits)
if ((i in tabela and v != 1) or ( not (i in tabela) and v == 1 ) ):
print( "Falhou na validação: indice",i )
return []
return f
def reverseBits(v,bits):
r = 0;
for i in range(bits):
r = r | (((v>>i)&1)<<(bits-i-1))
return r
def funcaoEmIndices(s,bits):
import re
s = s.upper()
# Se contem caracteres invalidos, aborte
if re.search("[^A-Z +/.]",s):
raise Exception("Funcao contem caracteres invalidos")
tabela = []
bits = max(ord(max(s))-ord('A')+1,bits)
# crie lista com variaveis esperadas baseado na funcao ou no numero de bits requisitado
variaveis = [chr(c+ord('A')) for c in range(bits)]
# para cada bloco da funcao
for b in s.split("+"):
r = 0;
# para cada letra+negacao do bloco
bloco = list(map(lambda x: str.strip(x," ."),re.findall("(?: |[/.])?(?:[A-Z])",b.replace("//",""))))
utilizar_bloco = True
for variavel in bloco:
# Se a variavel contem a negacao, seu tamanho é 2
if len(variavel) == 2:
# ignore, já que esse bit é 0 para a variavel
continue
# calcule o indice (A=0, B=1, etc...)
idx = ord(variavel[0]) - ord('A')
# caso variavel e variavel' seja definido, esse bloco é sempre zero
if "/"+variavel in bloco:
utilizar_bloco = False
break
# ligue o bit correspondente ao bit encontrado
r = r|(1<<idx)
# caso variavel e variavel' seja definido, esse bloco é sempre zero
if not utilizar_bloco:
continue
x = [r]
# para cada variavel esperada
for variavel in variaveis:
# se a variavel nao explicitamente mencionada, adicione
# o indice onde a variavel é 1 também
# faca o mesmo para cada novo indice adicionado (recursao implementada com loop)
if not variavel in b:
i = len(x)
for k in range(i):
idx = ord(variavel[0]) - ord('A')
x.append(x[k] | (1<<idx))
# Adicione os indices na tabela, sem duplicacao
tabela=list(set(tabela+x))
return (tabela,bits)
if __name__ == "__main__":
import sys
bits=0
tabela=[]
irrelevante=[]
usage = '''Sintaxe: %s [tabela [irrelevante [bits]] | --help ]
'tabela' determina os índices onde o resultado da função tem que ser true.
'irrelevante' determina os índices onde o resultado da função é irrelevante.
'bits' define o número de bits que a função contém. Se não for fornecido,
será definido à partir de 'tabela' e 'irrelevante'.
'-h' ou '--help' mostra esta ajuda.
Os argumentos 'tabela' e 'irrelevante' podem ser uma lista de índices ou uma
funçao. Exemplos: '0,2,3', '/A/B+/AB+AB'.
Se nemhum argumento for fornecido, a tabela de verdade será solicitada de forma
interativa.''' % sys.argv[0]
if len(sys.argv)==2 and (sys.argv[1]=='-h' or sys.argv[1]=='--help'):
print( usage )
else:
if (len(sys.argv) > 1):
if len(sys.argv)>3: bits=int(sys.argv[3])
while(True):
try:
tabela = sys.argv[1].split(",")
if len(tabela) == 1 and tabela[0].strip() == '':
tabela = []
else:
tabela=[int(x,0) for x in tabela]
except:
tabela, bits = funcaoEmIndices(sys.argv[1], bits)
if (len(sys.argv)>2):
try:
ibits = bits
irrelevante = sys.argv[2].split(",")
if len(irrelevante) == 1 and irrelevante[0].strip() == '':
irrelevante = []
else:
irrelevante =[int(x,0) for x in irrelevante]
except:
irrelevante, ibits=funcaoEmIndices(sys.argv[2],bits)
if (bits == ibits):
break
else:
bits = max(ibits,bits)
else:
break
else:
reverse = True
if len(sys.argv)>1 and sys.argv[1] == "A=lsb":
reverse = False
bits = int(raw_input("Numero de variaveis: "))
if (bits<1):
print( "Entrada invalida" )
exit(1)
for j in range(1<<bits):
i = j
if reverse:
i=reverseBits(j,bits)
ok = False
while(not ok):
ok=True
n=raw_input("Entre o valor para "+blocoEmTexto(criarBloco([indiceEmVetor(i,bits)]))+": ")
if n == 'x' or n == 'X' or n == '.':
irrelevante.append(i)
elif n == '1':
tabela.append(i)
elif n == '0':
pass
else:
print( "Entrada invalida")
ok=False
bits = numeroMinimoDeBits(tabela,irrelevante,bits)
print( "%s \"%s\" \"%s\" %d" % (sys.argv[0],",".join(map(str,tabela)), ",".join(map(str,irrelevante)), bits ))
print( funcaoEmTexto(validar(sorted(tabela),irrelevante,bits)))
|
n = input("введите 8 цифр о 0 до 9")
n = list(n)
a = (int(n[0]) + int(n[1]) + int(n[2]) + int(n[3]))
b = (int(n[4]) + int(n[5]) + int(n[6]) + int(n[7]))
if a == b:
print("lucky")
else:
print("no lucky")
print(n)
print(a)
print(b)
|
def rom_arab(roman):
numeric = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
arabic = 0
for d in range(len(roman)):
try:
if numeric[roman[d]] < numeric[roman[d + 1]]:
arabic -= numeric[roman[d]]
else:
arabic += numeric[roman[d]]
except IndexError:
arabic += numeric[roman[d]]
return arabic
a = rom_arab('IVX')
print(a) |
# -*- coding: utf-8 -*-
#Problem 1 : Write a Python program to convert degree to radian
pi=22/7
degree = float(input("Input degrees: "))
radian = degree*(pi/180)
print(radian)
#Problem 2 : Write a Python program to calculate the area of a trapezoid
base_1 = 5
base_2 = 6
height = float(input("Height of trapezoid: "))
base_1 = float(input('Base one value: '))
base_2 = float(input('Base two value: '))
area = ((base_1 + base_2) / 2) * height
print("Area is:", area)
#Problem 3 : Write a Python program to calculate the area of a parallelogram
base = float(input('Length of base: '))
height = float(input('Measurement of height: '))
area = base * height
print("Area is: ", area)
#Problem 4 : Write a Python program to calculate surface volume and area of a cylinder
pi=22/7
height = float(input('Height of cylinder: '))
radian = float(input('Radius of cylinder: '))
volume = pi * radian * radian * height
sur_area = ((2*pi*radian) * height) + ((pi*radian**2)*2)
print("Volume is: ", volume)
print("Surface Area is: ", sur_area)
#Problem 5 : Write a Python program to calculate surface volume and area of a sphere.
pi=22/7
radian = float(input('Radius of sphere: '))
sur_area = 4 * pi * radian **2
volume = (4/3) * (pi * radian ** 3)
print("Surface Area is: ", sur_area)
print("Volume is: ", volume)
#Problem 6 : Write a Python program to convert a decimal number to binary number.
b_num = list(input("Input a binary number: "))
value = 0
for i in range(len(b_num)):
digit = b_num.pop()
if digit == '1':
value = value + pow(2, i)
print("The decimal value of the number is", value)
#Problem 7 : Write a Python program to find the roots of a quadratic function.
from math import sqrt
print("Quadratic function : (a * x^2) + b*x + c")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
r = b**2 - 4*a*c
if r > 0:
num_roots = 2
x1 = (((-b) + sqrt(r))/(2*a))
x2 = (((-b) - sqrt(r))/(2*a))
print("There are 2 roots: %f and %f" % (x1, x2))
elif r == 0:
num_roots = 1
x = (-b) / 2*a
print("There is one root: ", x)
else:
num_roots = 0
print("No roots, discriminant < 0.")
|
"""Abstraction."""
from enum import Enum
class Strategy:
"""
Given a time series, a strategy is a way of deciding whether or not we need
to start panicking.
"""
def __init__(self, source):
self.source = source
def run(self):
"""Run the strategy and return the decision (StrategyResult)."""
raise NotImplementedError("run is not implemented")
def time_series(self):
return self.source.time_series()
class StrategyResult(Enum):
GREEN = 1
ORANGE = 2
RED = 3
|
# import dependencies
from src.CardStack import CardStack
class CardSequence(CardStack):
"""
A class that represents the face-up sequence of cards at the top of a Tableau. Primarily used to transfer cards
to-and-between tableaus.
Data definition is as follows:
- A CardSequence is a card, attached to another CardSeq (based on rules of whether it's valid to attach).
- A CardSequence is exactly one card.
"""
def __init__(self, cards):
"""
Constructor for a CardSequence.
:param cards: A list of Card objects.
"""
super().__init__()
# Construct the CardSequence based on the data definition
self.cards.append(cards[0])
for card in cards[1:]:
if card.can_attach_to(self.peek_top()):
self.cards.append(card)
else:
# Should never get here
raise ValueError("The provided list of cards cannot form a valid CardSequence.")
|
number_first = int(input("Введите первое число: "))
number_second = int(input("Введите второе число: "))
number_third = int(input("Введите третье число: "))
def my_func(*args):
my_list = list(args)
my_list.sort()
if len(my_list) > 2:
print(my_list[-2] + my_list[-1])
my_func(number_first, number_second, number_third)
|
# Personal Project by Bailey Schena
# Calculator
# Taking in a number
print("Please enter the first number")
numberOneInput = input("")
numberOne = int(numberTwoInput)
# Taking in a second number
print("Please enter the second number")
numberTwoInput = input("")
numberTwo = int(numberTwoInput)
# Choosing the operation
print("Please select an operation to perform with the two numbers.")
print("1. Add")
print("2. Multiply")
print("3. Subtract")
print("4. Divide")
userInputNum = input("Type in the corresponding number, and press enter: ")
userInput = int(userInputNum)
outputAnswer = 0
if userInput == 1:
print("The answer is: ", numberOne + numberTwo)
elif userInput == 2:
print("The answer is: ", numberOne * numberTwo)
elif userInput == 3:
print("The answer is: ", numberOne - numberTwo)
elif userInput == 4:
print("The answer is: ", numberOne / numberTwo)
|
# -*- coding: utf-8 -*-
"""
@author: Nellman1508
"""
import numpy as np
def bubble_sort(x):
"""Implementation of Bubble sort.
Takes integer list as input,
returns sorted list."""
print("Starting Bubble sort on following list:\n", x)
loop = 0
unsorted = True
while(unsorted):
loop += 1
print("Bubble sort is in iteration: ", loop)
changes = 0
for i in range(0, (len(x)-1)):
if x[i] > x[i+1]:
print("Bubble sort is changing position of: ", x[i], "and",
x[i+1])
j = x[i]
x[i] = x[i+1]
x[i+1] = j
changes += 1
if changes == 0:
unsorted = False
print("Bubble sort is finished. Sorted list is: \n", x)
return x
if __name__ == "__main__":
rand_numbers = list(np.random.randint(0, 100, size=20))
bubble_sort(rand_numbers)
|
from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
import numpy as np
#1. 데이터
x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8], [7,8,9], [8,9,10], [9,10,11], [10,11,12], [20,30,40], [30,40,50], [40,50,60]])
y = array([4,5,6,7,8,9,10,11,12,13,50,60,70])
print(x)
x1 = x[:10]
y1 = y[:10]
x2 = x[10:]
y2 = y[10:]
x1 = np.transpose(x1)
y1 = np.transpose(y1)
x2 = np.transpose(x2)
y2 = np.transpose(y2)
print("x1.shape : ", x1.shape)
print("x2.shape : ", x2.shape) #(4, 3)
print("y1.shape : ", y1.shape)
print("y2.shape : ", y2.shape) #(4, )
x1 = x1.reshape((x1.shape[0], x1.shape[1], 1))
x2 = x2.reshape((x2.shape[0], x2.shape[1], 1))
print(x)
print("x1.shape : ", x1.shape)
print("x2.shape : ", x2.shape) #(4, 3, 1)
#2. 모델 구성
from keras.models import Sequential, Model
from keras.layers import Dense, Input, LSTM
model = Sequential()
model.add(LSTM(5, activation='relu', input_shape=(3,1)))
model.add(Dense(1000))
model.add(Dense(5))
model.add(Dense(3))
model.add(LSTM(5, activation='relu', input_shape=(3,1)))
model.add(Dense(1000))
model.add(Dense(5))
model.add(Dense(3))
from keras.layers.merge import concatenate
merge1 = concatenate([middle1, middle2])
output1 = Dense(30)(merge1)
output1 = Dense(13)(output1)
output1 = Dense(3)(output1)
output2 = Dense(15)(merge1)
output2 = Dense(32)(output2)
output2 = Dense(3)(output2)
model = Model(inputs = [input1, input2], outputs = [output1, output2])
model.summary()
# model.summary()
#3. 실행
model.compile(loss='mse', optimizer='adam', metrics=['mse']) # metrics=['accuracy'])
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='loss', patience=10, mode='auto')
model.fit([x1_train, x2_train], [y1_train, y2_train], epochs=5, batch_size=1, validation_data=([x1_val, x2_val], [y1_val, y2_val]))
x_input = array([25,35,45])
x_input = x_input.reshape((1,3,1))
yhat = model.predict(x_input)
print(yhat) |
# 第七章
# 1.自定义一个序列,该序列按顺序包含52张扑克牌,分别是黑桃,红心,草花,方块的2-A。要求:提供序列的各种操做方法
'''
序列相关的方法
__len__(self)
__getitem__(self, key)
__contains__(self, item) 可直接用in
__setitem__(self,item)
__delitem__(self, key)
'''
'''
def check_key(key):
if not isinstance(key, int):raise TypeError("索引值必须是整数")
if key < 0: raise IndexError("索引值必须是非负整数")
if key >= 52:raise IndexError("索引值不能超过%d" % 52)
class StringCard:
def __init__(self):
self.__changed = {}
self.__deleted = []
def __len__(self):
return 52
def __getitem__(self, key):
check_key(key)
if key in self.__changed :
return self.__changed[key]
if key in self.__deleted :
return None
n = (key // 13)
n2 = key % 13
list_a = ["黑桃","红心", "草花", "方块"]
list_b = ["2","3", "4","5","6","7", "8","9","10","J", "Q","K","A"]
return list_a[n] + list_b[n2]
def __setitem__(self, key, value):
check_key(key)
self.__changed[key] = value
def __delitem__(self, key):
check_key(key)
if key not in self.__deleted :self.__deleted.append(key)
if key in self.__changed : del self.__changed[key]
sq = StringCard()
print(len(sq))
print(sq[5])
print(sq[1])
sq[1] = "ficnk"
print(sq[1])
del sq[1]
print(sq[1])
sq[1] = "ficdsadasnk"
print(sq[1])
print("ABC" in sq)
'''
# 2.自定义一个序列,该序列按顺序包含所有的三位数(如100,101,102,....)。要求:提供序列的各种操作方法
'''
def check_key(key):
if not isinstance(key, int):raise TypeError("索引值必须是整数")
if key < 0: raise IndexError("索引值必须是非负整数")
if key >= 900:raise IndexError("索引值不能超过%d" % 900)
class SeqNum:
def __init__(self):
self.__changed = {}
self.__deleted = []
def __len__(self):
return 900
def __getitem__(self, key):
check_key(key)
if key in self.__changed :
return self.__changed[key]
if key in self.__deleted :
return None
n = 100 + key
return n
def __setitem__(self, key, value):
check_key(key)
self.__changed[key] = value
def __delitem__(self, key):
check_key(key)
if key not in self.__deleted :self.__deleted.append(key)
if key in self.__changed : del self.__changed[key]
sq = SeqNum()
print(len(sq))
print(sq[5])
print(sq[1])
sq[1] = "ficnk"
print(sq[1])
del sq[1]
print(sq[1])
sq[1] = "ficdsadasnk"
print(sq[1])
print("ABC" in sq)
'''
# 3.自定义一个迭代器,该迭代器分别返回1, 1+2, 1+2+3...的累积和
'''
class CountSum:
# global i
def __init__(self, len):
self.first = 0
self.sec = 3
self.__len = len
self._i = 1
def __next__(self):
if self.__len == 0:
raise StopIteration
# 完成计算
self.first += self._i
self._i += 1
# 数列长度减一
self.__len -= 1
return self.first
def __iter__(self):
return self
count = CountSum(5)
# print(next(count))
for el in count:
print(el, end=" ")
'''
# 4.自定义一个生成器,该生成器可按顺序返回52张扑克牌,分别是黑桃,红心,草花,方块的2-A
# 生成器生成
'''
def gennerate():
print("----------函数开始---------")
list_a = ["黑桃","红心", "草花", "方块"]
list_b = ["2","3", "4","5","6","7", "8","9","10","J", "Q","K","A"]
cur = 0
j = 0
# 遍历val
for i in range(52):
n1 = j // 13
n2 = j % 13
j += 1
cur = list_a[n1] + list_b[n2]
yield cur
g = gennerate()
print("========================")
print(next(g))
for el in g:
print(el, end=" ")
'''
# 迭代器生成
'''
class CardGenerater:
def __init__(self, len):
self.first = 0
self.len = len
self.i = 0
# def fun(self, list_a, list_b):
# for i in range(4):
# for j in range(13):
# return list_a[i]+list_b[j]
def __next__(self):
if self.len == 0:
raise StopIteration
list_a = ["黑桃","红心", "草花", "方块"]
list_b = ["2","3", "4","5","6","7", "8","9","10","J", "Q","K","A"]
n1 = self.i // 13
n2 = self.i % 13
self.first = list_a[n1] + list_b[n2]
self.i += 1
self.len -= 1
return self.first
def __iter__(self):
return self
count = CardGenerater(52)
for el in count:
print(el, end=" ")
'''
# 5.自定义一个生成器,可依次返回1,2,3,4...的阶乘
'''
def factorial(n):
result = n
for i in range(1,n):
result *= i
return result
def gennerateNum(val):
print("--------函数开始---------")
cur = 0
for i in range(val):
cur = factorial(i)
yield cur
count = gennerateNum(5)
for el in count:
print(el, end=" ")
'''
# 6.自定义一个生成器,可依次访问前面目录下的所有Python源文件(以.py为后缀的文件)。
## 改成 Python读取文件夹下所有的文件
'''
import os
path = "G:\\07Blog\\Draft"#文件夹目录
files = os.listdir(path)
s = []
for file in files:
ss =file.split(".")
if len(ss) == 2:
if ss[1]=="md":
s.append(file)
print(s)
'''
'''
import os
def QueyGenerate(path,type):
print("-------函数开始-------")
# path = "G:\\07Blog\\Draft"#文件夹目录
files = os.listdir(path)
for file in files:
ss = file.split(".")
if len(ss) == 2:
if ss[1] == type:
yield file
q = QueyGenerate("G:\\07Blog\\Draft","md")
print("=======================")
for el in q:
print(el , end=" ")
'''
# 7.自定义一个代表二维坐标系上某个点的Point类(包括x,y两个属性),为Point类提供自定义的减法运算符支持,结果返回两点之间的距离
'''
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def __sub__(self,other):
if not isinstance(other, Point):
raise TypeError("-运算符要求的目标是Point类")
return Point(self._x - other._x,self._y - other._y)
def __repr__(self):
return "Point(x = %d, y = %d)" % (self._x,self._y)
p1 = Point(2,3)
p2 = Point(3,4)
p = p1 - p2
print(p)
'''
# 8.自定义代表扑克牌的Card类(包括花色和牌面值),为Card类提供自定义的比较大小的运算符支持,大小比较标准是先比较牌面值,如果牌面值相等则比较花色,花色大小规则为:黑桃>红心>草花>方块
list_a = ["黑桃","红心", "草花", "方块"]
list_b = ["2","3", "4","5","6","7", "8","9","10","J", "Q","K","A"]
class Card:
def __init__(self, color, num):
self._color = color
self._num = num
# ==
def __eq__(self,other):
if not isinstance(other, Card):
raise TypeError("==运算符要求的目标是Card类")
if(self._color == other._color):
if self._num == other._num:
return True
else:
return False
else:
return False
# >
def __gt__(self, other):
if not isinstance(other, Card):
raise TypeError(">运算符要求的目标是Card类")
if list_a.index(self._color) <= list_a.index(other._color):
if list_a.index(self._color) == list_a.index(other._color):
if list_b.index(self._num) <= list_b.index(other._num):
return False
else:
return True
else:
return False
else:
return True
# >=
def __ge__(self, other):
if not isinstance(other, Card):
raise TypeError(">=运算符要求的目标是Card类")
if list_a.index(self._color) < list_a.index(other._color):
return False
else:
if list_b.index(self._num) < list_b.index(other._num):
return False
else:
return True
c1 = Card("黑桃","2")
c2 = Card("黑桃","8")
c3 = Card("红心","2")
c4 = Card("草花","2")
c5 = Card("方块","8")
c6 = Card("草花","2")
print(c1 == c2) # False
print(c1 > c2) # False
print(c5 > c1) # True
print(c4 <= c3) # True
print(c4 == c6) # True |
"""
这是geomotry模块的文档说明
1.开始
2.结束
"""
def print_triangle(n):
"""
这是print_triangle(n)函数的文档说明
在控制台用星号打印三角形
"""
print("这是三角形,参数:", n)
def print_diamand(n):
"""
这是print_diamand(n)函数的文档说明
在控制台用星号打印菱形
"""
print("这是菱形,参数:", n) |
#CTI-110
#M2HW1 - Distance Traveled
#Jenaya Curry
#17 September 2017
#This program calculates the distance traveled based on speed and time variables.
SPEED = 70
distance6hours = SPEED * 6
distance10hours = SPEED * 10
distance15hours = SPEED * 15
print ('The car will travel', distance6hours,'miles in 6 hours.')
print ('The car will travel', distance10hours,'miles in 10 hours.')
print ('The car will travel', distance15hours,'miles in 15 hours.')
|
#CTI 110
#M5HW2 - Running Total
#Jenaya Curry
#16 October 2017
#Takes user input of grades, calculates the average, and displays a letter grade.
def main ():
total = 0
numberInput = float(input('Enter a number? '))
while numberInput > -1:
total = total + numberInput
numberInput = float(input('Enter a number? '))
print ('Total: ',total)
main ()
|
#This file was used to practice various methods to aggregate CSV data to list, dictionairies, etc...
import csv
with open('budget_data_1.csv', mode = 'r') as infile:
reader=csv.reader(infile)
with open('newbudget_data_1.csv', mode = 'w') as outfile:
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1]for rows in reader}
print(mydict)
{k: sum(map(int, v)) for k, v in mydict.items()}
|
from microbit import * # standard Micro:Bit libraries
from array import * # to use an array
import random # generate random numbers
count = 0 # initialise counter to 0
wait = 500 # initialise wait to half a sec
sequence = array('B',[]) # array to hold sequence
display.show("-") # start out showing a dash
def squark(dir): # function to show arrows
global wait
if dir==0: # Right
display.show(Image.ARROW_E)
elif dir==1: # Left
display.show(Image.ARROW_W)
elif dir==2: # Down
display.show(Image.ARROW_S)
elif dir==3: # Up
display.show(Image.ARROW_N)
else:
display.show("-")
sleep(wait)
display.show("-")
sleep(wait)
def play_sequence():
global count # use the count global variable
global sequence # use the sequence global variable
global wait # use the wait global variable
sequence.append(random.randint(0, 3)) # add a new value to sequence
for i in range(0, count): # loop for sequence length
squark(sequence[i]) # display the arrow
wait = 500 - (count * 15) # vary delay to speed things up
count = count+1 # increment sequence length
def get_tilt():
x = accelerometer.get_x() # read left-right tilt
y = accelerometer.get_y() # read up-down tilt
if x > 100:
return 0 # Right
elif x < -100:
return 1 # Left
elif y > 100:
return 2 # Down
elif y < -100:
return 3 # Up
else:
return 4 # Flat
def reset_game():
global count
global sequence
count=0
sequence=[]
def read_sequence():
global count
global sequence
display.show("*") # Show that we're waiting
for i in range(0, count-1):
while get_tilt()==4: # Wait for a tilt
sleep(50)
input=get_tilt()
if input == sequence[i]: # If it's right then show it
squark(input)
if i==9: # We have a winner
display.show(Image.SMILE)
sleep(1000)
display.show("WINNER")
reset_game()
else:
display.show("X") # Wrong tilt - game over
sleep(1000)
display.show("TRY AGAIN")
reset_game()
break
while True:
play_sequence() # play the sequence to be remembered
read_sequence() # read the sequence from the player
sleep(1000) # wait a sec
|
import random
import sys
def choiceFirstPlayer():
randomChoice = random.randint(0, 1)
if randomChoice == 0:
print('You begins first')
else:
print('Computer begins first')
print()
return randomChoice
def showBoard(currentBoard):
row3 = ' ' + currentBoard[6] + ' | ' + currentBoard[7] + ' | ' + currentBoard[8]
print(row3)
print('---+---+---')
row2 = ' ' + currentBoard[3] + ' | ' + currentBoard[4] + ' | ' + currentBoard[5]
print(row2)
print('---+---+---')
row1 = ' ' + currentBoard[0] + ' | ' + currentBoard[1] + ' | ' + currentBoard[2]
print(row1)
def getBoardCopy(board):
# Make a copy of the board list and return it.
boardCopy = []
for i in board:
boardCopy.append(i)
return boardCopy
def computerAutoPlay(currentBoard):
print()
print('Computer choices')
# Check win
for index in range(1, 10):
boardCopy = getBoardCopy(currentBoard)
if boardCopy[int(index) - 1] == ' ':
boardCopy[int(index) - 1] = computerChoice
win, winner = checkWin(boardCopy)
if win:
currentBoard[int(index) - 1] = computerChoice
return True
# Check lose
for index in range(1, 10):
boardCopy = getBoardCopy(currentBoard)
if boardCopy[int(index) - 1] == ' ':
boardCopy[int(index) - 1] = yourChoice
win, winner = checkWin(boardCopy)
if win:
currentBoard[int(index) - 1] = computerChoice
return True
# Check center
if currentBoard[4] == ' ':
currentBoard[4] = computerChoice
return True
# Check corner
while len(corner) > 0:
enterKey = random.choice(corner)
if currentBoard[int(enterKey)] == ' ':
currentBoard[int(enterKey)] = computerChoice
return
else:
corner.remove(enterKey)
# Check Column
while len(column) > 0:
enterKey = random.choice(column)
if currentBoard[int(enterKey)] == ' ':
currentBoard[int(enterKey)] = computerChoice
return
else:
column.remove(enterKey)
def youPlay(yourChoice, currentBoard):
while True:
print()
print('You can press 1 - 9 to play')
enterKey = input()
if enterKey in '123456789':
if currentBoard[int(enterKey) - 1] == ' ':
currentBoard[int(enterKey) - 1] = yourChoice
break
else:
print('This position already has value')
print()
def checkWin(Board):
if (Board[0] == Board[1]) and (Board[1] == Board[2]) and Board[0] != ' ':
return True, Board[0]
elif (Board[3] == Board[4]) and (Board[4] == Board[5]) and Board[3] != ' ':
return True, Board[3]
elif (Board[6] == Board[7]) and (Board[7] == Board[8]) and Board[6] != ' ':
return True, Board[6]
elif (Board[0] == Board[3]) and (Board[3] == Board[6]) and Board[0] != ' ':
return True, Board[0]
elif (Board[1] == Board[4]) and (Board[4] == Board[7]) and Board[1] != ' ':
return True, Board[1]
elif (Board[2] == Board[5]) and (Board[5] == Board[8]) and Board[2] != ' ':
return True, Board[2]
elif (Board[0] == Board[4]) and (Board[4] == Board[8]) and Board[0] != ' ':
return True, Board[0]
elif (Board[2] == Board[4]) and (Board[4] == Board[6]) and Board[2] != ' ':
return True, Board[2]
else:
return False, ''
yourChoice = ''
computerChoice = ''
currentBoard = []
moves = 0
corner = [0,2,6,8]
column = [1,3,5,7]
def clearBoard():
for iniData in range(9):
currentBoard.append(' ')
print('TIC TAC TOE')
while True:
print('Do you want to choice X or O')
yourChoice = input().upper()
if yourChoice == 'X':
computerChoice = 'O'
break
elif yourChoice == 'O':
computerChoice = 'X'
break
firstPlayer = choiceFirstPlayer()
clearBoard()
while True:
showBoard(currentBoard)
if firstPlayer == 0:
youPlay(yourChoice, currentBoard)
firstPlayer = 1
moves = moves + 1
else:
computerAutoPlay(currentBoard)
firstPlayer = 0
moves = moves + 1
win, winner = checkWin(currentBoard)
if win:
if yourChoice == winner:
print('You are Victory!!!')
firstPlayer = 0
print()
showBoard(currentBoard)
else:
print('Computer is Victory!!!')
firstPlayer = 1
print()
showBoard(currentBoard)
print()
while True:
print('Do you want to play again? (Yes or No)')
playAgain = input().lower()
if playAgain.startswith('y'):
currentBoard = []
clearBoard()
moves = 0
corner = [0,2,6,8]
column = [1,3,5,7]
break
elif playAgain.startswith('n'):
sys.exit()
if moves == 9:
print()
showBoard(currentBoard)
print()
print('Full option')
while True:
print('Do you want to play again? (Yes or No)')
playAgain = input().lower()
if playAgain.startswith('y'):
currentBoard = []
clearBoard()
moves = 0
corner = [0,2,6,8]
column = [1,3,5,7]
break
elif playAgain.startswith('n'):
sys.exit()
|
class Solution:
def maxDistToClosest(self, seats: list[int]) -> int:
l, r, ans = -1, 0, 0
for r in range(0, len(seats)):
if seats[r] == 1:
if l < 0:
ans = max(ans, r)
else:
ans = max(ans, (r - l) // 2)
l = r
return max(ans, len(seats) - l - 1)
# TESTS
for seats, expected in [
([0, 1], 1),
([1, 0, 0, 0, 1, 0, 1], 2),
([1, 0, 0, 0], 3),
([0, 1, 1, 0, 0, 0, 1, 0, 0, 0], 3),
]:
sol = Solution()
actual = sol.maxDistToClosest(seats)
print("Max distance to closest person of", seats, "->", actual)
assert actual == expected
|
from typing import List
class Solution:
def totalNQueens(self, n: int) -> int:
ans = 0
def dfs(queens: List[int], xydiff: List[int], xysum: List[int]) -> None:
"""
queens: column index of placed queens from row [0, n)
xydiff: coordinate diffs have been occupied
xysum: coordinate sums have been occupied
"""
nonlocal ans
r = len(queens)
if r == n:
ans += 1
return
for c in range(n):
if c not in queens and c - r not in xydiff and r + c not in xysum:
dfs(queens + [c], xydiff + [c - r], xysum + [r + c])
dfs([], [], [])
return ans
# TESTS
for n in range(1, 10):
sol = Solution()
actual = sol.totalNQueens(n)
print(f"# of distinct solutions to {n}-queens problem -> {actual}")
|
from typing import List
class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
N, n_of_ones = len(arr), sum(arr)
# check for corner cases
if n_of_ones == 0:
return [0, N - 1]
if n_of_ones % 3 != 0:
return [-1, -1]
# Find the beginning of each part
idx_of_ones = [i for i, v in enumerate(arr) if v == 1]
k = n_of_ones // 3
a, b, c = idx_of_ones[0], idx_of_ones[k], idx_of_ones[2 * k]
# then verify
while c < N and arr[a] == arr[b] == arr[c]:
a, b, c = a + 1, b + 1, c + 1
return [a - 1, b] if c == N else [-1, -1]
# TESTS
for arr, expected in [
([1, 0, 1, 0, 1], [0, 3]),
([1, 1, 0, 1, 1], [-1, -1]),
([1, 1, 0, 0, 1], [0, 2]),
]:
sol = Solution()
actual = sol.threeEqualParts(arr)
print("Three equal parts indices of", arr, "->", actual)
assert actual == expected
|
class Solution:
def detectCapitalUse(self, word: str) -> bool:
if len(word) <= 1:
return True
if word[0].isupper():
return word[1:].isupper() or word[1:].islower()
else:
return word[1:].islower()
def detectCapitalUseV1(self, word: str) -> bool:
return word.islower() or word.isupper() or word.istitle()
def detectCapitalUseV2(self, word: str) -> bool:
cap = 0
for c in word:
if c >= "A" and c <= "Z":
cap += 1
return (
cap == len(word)
or cap == 0
or (cap == 1 and word[0] >= "A" and word[0] <= "Z")
)
# TESTS
tests = [
("USA", True),
("G", True),
("f", True),
("FlaG", False),
("leetcode", True),
("Google", True),
]
for t in tests:
sol = Solution()
actual = sol.detectCapitalUse(t[0])
print("The usage of capitals in", t[0], "is right? ->", actual)
assert (
t[1]
== actual
== sol.detectCapitalUseV1(t[0])
== sol.detectCapitalUseV2(t[0])
)
|
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# cell[0][0] is used twice for row and col flags, we need an extra flag
# to indicate if col 0 should be set zeroes
m, n, c00 = len(matrix), len(matrix[0]), 1
for i in range(m):
if matrix[i][0] == 0:
c00 = 0
for j in range(1, n):
if matrix[i][j] == 0:
matrix[0][j], matrix[i][0] = 0, 0
for i in range(m)[::-1]:
for j in range(1, n)[::-1]:
if matrix[i][j] != 0 and (matrix[0][j] == 0 or matrix[i][0] == 0):
matrix[i][j] = 0
if c00 == 0:
matrix[i][0] = 0
# TESTS
for matrix, expected in [
([[1, 1, 1], [1, 0, 1], [1, 1, 1]], [[1, 0, 1], [0, 0, 0], [1, 0, 1]]),
(
[[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]],
[[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]],
),
(
[[1, 2, 3, 4], [5, 0, 7, 8], [0, 10, 11, 12], [13, 14, 15, 0]],
[[0, 0, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
),
]:
sol = Solution()
print("Set matrix", matrix, "zeroes ->")
sol.setZeroes(matrix)
print(" ", matrix)
assert matrix == expected
|
from typing import List
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 0:
return 0
l, r, prod, ans = 0, 0, 1, 0
while r < len(nums):
prod *= nums[r]
while l <= r and prod >= k:
prod /= nums[l]
l += 1
ans += r - l + 1
r += 1
return ans
# TESTS
tests = [
([10, 5, 2, 6], 0, 0),
([10, 5, 2, 6], 100, 8),
]
for nums, k, expected in tests:
sol = Solution()
actual = sol.numSubarrayProductLessThanK(nums, k)
print("# of subarray in", nums, "with product less than", k, "->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import Tuple
from local_packages.binary_tree import TreeNode
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def deepest(root: TreeNode) -> Tuple[int, TreeNode]:
if not root:
return 0, None
left_depth, left = deepest(root.left)
right_depth, right = deepest(root.right)
if left_depth == right_depth:
return left_depth + 1, root
elif left_depth > right_depth:
return left_depth + 1, left
else:
return right_depth + 1, right
return deepest(root)[1]
# TESTS
for tree, expected in [
("1,#,#", "1,#,#"),
("1,2,#,#,#", "2,#,#"),
("0,1,#,2,#,#,3,#,#", "2,#,#"),
("3,5,6,#,#,2,7,#,#,4,#,#,1,0,#,#,8,#,#", "2,7,#,#,4,#,#"),
(
"1,2,4,#,#,5,8,10,#,#,11,#,#,9,12,#,#,13,#,#,3,6,#,#,#",
"5,8,10,#,#,11,#,#,9,12,#,#,13,#,#",
),
]:
sol = Solution()
actual = TreeNode.serialize(sol.subtreeWithAllDeepest(TreeNode.deserialize(tree)))
print("Smallest Subtree with all the Deepest Nodes in", tree, "->", actual)
assert actual == expected
|
import string
class Solution:
def ladderLength(
self, beginWord: str, endWord: str, wordList: list[str]
) -> int:
wordset = set(wordList)
if not endWord in wordset:
return 0
queue = [(endWord, 1)]
wordset.remove(endWord)
while queue:
w, dist = queue.pop(0)
for i in range(len(w)):
for c in string.ascii_lowercase:
tw = w[:i] + c + w[i + 1 :]
if tw == beginWord:
return dist + 1
if tw in wordset:
queue.append((tw, dist + 1))
wordset.remove(tw)
return 0
# TESTS
for beginWord, endWord, wordList, expected in [
("hit", "cog", ["hot", "dot", "tog", "cog"], 0),
("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"], 5),
("hit", "cog", ["hot", "dot", "dog", "lot", "log"], 0),
("m", "n", ["a", "b", "c"], 0),
("a", "c", ["a", "b", "c"], 2),
("lag", "cog", ["hot", "dot", "dog", "lot", "log", "cog"], 3),
("hot", "dog", ["hot", "dot", "dog", "lot", "log", "cog"], 3),
]:
sol = Solution()
actual = sol.ladderLength(beginWord, endWord, wordList)
print(f"Shortest sequence from '{beginWord}' to '{endWord}' ->", actual)
assert actual == expected
|
from typing import List
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
ans = []
for p in sorted(people, key=lambda hk: (-hk[0], hk[1])):
ans.insert(p[1], p)
return ans
# TESTS
for people, expected in [
([], []),
([[7, 0]], [[7, 0]]),
(
[[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]],
[[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]],
),
(
[[6, 0], [5, 0], [4, 0], [3, 2], [2, 2], [1, 4]],
[[4, 0], [5, 0], [2, 2], [3, 2], [1, 4], [6, 0]],
),
]:
sol = Solution()
actual = sol.reconstructQueue(people)
print("After reconstructing queue ->", actual)
assert actual == expected
|
class Solution:
def partition(self, s: str) -> list[list[str]]:
ans = []
def dfs(s: str, path: list[str]) -> None:
if not s:
ans.append(path[:])
else:
for i in range(1, len(s) + 1):
if s[:i] == s[:i][::-1]:
path.append(s[:i])
dfs(s[i:], path)
path.pop()
dfs(s, [])
return ans
# TESTS
for s, expected in [
(
"aab",
[
["a", "a", "b"],
["aa", "b"],
],
),
("a", [["a"]]),
]:
sol = Solution()
actual = sol.partition(s)
print("All possible palindrome partitioning of", s, "->", actual)
assert sorted(actual) == sorted(expected)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import List
from local_packages.binary_tree import TreeNode
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
assert len(inorder) == len(postorder)
if len(inorder) == 0:
return None
root_index = inorder.index(postorder[-1])
root = TreeNode(
postorder[-1],
self.buildTree(inorder[:root_index], postorder[:root_index]),
self.buildTree(inorder[root_index + 1 :], postorder[root_index:-1]),
)
return root
# TESTS
tests = [
([], [], "#"),
([1], [1], "1,#,#"),
([2, 1], [2, 1], "1,2,#,#,#"),
([1, 2], [2, 1], "1,#,2,#,#"),
([2, 1, 3], [2, 3, 1], "1,2,#,#,3,#,#"),
([9, 3, 15, 20, 7], [9, 15, 7, 20, 3], "3,9,#,#,20,15,#,#,7,#,#"),
]
for t in tests:
sol = Solution()
actual = TreeNode.serialize(sol.buildTree(t[0], t[1]))
print("Construct from", t[0], t[1], "->", actual)
assert actual == t[2]
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from local_packages.binary_tree import TreeNode
from typing import Optional
class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
bfs, i = [root], 0
while bfs[i]:
bfs.append(bfs[i].left)
bfs.append(bfs[i].right)
i += 1
return not any(bfs[i:])
# TESTS
for tree, expected in [
("1,2,4,#,#,5,#,#,3,6,#,#,#", True),
("1,2,4,#,#,5,#,#,3,#,7,#,#", False),
]:
sol = Solution()
actual = sol.isCompleteTree(TreeNode.deserialize(tree))
print(tree, "is a complete tree ->", actual)
assert actual == expected
|
from typing import List
class Solution:
def pancakeSort(self, A: List[int]) -> List[int]:
N, ans = len(A), []
for n in range(N, 1, -1):
k = A.index(n)
if k < n - 1: # not already sorted
ans.extend([k + 1, n])
A = A[:k:-1] + A[:k]
return ans
# TESTS
tests = [
[1],
[2, 1],
[1, 2, 3],
[1, 3, 2, 4],
[3, 2, 4, 1],
[4, 5, 1, 2, 3],
[8, 7, 6, 5, 4, 3, 2, 1],
]
for t in tests:
sol = Solution()
print("k-values of the pancake flips of sorting", t, "->", sol.pancakeSort(t))
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from local_packages.list import ListNode
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow, fast = head, head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
return True
return False
# TESTS
for array, pos, expected in [
([3, 2, 0, -4], 1, True),
([1, 2], 0, True),
([1], -1, False),
([1], 0, True),
]:
sol = Solution()
head = ListNode.from_array(array)
if expected:
cycle_pos = head
while pos > 0:
cycle_pos, pos = cycle_pos.next, pos - 1
tail = head
while tail and tail.next:
tail = tail.next
tail.next = cycle_pos
actual = sol.hasCycle(head)
print(array, pos, "has cycle ->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from local_packages.binary_tree import TreeNode
from typing import Optional
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
if root is None:
return ""
lstr = (
f"({self.tree2str(root.left)})" if root.left or root.right else ""
)
rstr = f"({self.tree2str(root.right)})" if root.right else ""
return f"{root.val}{lstr}{rstr}"
# TESTS
for t, expected in [
("1,2,4,#,#,#,3,#,#", "1(2(4))(3)"),
("1,2,#,4,#,#,3,#,#", "1(2()(4))(3)"),
]:
sol = Solution()
actual = sol.tree2str(TreeNode.deserialize(t))
print(t, "->", actual)
assert actual == expected
|
from collections import defaultdict
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.links = defaultdict(Trie)
self.is_end = False
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
p = self
for c in word:
p = p.links[c]
p.is_end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
p = self
for c in word:
if c not in p.links:
return False
p = p.links[c]
return p.is_end
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
p = self
for c in prefix:
if c not in p.links:
return False
p = p.links[c]
return True
# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert("apple")
assert obj.search("apple") == True
assert obj.search("app") == False
assert obj.startsWith("app") == True
obj.insert("app")
assert obj.search("app") == True
|
class MapSumV1:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = dict()
def insert(self, key: str, val: int) -> None:
self.d[key] = val
def sum(self, prefix: str) -> int:
return sum(self.d[key] for key in self.d if key.startswith(prefix))
from collections import defaultdict
class TrieNode:
def __init__(self):
self.child = defaultdict(TrieNode)
self.sum = 0 # Store the sum of values of all strings go through this node.
class MapSumV2:
def __init__(self):
self.root = TrieNode()
self.map = defaultdict(int)
def insert(self, key: str, val: int) -> None:
# if the key already existed, the original key-value pair will be overridden to the new one.
diff = val - self.map[key]
curr = self.root
for c in key:
curr = curr.child[c]
curr.sum += diff
self.map[key] = val
def sum(self, prefix: str) -> int:
curr = self.root
for c in prefix:
if c not in curr.child:
return 0
curr = curr.child[c]
return curr.sum
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)
# TESTS
obj = MapSumV2()
obj.insert("apple", 3)
assert obj.sum("ap") == 3
obj.insert("app", 2)
assert obj.sum("ap") == 5
|
from typing import List
class Solution:
def validateStackSequencesV1(self, pushed: List[int], popped: List[int]) -> bool:
stack, i, j, n = [], 0, 0, len(pushed)
while j < n:
if len(stack) == 0 or stack[-1] != popped[j]:
if i == n:
return False
stack.append(pushed[i])
i += 1
else:
stack.pop()
j += 1
return len(stack) == 0
def validateStackSequencesV2(self, pushed: List[int], popped: List[int]) -> bool:
stack, j = [], 0
for v in pushed:
stack.append(v)
while len(stack) > 0 and stack[-1] == popped[j]:
stack.pop()
j += 1
return len(stack) == 0
# TESTS
for pushed, popped, expected in [
([1, 2, 3, 4, 5], [4, 5, 3, 2, 1], True),
([1, 2, 3, 4, 5], [4, 3, 5, 1, 2], False),
([], [], True),
]:
sol = Solution()
actual = sol.validateStackSequencesV1(pushed, popped)
print("Are", pushed, popped, "validate stack sequences ->", actual)
assert actual == expected
assert expected == sol.validateStackSequencesV2(pushed, popped)
|
from cmath import exp
from collections import Counter
from curses.ascii import SO
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
for s, t, expected in [
["rat", "cat", False],
["eat", "tea", True],
["anagram", "nagaram", True],
["成功", "功成", True],
["成功", "功夫", False],
]:
sol = Solution()
actual = sol.isAnagram(s, t)
print(f"Is {s} and {t} anagram? -> {actual}")
assert actual == expected
|
from typing import Tuple
class Solution:
def complexNumberMultiply(self, num1: str, num2: str) -> str:
parse = lambda num: map(int, num[:-1].split("+", 1))
r1, i1 = parse(num1)
r2, i2 = parse(num2)
return f"{r1 * r2 - i1 * i2}+{r1 * i2 + r2 * i1}i"
# TESTS
for num1, num2, expected in [
("1+1i", "1+1i", "0+2i"),
("1+-1i", "1+-1i", "0+-2i"),
]:
sol = Solution()
actual = sol.complexNumberMultiply(num1, num2)
print(f"{num1} * {num2} = {actual}")
assert actual == expected
|
class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
if stack and stack[-1] == c.swapcase():
stack.pop()
else:
stack.append(c)
return "".join(stack)
# TESTS
for s, expected in [
("leEeetcode", "leetcode"),
("abBAcC", ""),
("s", "s"),
]:
sol = Solution()
actual = sol.makeGood(s)
print("After making", s, "good ->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from local_packages.binary_tree import TreeNode
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root
# TESTS
tests = [
("#", 1, "1,#,#"),
("4,2,1,#,#,3,#,#,7,#,#", 5, "4,2,1,#,#,3,#,#,7,5,#,#,#"),
(
"40,20,10,#,#,30,#,#,60,50,#,#,70,#,#",
25,
"40,20,10,#,#,30,25,#,#,#,60,50,#,#,70,#,#",
),
]
for tree, val, expected in tests:
sol = Solution()
actual_tree = sol.insertIntoBST(TreeNode.deserialize(tree), val)
actual = TreeNode.serialize(actual_tree)
print("Insert", val, "into", tree, "->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from local_packages.binary_tree import TreeNode
class Solution:
def getTargetCopyV1(
self, original: TreeNode, cloned: TreeNode, target: TreeNode
) -> TreeNode:
if not original or original is target:
return cloned
left = self.getTargetCopy(original.left, cloned.left, target)
if left:
return left
return self.getTargetCopy(original.right, cloned.right, target)
def getTargetCopyV2(
self, original: TreeNode, cloned: TreeNode, target: TreeNode
) -> TreeNode:
def iterator(node: TreeNode):
if node:
yield node
yield from iterator(node.left)
yield from iterator(node.right)
for n1, n2 in zip(iterator(original), iterator(cloned)):
if n1 is target:
return n2
|
from typing import List
from random import random
import math
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.rad = radius
self.x, self.y = x_center, y_center
def randPoint(self) -> List[float]:
rad = self.rad * math.sqrt(random())
theta = 2 * math.pi * random()
return [
self.x + rad * math.cos(theta),
self.y + rad * math.sin(theta),
]
# Your Solution object will be instantiated and called as such:
# obj = Solution(radius, x_center, y_center)
# param_1 = obj.randPoint()
for radius, x_center, y_center, n in [
(1, 0, 0, 3),
(5, 1, 1, 5),
(7, -1, 0, 7),
(10, 5, -7.5, 10),
]:
sol = Solution(radius, x_center, y_center)
print(
f"Random points in circle ({radius}, {x_center}, {y_center}) ->",
[sol.randPoint() for _ in range(n)],
)
|
from typing import List
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
visited = {0}
def dfs(i: int) -> None:
for k in rooms[i]:
if k not in visited:
visited.add(k)
dfs(k)
dfs(0)
return len(visited) == len(rooms)
# TESTS
for rooms, expected in [
([[1], [2], [3], []], True),
([[1, 3], [3, 0, 1], [2], [0]], False),
]:
sol = Solution()
actual = sol.canVisitAllRooms(rooms)
print("You can enter every room in", rooms, "->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from local_packages.binary_tree import TreeNode
from typing import Optional
from collections import defaultdict
class Solution:
def findDuplicateSubtrees(
self, root: Optional[TreeNode]
) -> list[Optional[TreeNode]]:
seen = defaultdict(list)
def postorder(node: Optional[TreeNode]) -> None:
if not node:
return "#"
serialized = (
f"{node.val},{postorder(node.left)},{postorder(node.right)}"
)
seen[serialized].append(node)
return serialized
postorder(root)
return [seen[key][0] for key in seen if len(seen[key]) > 1]
# TESTS
for tree, expected in [
("1,2,4,#,#,#,3,2,4,#,#,#,4,#,#", ["4,#,#", "2,4,#,#,#"]),
("2,1,#,#,1,#,#", ["1,#,#"]),
("2,2,3,#,#,#,2,3,#,#,#", ["3,#,#", "2,3,#,#,#"]),
]:
sol = Solution()
actual = [
TreeNode.serialize(root)
for root in sol.findDuplicateSubtrees(TreeNode.deserialize(tree))
]
print("Find duplicate subtrees in", tree, "->", actual)
assert actual == expected
|
from typing import List
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
row = [1]
while rowIndex > 0:
row = [0] + row
for i in range(len(row) - 1):
row[i] += row[i + 1]
rowIndex -= 1
return row
# TESTS
tests = [
(0, [1]),
(1, [1, 1]),
(2, [1, 2, 1]),
(3, [1, 3, 3, 1]),
(4, [1, 4, 6, 4, 1]),
]
for t in tests:
sol = Solution()
actual = sol.getRow(t[0])
print("Pascal triangle of", t[0], "index ->", actual)
assert actual == t[1]
|
from typing import List
from collections import defaultdict
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
edge_count, max_count = defaultdict(int), 0
for row in wall:
s = 0
for brick in row[0:-1]:
s += brick
edge_count[s] += 1
max_count = max(max_count, edge_count[s])
return len(wall) - max_count
# TESTS
for wall, expected in [
([[1, 2, 2, 1], [3, 1, 2], [1, 3, 2], [2, 4], [3, 1, 2], [1, 3, 1, 1]], 2),
([[3], [3], [3]], 3),
]:
sol = Solution()
actual = sol.leastBricks(wall)
print("The least of crossed bricks in", wall, "->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from local_packages.binary_tree import TreeNode
from collections import defaultdict
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> list[int]:
graph = defaultdict(list)
def build_graph(node: TreeNode, parent: TreeNode) -> None:
if node and parent:
graph[node.val].append(parent.val)
graph[parent.val].append(node.val)
if node.left:
build_graph(node.left, node)
if node.right:
build_graph(node.right, node)
build_graph(root, None)
ans = []
visited = set([target.val])
def dfs(curr: int, distance: int) -> None:
if distance == k:
ans.append(curr)
return
for neighbor in graph[curr]:
if neighbor not in visited:
visited.add(neighbor)
dfs(neighbor, distance + 1)
dfs(target.val, 0)
return ans
|
from typing import List
from collections import defaultdict
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
ans = [[0 for _ in r] for r in mat]
m, n = len(mat), len(mat[0])
diag = defaultdict(list)
for i in range(m):
for j in range(n):
diag[i - j].append(mat[i][j])
for d in diag:
diag[d].sort(reverse=True)
for i in range(m):
for j in range(n):
ans[i][j] = diag[i - j].pop()
return ans
# TESTS
for mat, expected in [
([[1]], [[1]]),
(
[[3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2]],
[[1, 1, 1, 1], [1, 2, 2, 2], [1, 2, 3, 3]],
),
]:
sol = Solution()
actual = sol.diagonalSort(mat)
print("Diagonal sort", mat, "->", actual)
assert actual == expected
|
from math import sqrt
class Solution:
def countPrimes(self, n: int) -> int:
if n < 2:
return 0
is_prime = [0, 0] + [1] * (n - 2)
for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
is_prime[i * i : n : i] = [0] * len(is_prime[i * i : n : i])
return sum(is_prime)
# TESTS
for n, expected in [
[0, 0],
[3, 1],
[4, 2],
[5, 2],
[6, 3],
[7, 3],
[8, 4],
[10, 4],
[15, 6],
[300, 62],
[1000, 168],
[5000, 669],
]:
sol = Solution()
actual = sol.countPrimes(n)
print("# of primes less than", n, "->", actual)
assert actual == expected
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import List, Optional
from collections import defaultdict
from local_packages.binary_tree import TreeNode
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = defaultdict(list)
def helper(root: Optional[TreeNode]) -> int:
if not root:
return -1
idx = 1 + max(helper(root.left), helper(root.right))
ans[idx].append(root.val)
return idx
helper(root)
return list(ans.values())
# TESTS
for tree, expected in [
("1,2,4,#,#,5,#,#,3,#,#", [[4, 5, 3], [2], [1]]),
("1,#,#", [[1]]),
]:
sol = Solution()
actual = sol.findLeaves(TreeNode.deserialize(tree))
print("Find leaves of tree", tree, "->", actual)
assert actual == expected
|
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for token in path.split("/"):
if token == "." or token == "":
continue
elif token == "..":
if stack:
stack.pop()
else:
stack.append(token)
return "/" + "/".join(stack)
# TESTS
for path, expected in [
("", "/"),
("/", "/"),
("/a/b", "/a/b"),
("/home/", "/home"),
("/../", "/"),
("/home//foo/", "/home/foo"),
("/a/./b/../../c/", "/c"),
]:
sol = Solution()
actual = sol.simplifyPath(path)
print("Simplified canonical path of", path, "->", actual)
assert actual == expected
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from local_packages.list import ListNode
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow = fast = entry = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
while slow != entry:
slow, entry = slow.next, entry.next
return entry
return None
# TESTS
for array, pos in [
([3, 2, 0, -4], 1),
([1, 2], 0),
([1], -1),
]:
sol = Solution()
# build the cycle
head = ListNode.from_array(array)
p, entry, i = head, None, 0
while p and p.next:
if i == pos:
entry = p
p, i = p.next, i + 1
p.next = entry
actual = sol.detectCycle(head)
print("The node where cycle begins in", array, "->", actual and actual.val)
assert actual == entry
|
from functools import reduce
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
func = lambda res, c: res[:-1] if c == "#" else res + [c]
return reduce(func, s, []) == reduce(func, t, [])
# TESTS
for s, t, expected in [
("ab#c", "ad#c", True),
("ab##", "c#d#", True),
("a##c", "#a#c", True),
("a#c", "b", False),
]:
sol = Solution()
actual = sol.backspaceCompare(s, t)
print("Backspace compare(", s, ",", t, ") ->", actual)
assert actual == expected
|
class Solution:
def hammingDistanceV1(self, x: int, y: int) -> int:
ans, xor = 0, x ^ y
while xor:
ans += 1 if xor & 1 else 0
xor >>= 1
return ans
def hammingDistanceV2(self, x: int, y: int) -> int:
ans, xor = 0, x ^ y
while xor:
ans += 1
xor &= xor - 1
return ans
# TESTS
for x, y, expected in [
[1, 1, 0],
[2, 3, 1],
[1, 4, 2],
[4, 8, 2],
[4, 9, 3],
[4, 10, 3],
[1, 19091801, 10],
]:
sol = Solution()
actual = sol.hammingDistanceV2(x, y)
print("Hamming distance of", x, y, "->", actual)
assert actual == expected
|
from typing import List
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binarySearch(l: int, r: int, first: bool) -> int:
nonlocal target
while l <= r:
mid = l + (r - l) // 2
if nums[mid] < target:
l = mid + 1
elif nums[mid] > target:
r = mid - 1
else: # == target
if first: # search for the first position
if mid == 0 or nums[mid - 1] != target:
return mid
else:
r = mid - 1
else: # search for the last position
if mid == len(nums) - 1 or nums[mid + 1] != target:
return mid
else:
l = mid + 1
return -1
first = binarySearch(0, len(nums) - 1, True)
if first == -1:
return [-1, -1]
return [first, binarySearch(first, len(nums) - 1, False)]
# TESTS
for nums, target, expected in [
([5, 7, 7, 8, 8, 10], 8, [3, 4]),
([5, 7, 7, 8, 8, 10], 6, [-1, -1]),
([], 0, [-1, -1]),
([5, 7, 7, 8, 8, 10, 10, 10], 5, [0, 0]),
([5, 7, 7, 8, 8, 10, 10, 10], 10, [5, 7]),
]:
sol = Solution()
actual = sol.searchRange(nums, target)
print("Search", target, "in", nums, "->", actual)
assert actual == expected
|
from collections import Counter
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
diff = Counter(t) - Counter(s)
return list(diff.keys())[0]
def findTheDifferenceXor(self, s: str, t: str) -> str:
code = 0
for ch in s + t:
code ^= ord(ch)
return chr(code)
# TESTS
for s, t, expected in [
("abcd", "abcde", "e"),
("abcd", "abcdd", "d"),
("aaaaa", "aaaaaa", "a"),
("aaaaa", "aabaaa", "b"),
]:
sol = Solution()
actual = sol.findTheDifference(s, t)
print("The letter that was added in", t, "from", s, "->", actual)
assert actual == expected
assert expected == sol.findTheDifferenceXor(s, t)
|
from typing import List
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for n in asteroids:
while n < 0 and stack and stack[-1] > 0:
if n + stack[-1] == 0:
stack.pop()
break
elif n + stack[-1] < 0:
stack.pop()
else:
break
else:
stack.append(n)
return stack
# TESTS
for asteroids, expected in [
([5, 10, -5], [5, 10]),
([8, -8], []),
([10, 2, -5], [10]),
([-2, -1, 1, 2], [-2, -1, 1, 2]),
([1, 2, -4, 3], [-4, 3]),
]:
sol = Solution()
actual = sol.asteroidCollision(asteroids)
print("After all collisions in", asteroids, "->", actual)
assert actual == expected
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.