text stringlengths 37 1.41M |
|---|
"""
recursive function
summary of number sequence
s(n) = s(n-1) + n
s(10) = s(9) + 10
s(9) = s(8) + 9
...
s(1) = 1
"""
def s(n):
if n == 1:
return 1
return s(n-1) + n
result = s(10)
print(f"The sum is {result}")
"""
numbers = [1,2,3,4,5,6,7,8,9,10]
print("=== start ===")
sum = 0
for n in numbers:
sum += n
print(f"The sum is {sum}")
print("=== end ===")
"""
|
"""
string to datetime object
"""
from datetime import datetime
date_string = "6 December, 2020 01:10:38"
print("date_string =", date_string)
print("type of date_string =", type(date_string))
try:
date_object = datetime.strptime(date_string, "%d %B, %Y %H:%M:%S")
except ValueError as ve:
print("String does not match!")
print("date_object =", date_object)
print("type of date_object =", type(date_object)) |
"""
Q2.chengjun
"""
list1 = [1, 2, 3, 4, 5]
a = 1
for b in list1:
a= a * b
print(a) |
"""
1, 2, 3, 4, ..., 20 ?
product = 1x2x3x....x20
"""
product = 1
"""
product x 1 -> product
product x 2 -> product
...
product x 20 -> product
"""
for i in range(1,21):
product = product * i
print("Product is {}".format(product))
"""
2432902008176640000
2432902008176640000
""" |
"""
set max size for a window
maxsize != maximize
"""
import tkinter as tk
root = tk.Tk()
root.title('Python GUI - subtopic')
winw= 800
winh= 450
posx=300
posy=200
root.geometry(f'{winw}x{winh}+{posx}+{posy}')
# case 1.
root.maxsize()
# case 2.
root.maxsize(1000,600)
root.mainloop() |
"""
python file I/O
Opening Files
open()
first look
"""
# case 4. open file which does not exist
# error occurs
print("[info] open file in specified full path")
print("[info] opening file_open.txt ...")
# FileNotFoundError: [Errno 2] No such file or directory:
f = open("D:/workspace/pycharm201803/ceit4101python/module_8_fileio/file_not_exist.txt")
print("[info] closing ...")
f.close()
print("[info] done.")
|
"""
[Homework]
Write codes to try out number formatting type
Date: 2021-05-09
Due date: by the end of next Sat.
"""
# case 1
num1 = 10
str1 = "I am testing the data: {:5d}".format(num1)
print(str1)
print('======')
# case 2.
char = 200
str2 = "I am testing the data: {:c}".format(char)
print(str2)
char = 201
str2 = "I am testing the data: {:c}".format(char)
print(str2)
char = 202
str2 = "I am testing the data: {:c}".format(char)
print(str2)
print('======')
# case 3.
num2 = 200
str2 = "I am testing the data: {:b}".format(num2)
print(str2)
print(0b11001000)
print('======')
# case 4.
num3 = 200
str2 = "I am testing the data: {:o}".format(num3)
print(str2)
print(0o310)
print('======')
# case 5.
num4 = 200
str2 = "I am testing the data: {:x}".format(num4)
print(str2)
print(0xc8)
print('======')
# case 6.
num5 = 200
str2 = "I am testing the data: {:X}".format(num5)
print(str2)
print(0xC8)
print('======')
# case 7.
num5 = 200
str2 = "I am testing the data: {:n}".format(num5)
print(str2)
print('======')
# case 8.
num5 = 200
str2 = "I am testing the data: {:e}".format(num5)
print(str2)
print(2.000000e+02)
print('======')
# case 9.
num5 = 200
str2 = "I am testing the data: {:E}".format(num5)
print(str2)
print(2.000000E+02)
print('======')
# case 10.
num5 = 200
str2 = "I am testing the data: {:f}".format(num5)
print(str2)
print('======')
# case 11.
num5 = 200
str2 = "I am testing the data: {:F}".format(num5)
print(str2)
print('======')
# case 12.
num5 = 1.23456789
str2 = "I am testing the data: {:g}".format(num5)
print(str2)
print('======')
# case 13
str2 = "I am testing the data: {:G}".format(num5)
print(str2)
print('======')
# case 14
num5 = 200
str2 = "I am testing the data: {:%}".format(num5)
print(str2)
|
"""
i/o
input / output
standard input dev. keyboard
standard output dev. monitor/screen/console
*object
sep = separator
end = '\n'
"""
print("hello")
print("hello","world", sep="_")
print("hello","world", sep=",")
print("hello","world", sep=";")
print("hello","world", sep=":")
print("hello","world", sep="::")
print(1,2,3,4, sep="::")
print("==============")
print()
print("==============")
print(end='\n')
print("==============")
|
"""
stem1402_python_homework_2_steven
"""
# 1. Write a Python function to find the Max of three numbers.
def maximum(x, y, z):
list1 = [x, y, z]
return max(list1)
x = 21
y = 346
z = 345
print("The maximum number of {}, {} and {}, is {}".format(x, y, z, maximum(x,y,z)))
print("-------------------------------------------------------------------------")
print()
# 2. Write a Python function to sum all the numbers in a list.
list1 = [1,3,4,23,5,463,45,36,1]
def adding(list):
sum = 0
for num in list1:
sum += num
return sum
print("The sum of the numbers in {} is {}.".format(list1, adding(list1)))
print("-------------------------------------------------------------------------")
print()
# 3. Write a Python function to multiply all the numbers in a list.
list1 = [1,3,4,23,5,463,45,36,1]
def multiplying(list):
product = 1
for num in list1:
product *= num
return product
print("The product of the numbers in {} is {}.".format(list1, multiplying(list1)))
print("-------------------------------------------------------------------------")
print()
# 4. Write a Python program to reverse a string.
a = [1,32,354,36,3]
def reverse(list):
n = len(a) - 1
while n >= 0:
print(a[n], end=" ")
n -= 1
print("When you reverse", a, "you get", end=" "), reverse(list)
print()
print("-------------------------------------------------------------------------")
|
def AND(num_1, num_2):
return num_1 and num_2
print(AND(float(input('Please enter the and:')),float(input('Please enter the other and:')))) |
"""
8. Write a Python function that takes a list of words and
returns the length of the longest one.
"""
"""
wordlist = ['abc','cdef','ab','cdefg','bccc']
longest = wordlist[0]
for word in wordlist:
# print(word, len(word))
if len(longest) < len(word):
longest = word
print("The length of the longest word is {}.".format(len(longest)))
"""
def getlongest(wordlist):
if len(wordlist) == 0:
return 0
else:
longest = wordlist[0]
for word in wordlist:
# print(word, len(word))
if len(longest) < len(word):
longest = word
return len(longest)
# main program
wordlist = ['abc','a','ab']
print(getlongest(wordlist))
|
"""
review list
"""
# TypeError: '<' not supported between instances of 'str' and 'int'
my_list = [2,'a5',1,'b6',7]
# my_list.sort()
# original password: mylaptop
# encrypt by reversing
original_pwd = ['m','y','l','a','p','t','o','p']
print(original_pwd)
original_pwd.reverse()
new_pwd = original_pwd
print(new_pwd)
result = ''
for i in new_pwd:
result += i
print("Encrypted password is '{}'".format(result))
|
"""
you can input a Name again and again from keyboard
Bonsoir, the Name!
if you input 'Eva'
print out Bonjour, Eva
and then exit the program
"""
def greeting(name):
print("Bonsoir {}".format(name))
while True:
name = input("Input your name:")
if 'eva' == name.lower():
print('Bonjour {}'.format(name))
break
else:
greeting(name)
|
"""
[Homework]
Quiz6. question 8
"""
"""
Q8
"""
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
print(matrix[0][0], str(matrix[0][1])+'\t', str(matrix[0][2])+'\t', matrix[0][3])
print(matrix[1][0], str(matrix[1][1])+'\t', str(matrix[1][2])+'\t', matrix[1][3])
print(matrix[2][0], str(matrix[2][1]), str(matrix[2][2])+'\t', matrix[2][3])
print("==================")
#
row1 = [1, 2, 3, 4]
row2 = [5, 6, 7, 8]
row3 = [9, 10, 11, 12]
print(row1)
print(row2)
print(row3)
|
"""
summary
1. list comp. is an elegant way to define and create lists based on existing lists.
2. list comp. is generally more compact and faster than normal functions and loops for creating lists.
3. we should avoid writing very long list comp in one line to ensure that code is user-friendly.
4. every list comp. can be rewritten in for-loop, but every for loop cannot be rewritten in the form of list comp.
"""
"""
[Homework]
Date: 2021-04-03
1. Write a program to generate a list.
selecting all even numbers from 1 to 100, and then generate a list in which each item is square of the corresponding even number.
Hints: Using list comprehension
Sample: [1,2,3,4,5,6,7,...100]
Expected Result: [ 4, 16, 36, 64, 100, ... , 10000]
2. Write a program to generate a list.
There are two given string 'ABC' and 'XYZ'
generating a new list like ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
Hints: Using list comprehension
Due Date: by the end of next Friday
""" |
def replaceall(target, new):
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] * 3
next_index = -1
for i in my_list:
if i == target:
next_index = my_list.index(i, next_index + 1)
print(next_index)
my_list[next_index] = new
return my_list
my_list = replaceall('r', 'x')
print(my_list)
|
"""
insert items
"""
# case 1. insert a single item
# insert(index, item)
odd = [1,9]
odd.insert(1, 3)
print(odd)
# case 2. insert multi items
odd[2:2] = [5,7]
print(odd)
# odd[2:2] = []
# print(odd) |
# program 2
"""
# plan:
1. define characters
2. input the string
3. create "counting"
4. define a counter function
3. count the number of each character using the counter
4. print the result of each character
"""
# program:
def counter(user_str):
counting = {}
for char in user_str:
try:
counting[char] += 1
except KeyError:
counting[char] = 1
return counting
# characters = '''abcdefghijklmnopqrstuvwxyz1234567890, ./;'#][{}~@:<>?"`¬\|'''
user_str = input("Write your string and I will count the number of time each character is occurring: ")
counter(user_str)
# for characters in user_str:
# counting = {}
#
# def counter(user_str):
# for characters in user_str:
# try:
# counting[characters] += 1
# except KeyError:
# counting[characters] = 1
# return counting
print(counter(user_str))
|
"""
converting a floating number to a fraction
"""
import fractions
import decimal
# ex1.
print(fractions.Fraction(1.1))
print(decimal.Decimal(1.1))
print(decimal.Decimal('1.1'))
print()
# solution 1. limit denominator
result = fractions.Fraction(1.1).limit_denominator()
print(result)
# solution 2. as string
print(fractions.Fraction('1.1'))
|
"""
fraction
f = p/q (p, q are integers, q!=0)
A fraction has a numerator and a denominator,
both of which are integers.
This module has support for rational number arithmetic.
"""
import fractions
from fractions import Fraction as F
f1 = fractions.Fraction(1.5)
print(f1)
f2 = fractions.Fraction(1.3)
print(f2)
f3 = fractions.Fraction('1.3')
print(f3)
f4 = F(1.6)
print(f4)
f4 = F('1.6')
print(f4)
# accepting 2 parameters
f5 = F(8,3)
print(f5)
f6 = F(1,5)
print(f6)
|
"""
string literal
"""
# case 1: normal string with ", '
strings = "This is Python"
strings2 = 'This is Python'
print("strings",strings)
print("strings2",strings2)
# case 2
char = "C"
char = 'C'
print("char",char)
# case 3
multiline_str = """This is a multiline string with more than one line code."""
print(multiline_str)
multiline_str = """66666 This is a multiline string
with more than one line code.
ksdjfasdfaskdf asdfjas dfas f sdf as dfas"""
print(multiline_str)
multiline_str = '''66666 This is a multiline string
with more than one line code.
ksdjfasdfaskdf asdfjas dfas f sdf as dfas'''
print(multiline_str)
# case 4: escaped character
print("This is a multiline string. It is powerful")
print("This is a multiline string. \n It is powerful")
# new line \n
# \\
# \'
# \"
# \n
# \t
print("This is a quote like \" ")
print("This is a quote like \' ")
print("This is a quote like \t is a quote like \t is a quote")
# case 5: unicode
unicode = u"\u00dcnic\u00f6de"
copywrite = "Copyright. \u00A9 All rights reserved"
print(copywrite)
ibmtm = "IBM \u2122"
print(ibmtm)
# case 6: raw string
raw_str = r"raw \n string"
print(raw_str)
|
"""
[Homework]
Date: 2021-01-24
Write a Python GUI program to create your own window
Common requirements:
1. set a title
2. set an image icon
Extra requirements:
1. specify dimension at 16:9
2. make it at center point on your screen
3. set a background color
4. make it topmost
5. set max size and min size
6. make it resizable
7. print out the initial height and width of your window at console
8. resizing your window
9. print out the current height and width of your window at console
"""
"""
score
not executable (-35)
"""
import tkinter as tk
root = tk.Tk()
# 1.
root.title("Python GUI - Homework")
# 2.
### root.iconbitmap("IMG_2408.ico")
# extra requirements
# 1. and 2.
width = int(input("Please input the width of the window (Note that width:height must be equal to 16:9)"))
height = int(input("Please input the height of the window (Note that width:height must be equal to 16:9)"))
root.geometry("{}x{}+{}+{}".format(width, height, root.winfo_screenwidth()/2 - width/2, root.winfo_screenheight()/2 - height/2))
# 3.
root.config(bg="gold")
# 4.
root.attributes('-topmost', True)
# 5.
root.maxsize()
root.minsize(300, 200)
# 6.
root.resizable(True, True)
root.update()
# 7.
print("Height = {}, Width = {}".format(root.winfo_height(), root.winfo_width()))
# 8.
root.geometry("{}x{}+{}+{}".format(600, 400, root.winfo_screenwidth()/2 - 600/2, root.winfo_screenheight()/2 - 400/2))
root.update()
# 9.
print("Height = {}, Width = {}".format(root.winfo_height(), root.winfo_width()))
root.mainloop() |
"""
review of function
"""
"""
1a. what is function in python
1b. what is function in math
mapping relationship
2. how it works
3. define a function
keyword: def
4. how to use
call a function
5. syntax of function
signature of function
function name
function argument
return statement
6. input and output of function
7. function type
built-in function print(), len(), type(), id()
user-defined function
8. function arguments
positional argument
default argument
variable argument
keyword argument
arbitrary argument print(*obj) i.e. print(1) print(2,3)
9. Recursive function and recursion
process include itself, call it in itself
iteration i.e. for
10. Anonymous function/ lambda function
lambda arg1,[arg2,...] : expr
as a parameter
high order function
filter(func, iterable), map(func, iterable)
11. global scope, local scope, module scope
global variable
local variable
accessibility and visibility
""" |
"""
User-defined Exceptions
1. what is it?
2. how to write
3. how to use
4. why to use
a. Built-in error
b. ValueError, ValueError
c. reusable
Exception/Error
Runtime
Logical
Built-in Error
20-30
Syntax
try:
pass
except:
pass
except:
pass
else:
pass
finally:
pass
try:
pass
except:
pass
try:
pass
except:
pass
else:
pass
try:
pass
finally:
pass
catch specific error
except SpecificErrorName
except (ErrorName1, ErrorName2, ...)
exception/error category
Concrete error type
Exception
"""
class CustomError(Exception):
pass
condition = True
if condition:
raise CustomError("This is a customError")
|
"""
set
set()
empty set
"""
mylist = [1,2,3,2]
myset = set(mylist)
print(myset)
mytuple = (1,2,3,2)
myset = set(mytuple)
print(myset)
# empty set
set1 = {}
print(type(set1))
set1 = set()
print(type(set1))
|
str1 = "aaaaaaaaaaa"
str2 = "ab"
"11"
"2"
print("11">"2")
print(11>2) |
"""
2021-04-04
Quiz5 q1 - q6
Due date: by the end of next Sat.
"""
"""
answer:
q1
ans: a
q2
ans: integers: class 'int'
floating point numbers: class 'float'
complex numbers: class 'complex'
q3
ans: integers: a = 1, a = 2
floating point numbers: b = 1.5, b = 2.5
complex numbers: c = 1+2j, c = 2+4j
q4
ans: sample code (integer example)
z = 10
print('The data type of z is', type(z))
q5
ans: num = 9
print('The data type of num is', type(num))
print(isinstance(num, int))
'True'
"""
# test answer here
# q4 answer code
z = 10
print('The data type of z is', type(z))
# q5 answer code
num = 9
print('The data type of num is', type(num))
print(isinstance(num, int))
# test answer 'True'
|
def word(a,y):
b = []
c = y.split(" ")
for i in c:
if len(i) > a:
b.append(i)
return b
x = ('The python homework number three')
print(word(4,x))
|
"""
collection
"""
list1 = [3,1,6,7,4]
list2 = [True, 1.2, 5, 'abc']
print(list1)
print(list2)
tuple1 = (3,2,1,4,6)
tuple2 = (2,3,1,4,6)
print(tuple1)
print(tuple2)
set1 = {True, 1.2, 5, 'abc'}
print(set1)
set2 = {1, 1, 2, 2, 3, 3}
print(set2)
set3 = {'a','b','c','d','e'}
print(set3)
dict = {"Mon":"1",
"Tue":"2",
"Wed":"3"
}
print(dict)
dict1 = {
"Mon":"1",
"Tue":"2",
"Wed":"3"
}
print(dict1)
print(dict1["Mon"])
dict2 = {
"1": "Peter",
"2":"Marie",
"3":"Sarah",
"4":"Jackie"
}
print(dict2['1']) |
"""
try
except
"""
def f1():
print("f1()")
f2()
def f2():
print("f2()")
f3()
def f3():
print("f3()")
raise Exception
# main program
print("start")
try:
f1()
except Exception:
print("Waring: there is an exception!")
print("end")
print("continue to work")
|
from unittest import TestCase
from .. import app
class ValidNumberTest(TestCase):
ERROR_MSG = 'Invalid - `%s`'
def setUp(self):
self.solution = app.Solution()
### sample input from leetcode
def test_number(self):
test_str = '0'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_float_number(self):
test_str = ' 0.1'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_alphabet(self):
test_str = 'abc'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_number_with_alphabet(self):
test_str = '1 a'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_exponent(self):
test_str = '2e10'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_exponent2(self):
test_str = '2e10e'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong1(self):
test_str = 'e9'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong2(self):
test_str = '.1'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong3(self):
test_str = '3.'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong4(self):
test_str = '0e'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong5(self):
test_str = '46.e3'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong6(self):
test_str = '.e'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong7(self):
test_str = '.e1'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong8(self):
test_str = '0.e'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong9(self):
test_str = '6e6.5'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong10(self):
test_str = ' 005047e+6'
self.assertTrue(expr=self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
def test_wrong11(self):
test_str = '3.5e+3.5e+3.5'
self.assertTrue(expr=not self.solution.isNumber(test_str),
msg=ValidNumberTest.ERROR_MSG%(test_str))
|
#metatropi string se arithmo ascii
L=input("Insert a word: ")
def split(word):
return [char for char in word]
word = list(L)
num=""
for i in list(map(str, map(ord, list(L)))):
print(i, end="")
num+=i
int_num=int(num)
prime=bool(False)
if int_num > 1:
for i in range(2, int(int_num/2)):
if (int_num % i) == 0:
prime=bool(True)
break
if prime == True:
print(" ",int_num, "is not a prime number")
else:
print (" ",int_num, "is a prime number") |
# ex 1
emptylist = []
print(emptylist)
# ex 2
list1 = ["sport"]
print(list1)
# ex 3
list2 = ["sport", "books", "robots"]
print(list2)
# ex 4
list2.append("computers")
print(list2)
# ex 5
new_items = input("enter a hobby: ")
list2.append(new_items)
print(list2)
# ex6
print(*list2)
# ex 7
print(*list2, sep = ", ")
# ex 8
print(*list2, sep = "|")
# ex 9
print(list2[0])
print(list2[-1])
print(list2[-2])
# ex 10
print(list2[0].upper())
print(list2[-1].upper())
print(list2[-2].upper())
# ex 11
list2.pop(0)
list2.append("Spider Man")
print(list2)
# ex 12
list2.pop(-1)
list2.append("Dragon Ball")
print(list2)
# ex 13
i = int(input("Enter the index: "))
list2.pop(i)
list2.append(input("enter something: "))
print(list2)
# ex 14
list2.pop(2)
print(list2)
# ex 15
for i in list2:
if i == "LOL":
list2.remove(i)
print(list2)
if "LOL" not in list2:
print("Check the items in the list again")
# ex 16
i = int(input("Enter the index of the item you want to delete: "))
list2.pop(i)
print(list2)
# ex 17
i = input("Enter the item you want to delete: ")
list2.remove(i)
print(list2)
# ex 18
for i in ["sleep", "eat", "code"]:
list2.append(i)
for item in list2:
print(item)
# ex 19
for item in list2:
print(item.upper())
# ex 20
for i, item in enumerate(list2):
print(i+1, ".", item.upper())
# ex 21
for item in list2:
if "e" in list(item) or "E" in list(item):
print(item.upper()) |
#Store five names and their favorite numbers in a dictionary
favorite_numbers = {'eric':55, 'tony':93, 'sarah':23, 'melissa':85, 'matt':32,}
#Inserts the key and value using the format function
print(f"Eric's favorite number is {favorite_numbers['eric']}.")
#Creates a variable for the key and value then prints
num = favorite_numbers['tony']
print("Tony's favorite number is " + str(num) + '.')
#Use a for loop to print the key and value for the dictionary
for key, value in favorite_numbers.items():
print(f"\nName: {key.title()}")
print(f"Number: {value}") |
class User:
def __init__(self, first_name, last_name, hometown, age, status):
self.first_name = first_name.title()
self.last_name = last_name.title()
self.hometown = hometown.title()
self.age = age
self.status = status
self.login_attempts = 0
def increment_login_attempts(self):
self.login_attempts += 1
print(f"You have attempted to login {self.login_attempts} times.")
def describe_user(self):
print(f"My name is {self.first_name} {self.last_name} and I am from {self.hometown}. I am {str(self.age)} years old and I am {self.status}.")
def reset_login_attempts(self):
self.login_attempts = 0
print(f"Your login attempts have been reset.")
class Admin(User):
def __init__(self, first_name, last_name = 'none', hometown = 'none', age = 'none', status = 'none'):
super().__init__(first_name, last_name, hometown, age, status)
self.privileges = Privileges()
'''def show_privileges(self):
print("\nAs an Admin you are able to do the following: ")
for priv in self.privileges:
print("\t -" + priv)'''
#admin = Admin('Administrator')
#admin.privileges = ['Delete posts', 'Boot users', 'Kick all the ass']
#admin.describe_user()
#admin.show_privileges()
class Privileges:
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print("- " + privilege)
else:
print("- This user has no privileges.")
admin = Admin('Administrator')
admin.describe_user()
admin.privileges.show_privileges()
print("\nAdding privileges...")
eric_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
admin.privileges.privileges = eric_privileges
admin.privileges.show_privileges() |
#Create a FOR loop that lists out the different types of pizza in the list.
pizzas = ['supreme', 'hawaiian', 'meat lovers']
for pizza in pizzas:
print(f"Give me a {pizza.title()} pizza and I will be happy.")
print("Pizza is the best!") |
def sandwich_order(bread, meat, *toppings):
print(f"We will make a {meat} sandwich on {bread} bread with the following toppings: ")
for topping in toppings:
print(f"- {topping}")
sandwich_order('white', 'turkey', 'lettuce','pickle','mayo') |
#Prints the name in the variable using all three case types on a separate line.
name = "kevin debruyne"
print(f"{name.title()} \n{name.upper()} \n{name.lower()}") |
#Create three dictionaries of people's info then store the dicitonaries in a list
people = []
person = {
'first': 'isabella',
'last': 'fouquier',
'age': 15,
'city': 'white oak',
}
people.append(person)
person = {
'first': 'matthew',
'last': 'fouquier',
'age': 41,
'city': 'tampa',
}
people.append(person)
person = {
'first': 'amanda',
'last': 'braun',
'age': 39,
'city': 'tampa'
}
people.append(person)
for person in people:
name = person['first'].title() + " " + person['last'].title()
age = str(person['age'])
city = person['city'].title()
print(name + " is " + age + " years old and lives in " + city + ".") |
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 切片操作左闭右开
result = arr[7:10] # 取出7~10位 ['8', '9', '10']
result = arr[-3:-1] # 取出倒数第三位到倒数第1位 ['8', '9']
result = arr[-3:] # 如果想包含到最后一位,直接省略后面一个就行,最前面同理。['8', '9', '10']
result = arr[:] # 两边都省略就是包含全部的list内容
# 控制切片步长
result = arr[1:6:2] # 1~6位每两位取出一个['2', '4', '6']
result = arr[::4] # list所有内容中每4位取出一个 [1, 5, 9]
print(result)
|
# 字典是另一种可变容器模型,且可存储任意类型对象。
# 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 ,
# 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
# d = {key1 : value1, key2 : value2 }
dict = {'a': 1, 'b': 2, 'c': '3'}
print(dict)
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
# 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
|
# 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
def sumEvenGrandparent(self, root):
nodes = [root]
total = 0
while nodes:
currentNode = nodes.pop()
if hasattr(currentNode, 'parent') and hasattr(currentNode.parent, 'parent'):
if currentNode.parent.parent.val % 2 == 0:
total += currentNode.val
if currentNode.right:
currentNode.right.parent = currentNode
nodes.append(currentNode.right)
if currentNode.left:
currentNode.left.parent = currentNode
nodes.append(currentNode.left)
return total
# Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)
# If there are no nodes with an even-valued grandparent, return 0.
# Example 1:
# Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
# Output: 18
# Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
# Constraints:
# The number of nodes in the tree is between 1 and 10^4.
# The value of nodes is between 1 and 100.
|
def isValid(s):
stack = []
d = {'(': ')', '[': ']', '{': '}'}
for ch in s:
if ch in d.keys():
stack.append(ch)
elif len(stack) > 0 and ch == d[stack.pop()]:
continue
else:
return False
if len(stack) > 0:
return False
else:
return True
print(isValid("(("))
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
# An input string is valid if:
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
# Example 1:
# Input: s = "()"
# Output: true
# Example 2:
# Input: s = "()[]{}"
# Output: true
# Example 3:
# Input: s = "(]"
# Output: false
# Example 4:
# Input: s = "([)]"
# Output: false
# Example 5:
# Input: s = "{[]}"
# Output: true
|
def isPowerOfThree(n):
if n == 0:
return False
while n % 3 == 0:
n = n / 3
if n == 1:
return True
else:
return False
print(isPowerOfThree(1)) |
def kidsWithCandies(candies, extraCandies):
return [True if person + extraCandies >= max(candies) else False for person in candies]
print(kidsWithCandies([4,2,1,1,2], 1))
|
def longestCommonPrefix(strs):
if not strs:
return ""
shortest_word = min(strs,key=len)
for i, ch in enumerate(shortest_word):
for other in strs:
if other[i] != ch:
return shortest_word[:i]
return shortest_word
print(longestCommonPrefix(["flower","flow","flight"]))
|
# list 清單
a = ['Toyota', 'Honda'] # 空清單
print(a)
# index(索引) (車廂代號, 從0開始)
print(a[0])
print(a[1])
# .append() 加東西進清單
a.append('Audi')
print(a)
# len() 取長度 length
print(len(a))
# in + 清單, 檢查東西有沒有在裡面
print('Audi' in a) # 是非題 True, False
print('Benz' in a)
|
def isPrime(n):
if (n <= 1):
return False
max_divisor = n
cur_divisor = 2
while (cur_divisor <= max_divisor):
# print("cur_divisor: {0}, max_divisor: {1}".format(cur_divisor, max_divisor))
if (cur_divisor == max_divisor):
return True
elif (0 == n % cur_divisor):
# print("{0} is divisible by {1}".format(n, cur_divisor))
return False
else:
max_divisor = n // cur_divisor
cur_divisor = cur_divisor + 1
return True
def getLeastPrimeDivisor(n, primes):
if (n in primes):
return n
for prime in primes:
if (0 == n % prime):
return prime
return n
primes = set()
for x in range(1, 10000):
if (isPrime(x)):
primes.add(x)
n = 1234567890
divisors = list()
while (n not in primes):
leastPrimeDivisor = getLeastPrimeDivisor(n, sorted(primes))
divisors.append(leastPrimeDivisor)
n = n // leastPrimeDivisor
divisors.append(n)
print(divisors) |
def close_enough(old, new):
return abs(old - new) < 0.001
def fixed_point(f, start):
# 这个方法来计算不动点:
# 思路就是不断把得数带入自变量里
# 前提条件是 这个过程 是收敛的
def iter(old, new):
if close_enough(old, new):
return new
else:
return iter(new, f(new))
return iter(start, f(start))
def sqrt(x):
# 这个 f 求不动点过程就是收敛的
# def f(y):
# return (y + x / y) / 2
# return fixed_point(f, 1)
# 下面这个写法与上3行等价, 但更简洁
return fixed_point(lambda y: (y + x / y) / 2, 1)
def average_damp(f):
# 于是用 平均阻尼函数来确保 它 收敛
return lambda x: (f(x) + x) / 2
def sqrt1(x):
# 但是有一些函数 求不动点时 不收敛
return fixed_point(average_damp(lambda y: x / y), 1)
def main():
print(sqrt(121))
print(sqrt1(121))
if __name__ == '__main__':
main() |
'''
This program reads through the email and finds all the lines
that contain From: and To: .
We will count the following:
usernames in the From: field
hosts in the From: field
usernames in the To: field
hosts in the To: field
We will print the different objects in csv format
'''
# To access STDOUT
import sys
#To access .writerows()
import csv
#Creating file handle to read file
fhand = open('mbox-short.txt')
# connect a csv.writer filehandle to STDOUT
cw = csv.writer(sys.stdout)
#Empty list to store information
fromto = []
fromAdd=[]
toAdd=[]
frUsers=[]
frHosts=[]
toUsers=[]
toHosts=[]
#Read through each line in the file, Strip white space
for line in fhand:
line= line.rstrip()
#If the line starts with From: then append the line to a list and split by the whitespace
#Append the second character to a new list
if line.startswith('From:'):
fromto.append(line)
frWords = line.split()
fromAdd.append(frWords[1])
#If the line starts with To: then append the line to a list and split by the whitespace
#Append the second character to a new list
elif line.startswith('To:'):
fromto.append(line)
toWords = line.split()
toAdd.append(toWords[1])
#go through each item in the list and split at the @ and append each item to a new list
for frItem in fromAdd:
obj = frItem.rstrip()
for x,y in [frItem.split('@')]:
frUsers.append(x)
frHosts.append(y)
#go through each item in the list and split at the @ and append each item to a new list
for toItem in toAdd:
obj = toItem.rstrip()
for a,b in [toItem.split('@')]:
toUsers.append(a)
toHosts.append(b)
#Create a dictionary
#Iterate throught the list and count each occurance and add the item and the occurance to the dictionary
fromUsers=dict()
for i in frUsers:
fromUsers[i]=fromUsers.get(i,0)+1
#Print the header and use .writerows to display the information
print('--- FROM USER ---')
cw.writerows(sorted(fromUsers.items()))
#Create a dictionary
#Iterate throught the list and count each occurance and add the item and the occurance to the dictionary
fromHosts=dict()
for i in frHosts:
fromHosts[i]=fromHosts.get(i,0)+1
#Print the header and use .writerows to display the information
print('--- FROM HOST ---')
cw.writerows(sorted(fromHosts.items()))
#Create a dictionary
#Iterate throught the list and count each occurance and add the item and the occurance to the dictionary
tooUsers=dict()
for i in toUsers:
tooUsers[i]=tooUsers.get(i,0)+1
#Print the header and use .writerows to display the information
print('--- TO USER ---')
cw.writerows(sorted(tooUsers.items()))
#Create a dictionary
#Iterate throught the list and count each occurance and add the item and the occurance to the dictionary
tooHosts=dict()
for i in toHosts:
tooHosts[i]=tooHosts.get(i,0)+1
#Print the header and use .writerows to display the information
print('--- TO HOST ---')
cw.writerows(sorted(tooHosts.items()))
# print(toAdd)
|
board = [
[0,0,0,0,0,0,8,1,7],
[0,2,0,9,0,0,0,3,0],
[8,0,0,7,0,0,9,0,0],
[5,0,0,0,8,0,0,0,0],
[0,0,3,1,0,2,5,0,0],
[0,0,0,0,4,0,0,0,6],
[0,0,8,0,0,5,0,0,4],
[0,7,0,0,0,4,0,6,0],
[2,9,4,0,0,0,0,0,0]
]
def show_board(board):
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print('-----------------------------')
for j in range(len(board[0])):
if j % 3 == 0 and j != 0:
print('| ',end='')
print(board[i][j],' ',end='')
if j == 8:
print('')
# find a empty place
def find_empty(board):
done = False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
done = True
return (i,j)
return ()
"""
find a number that can be fit there by checking for first number from 0 to 1
a number is fit at that particular position if it is not present in that column or on its box or in it's row
"""
assigned_numbers = []
def valid_number(board,empty_row,empty_col,start_from=1):
done = False
if not done:
for i in range(start_from,10):
#checking in row
for j in board[empty_row]:
if j == i: #if in row break checking row loop and check for another value of i
break
else:
# i value not in row then checking in column
for k in range(len(board)):
c = board[k][empty_col]
if c == i: #if i value in column break checking column loop and check for another value of i
break
else:
# now value of i is not in column and also not in row
# now checking does i value exist in the 3 x 3 box of that element
"""
now i will devide board in 3 new-rows and 3 new-columns
and every new-row contain 3 rows
and every new-col contain 3 columns
hence,
new-row will start from 0 and end on 2
same for new-col
hence, formula for both is
new-row = row // 3
new-col = column //3
"""
new_row = empty_row // 3
new_col = empty_col // 3
#checking in row three times so that all the elements will be checked
for c in range(3):
in_box = False
#following loop check it for single row of that box
for r in range(3):
n = board[(new_row*3)+c][(new_col*3)+r]
if n == i:
in_box = True
break
if in_box:
break
if not in_box:
board[empty_row][empty_col] = i
assigned_numbers.append([empty_row , empty_col, i])
done = True
break
if i == 9 and board[empty_row][empty_col] == 0:
board[empty_row][empty_col] = '#'
# main loop to execute this functions multiple times
while True:
try:
empty_row , empty_col = find_empty(board)
valid_number(board, empty_row, empty_col)
except:
break
show_board(board)
print("Assigned Numbers = ",assigned_numbers) |
# Student: Frank O'Connor
# E-80 Assignment 3
# Email: fjo.con@gmail.com
import csv, sys, os.path, bisect
assign_count = {}
availibility = {}
fail_reason = ""
def main(argv):
# Example Usage: 'python .\assign_times.py shifts.txt'
if len(sys.argv) < 2 or len(sys.argv) > 2:
sys.exit('Usage: %s shifts_filename' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Text file \"%s\" was not found!' % sys.argv[1])
shifts_filename = sys.argv[1]
ifile = open(shifts_filename, "rb")
# X set of variables, here they are hour shifts {0_1,0,_2,1_1,1_2,2_1,2_2,3_1,3_2}
# note: 2 timeslots per shift
# D set of domains, here they domains for the shifts will be students
# C set of constraints, constraints are:
# 2 students for every timeslot
# students must do 2 shifts
#availibility = {}
assignment = {}
domains = {}
for line in ifile:
# remove trailing whitespace, \r, \n etc
line = line.rstrip()
# assuming can split lines on whitespace, as question states to assume
# "hour identifiers and names are opaque strings that contain no whitespace"
split_words = line.split(" ")
#print split_words
student = split_words.pop(0)
availibility[student] = split_words
#print split_words
for word in split_words:
# we get all the timeslots, note every shift has 2 slots
assignment[word+"_1"] = None
assignment[word+"_2"] = None
# construct variable domains also
if word+"_1" in domains.keys():
domains[word+"_1"].append(student)
domains[word+"_2"].append(student)
else:
domains[word+"_1"] = [student]
domains[word+"_2"] = [student]
assign_count[student] = 0
assign_count[student] = 0
print assignment
print availibility
print "domains", domains
# dict representing assignment of shifts, initially, none assigned
# copy.copy(assignment) ??
back_tracking_search(assignment, availibility, domains, assign_count)
ifile.close()
def back_tracking_search(assignment, availibility, domains, assign_count):
print_assignment(assignment)
if is_complete_assignment(assignment, availibility):
# complete valid assignment
return assignment
next_var = select_unassigned_variable(assignment, availibility, domains)
ordered_domain_values = order_values(domains[next_var], assignment, assign_count)
for dom_val in ordered_domain_values:
print "in here", dom_val
assignment[next_var] = dom_val
assign_count[dom_val] = assign_count[dom_val] + 1
if is_consistent(assignment, availibility):
print "is consist -- in here"
result = back_tracking_search(assignment, availibility, domains, assign_count)
if result is not None:
return result
assignment[next_var] = None
assign_count[dom_val] = assign_count[dom_val] -1
return None
def is_consistent(assignment, availibility):
for timeslot, assigned_val in assignment.iteritems():
if assigned_val is not None:
# verify valid assigned matches availibility
if timeslot[:-2] not in availibility[assigned_val]:
print timeslot[:-2], assigned_val, " assignment not consistent"
return False
if timeslot.endswith("_1"):
# same student can't be assigned to 2 timeslots in the same shift
if assignment[timeslot[:-1]+"2"] is not None and assignment[timeslot] is not None:
if assignment[timeslot[:-1]+"2"] == assignment[timeslot]:
print "same shift"
return False
return True
def select_unassigned_variable(assignment, availibility, domains):
minimum_remaining_values = None
count = None
# applying minimum remaining values heuristic
for timeslot, possible_values in domains.iteritems():
print "timeslot" , timeslot , "possible_values" , possible_values
if assignment[timeslot] is None:
if count is None:
minimum_remaining_values = timeslot
count = len(possible_values)
elif len(possible_values) < count:
count = len(possible_values)
minimum_remaining_values = timeslot
print count
return minimum_remaining_values
def order_values(values, domains, assign_count):
ordered_values = values
# initial sort on number of domain values available,
#(this deals with tiebreaker on sort for on assigned values)
#ordered_values = sorted(ordered_values, key=sort_by_availibility, reverse=True)
## !!!!!!!!!! First search may not be necessary !!!!!!!!!!!
print "ordered_values_availibility", ordered_values
# order by least constraining value,
# i.e. the student with least assigned slots
ordered_values = sorted(ordered_values, key=sort_by_assign_count)
print "ordered_values", ordered_values
return ordered_values
def sort_by_assign_count(s):
print "assign_count", assign_count
return assign_count[s]
def sort_by_availibility(s):
print "len(availibility)", len(availibility[s])
return len(availibility[s])
def is_complete_assignment(assignment, availibility):
for timeslot, assigned_val in assignment.iteritems():
if assigned_val is None:
# All slots not assigned yet
print "not all assigned"
return False
else:
# verify valid assigned matches availibility
if timeslot[:-2] not in availibility[assigned_val]:
print timeslot[:-2], assigned_val, " assignment not valid"
return False
if timeslot.endswith("_1"):
print timeslot
# same student can't be assigned to 2 timeslots in the same shift
if assignment[timeslot[:-1]+"2"] == assignment[timeslot]:
print "same shift"
return False
# Also each student must have more than 2 ??
print_assignment(assignment)
return True
def print_assignment(assignment):
for timeslot, assigned_val in sorted(assignment.iteritems()):
if timeslot.endswith("_1"):
firstPerson = assigned_val
secondPerson = assignment[timeslot[:-1]+"2"]
if firstPerson is None:
firstPerson = "Nobody"
if secondPerson is None:
secondPerson = "Nobody"
print "Hour "+ timeslot[:-2] + ": "+ firstPerson + " " + secondPerson
# --------- main ---------
if __name__ == '__main__':
main(sys.argv)
|
#! import usr/bin/python3
# Dictionary.py : Simple program to find the meaning of given word
import requests
from bs4 import BeautifulSoup
print("Word:")
w = str(input())
print("please wait..... while we get u ur meaning")
res = requests.get("http://www.dictionary.com/browse/" + w)
soup = BeautifulSoup(res.content,"lxml")
print(soup.find_all("div",{"class":"def-content"})[0].text)
|
#calender of the year which is entered
import calendar
y = int(input("Enter Any year"))
m = 1
print("\n**********CALENDAR********")
cal=calendar.TextCalendar(calendar.SUNDAY)
i=1
while i <=12:
cal.prmonth(y,i)
i+=1
|
input_string = input("Enter Tasks separated by coma ")
task_list = input_string.split(",")
print("Printing all Task For Today")
for task in task_list:
for i, task in enumerate(task_list,1):
print(i, '. ' + task, sep='',end='i')
|
'''
APS-2020
Problem Description, Input, Output : https://codeforces.com/contest/1367/problem/A
Code by : Sagar Kulkarni
'''
for _ in range(int(input())):
str1=input();
list1=list(str1)
if len(list1)==2:
print(str1)
else:
list2=[]
for i in range(1,len(list1)-2,2):
list2.append(list1[i])
print(list1[0]+"".join(list2)+list1[-1])
|
'''
APS-2020
Problem Description, Input, Output : https://www.codechef.com/problems/SPLITIT
Code by : Sagar Kulkarni
'''
for _ in range(int(input())):
n=int(input())
list1=list(input())
if list1[-1] in list1[:n-1]:
print("YES")
else:
print("NO")
|
'''
APS-2020
Problem Description : Remove punctuations from a string
Input : string
Output : string (without punctuations)
Code by : Sagar Kulkarni
'''
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
print("Enter a String")
my_str=input()
no_punct=""
for char in my_str:
if char not in punctuations:
no_punct=no_punct + char
print(no_punct)
|
'''
APS-2020
Problem Description, Input, Output : https://codeforces.com/contest/71/problem/A
Code by : Sagar Kulkarni
'''
for _ in range(int(input())):
str1=input()
if len(str1)>10:
newStr=str1[0:1]+str((len(str1)-2))+str1[-1]
print(newStr)
else:
print(str1)
|
'''
APS-2020
Problem Description, Input, Output : https://codeforces.com/contest/1301/problem/A
Code by : Sagar Kulkarni
'''
T=int(input())
for _ in range(0,T):
a=input()
b=input()
c=input()
list1=list(a)
list2=list(b)
list3=list(c)
for i in range(0,len(list3)):
if list3[i]==list2[i]:
temp=list1[i]
list1[i]=list3[i]
list3[i]=temp
else:
temp=list2[i]
list2[i]=list3[i]
list3[i]=temp
if list1==list2:
print("YES")
else:
print("NO")
|
# -*- coding: utf-8 -*-
import math
import random
def average(data):
return sum(data) * 1.0 / len(data)
def variance(data):
avg = average(data)
var = map(lambda x: (x - avg)**2, data)
return average(var)
def standard_deviation(data):
return math.sqrt(variance(data))
def get_variance_range(n, m, amplt):
"""
Gets an approximation of the bounds for the variance of a data set
whose amplitude is amplt.
The algorithm generates n random values betwen 0 and amplt. Over
this n random values, calculates the variance. Then, it repeats this
process m times and finally, gets the minimun and maximum calculated
variance.
"""
deviations = []
for i in range(0, m):
data = []
for i in range(0, n):
val = random.randint(0, amplt)
data.append(val)
deviations.append(variance(data))
return min(deviations), max(deviations)
|
import unittest
from cooking import cook
class CookingTest(unittest.TestCase):
def test_single_input_unchanged(self):
number = 5
expected_output = (5, 5)
output = cook(number)
self.assertEqual(output, expected_output)
def test_two_digit_no_swap(self):
number = 22
expected_output = (22, 22)
output = cook(number)
self.assertEqual(output, expected_output)
def test_two_digit_swap_max(self):
number = 12
expected_output = (12, 21)
output = cook(number)
self.assertEqual(output, expected_output)
def test_two_digit_swap_min(self):
number = 31
expected_output = (13, 31)
output = cook(number)
self.assertEqual(output, expected_output)
def test_three_digit_swap_both(self):
number = 897
expected_output = (798, 987)
output = cook(number)
self.assertEqual(output, expected_output)
def test_five_digit_swap_both(self):
number = 31524
expected_output = (13524, 51324)
output = cook(number)
self.assertEqual(output, expected_output)
def test_three_digit_repeat(self):
number = 211
expected_output = (112, 211)
output = cook(number)
self.assertEqual(output, expected_output)
def test_three_digit_repeat_max(self):
number = 122
expected_output = (122, 221)
output = cook(number)
self.assertEqual(output, expected_output)
def test_three_digit_max_first_highest(self):
number = 918
expected_output = (198, 981)
output = cook(number)
self.assertEqual(output, expected_output)
def test_seven_digit_max_third_highest(self):
number = 9982369
expected_output = (2989369, 9992368)
output = cook(number)
self.assertEqual(output, expected_output)
def test_three_digit_min_first_position(self):
number = 132
expected_output = (123, 312)
output = cook(number)
self.assertEqual(output, expected_output)
def test_number_with_zero(self):
number = 101
expected_output = (101, 110)
output = cook(number)
self.assertEqual(output, expected_output)
def test_number_with_zeroes(self):
number = 1010
expected_output = (1001, 1100)
output = cook(number)
self.assertEqual(output, expected_output)
def test_number_with_more_zeroes(self):
number = 1000
expected_output = (1000, 1000)
output = cook(number)
self.assertEqual(output, expected_output)
if __name__ == '__main__':
unittest.main() |
#!/home/hmeng/anaconda3/bin/python
#list
print([1, 2] + [3, 4])
print([1]*5)
print(2 in [1, 2, 5])
l = [3, 5]
l.append(6)
print(l)
# tuple
t = (1, 'a', 2, 'b')
a, b, c, d = t
print(b)
#dictorary
dict = {'name':'Josh',
'age': 15,
'weight':'40kg'}
for key in dict.keys():
print(key)
for value in dict.values():
print(value)
for key, value in dict.items():
print(key, value)
# set
my_set = {1, 2, 3}
print(type(my_set))
my_set = set([1, 2, 3, 2])
print(my_set)
my_set.add(4)
my_set.update([4, 5, 6])
print(my_set)
#string
s2 = 'Python is a widely used high-level programming language for general-purpose programming.'
print(s2.split(' '))
#time
import datetime
import time
# from 1970/1/1
timestamp = time.time()
dt_now = datetime.datetime.fromtimestamp(timestamp)
print(dt_now)
print('{}年{}月{}日'.format(dt_now.year, dt_now.month, dt_now.day))
today = datetime.datetime.today().strftime('%y%m%d')
print(today)
#map
l1 = [1, 3, 5, 7, 9]
l2 = [2, 4, 6, 8, 10]
mins = map(min, l1, l2)
print(list(mins))
#lambda
l1 = [1, 3, 5, 7, 9]
l2 = [2, 4, 6, 8, 10]
result = map(lambda x, y: x * 2 + y, l1, l2)
print(list(result))
# list
l1 = [i for i in range(100) if i%2==0]
#csv
import csv
with open('./data/grades.csv') as csvfile:
grades_data = list(csv.DictReader(csvfile))
print(grades_data[0].keys())
sum_assign1 = sum(float(row['assignment1_grade']) for row in grades_data) / len(grades_data)
avg_assign1 = sum_assign1/len(grades_data)
print('assignment1平均分数:', avg_assign1)
# pack & unpack
l1 = list(range(1, 6))
l2 = list(range(6, 11))
zip_gen = zip(l1, l2)
x, y = zip(*zip_gen)
list(x)
|
from abc import ABCMeta, abstractmethod
class ABCMesh(object):
"""Abstract base class for mesh.
Attributes
----------
name : str
name of mesh
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_point(self, uid): # pragma: no cover
""" Returns a point with a given uid.
Returns the point stored in the mesh
identified by uid. If such point do not
exists an exception is raised.
Parameters
----------
uid : uuid.UUID
uid of the desired point.
Returns
-------
point : Point
Mesh point identified by uuid
Raises
------
KeyError :
If the point identified by uid was not found
TypeError :
When ``uid`` is not uuid.UUID
"""
@abstractmethod
def get_edge(self, uid): # pragma: no cover
""" Returns an edge with a given uid.
Returns the edge stored in the mesh
identified by uid. If such edge do not
exists an exception is raised.
Parameters
----------
uid : uuid.UUID
uid of the desired edge.
Returns
-------
edge : Edge
Edge identified by uid
Raises
------
KeyError :
If the edge identified by uid was not found
TypeError :
When ``uid`` is not uuid.UUID
"""
@abstractmethod
def get_face(self, uid): # pragma: no cover
""" Returns a face with a given uid.
Returns the face stored in the mesh
identified by uid. If such a face does
not exists an exception is raised.
Parameters
----------
uid : uuid.UUID
uid of the desired face.
Returns
-------
face : Face
Face identified by uid
Raises
------
KeyError :
If the face identified by uid was not found
TypeError :
When ``uid`` is not uuid.UUID
"""
@abstractmethod
def get_cell(self, uid): # pragma: no cover
""" Returns a cell with a given uid.
Returns the cell stored in the mesh
identified by uid. If such a cell does not
exists an exception is raised.
Parameters
----------
uid : uuid.UUID
uid of the desired cell.
Returns
-------
cell : Cell
Cell identified by uid
Raises
------
KeyError :
If the cell identified by uuid was not found
TypeError :
When ``uid`` is not uuid.UUID
"""
@abstractmethod
def add_points(self, points): # pragma: no cover
""" Adds a set of new points to the mesh.
Parameters
----------
points : iterable of Point
Points to be added to the mesh
Raises
------
ValueError :
If other point with a duplicated uid was already
in the mesh.
"""
@abstractmethod
def add_edges(self, edge):
""" Adds a set of new edges to the mesh.
Parameters
----------
edges : iterable of Edge
Edge to be added to the mesh
Raises
------
ValueError :
If other edge with a duplicated uid was already
in the mesh
"""
@abstractmethod
def add_faces(self, face): # pragma: no cover
""" Adds a set of new faces to the mesh.
Parameters
----------
faces : iterable of Face
Face to be added to the mesh
Raises
------
ValueError :
If other face with a duplicated uid was already
in the mesh
"""
@abstractmethod
def add_cells(self, cell): # pragma: no cover
""" Adds a set of new cells to the mesh.
Parameters
----------
cells : iterable of Cell
Cell to be added to the mesh
Raises
------
ValueError :
If other cell with a duplicated uid was already
in the mesh
"""
@abstractmethod
def update_points(self, point): # pragma: no cover
""" Updates the information of a set of points.
Gets the mesh point identified by the same
uid as the provided point and updates its information
with the one provided with the new point.
Parameters
----------
points : iterable of Point
Point to be updated
Raises
------
ValueError :
If the any point was not found in the mesh
"""
@abstractmethod
def update_edges(self, edge): # pragma: no cover
""" Updates the information of a set of edges.
Gets the mesh edge identified by the same
uid as the provided edge and updates its information
with the one provided with the new edge.
Parameters
----------
edges : iterable of Edge
Edge to be updated
Raises
------
ValueError :
If the any edge was not found in the mesh
"""
@abstractmethod
def update_faces(self, face): # pragma: no cover
""" Updates the information of a set of faces.
Gets the mesh face identified by the same
uid as the provided face and updates its information
with the one provided with the new face.
Parameters
----------
faces : iterable of Face
Face to be updated
Raises
------
ValueError :
If the any face was not found in the mesh
"""
@abstractmethod
def update_cells(self, cell): # pragma: no cover
""" Updates the information of a set of cells.
Gets the mesh cell identified by the same
uid as the provided cell and updates its information
with the one provided with the new cell.
Parameters
----------
cells : iterable of Cell
Cell to be updated
Raises
------
ValueError :
If the any cell was not found in the mesh
"""
@abstractmethod
def iter_points(self, uids=None): # pragma: no cover
""" Returns an iterator over points.
Parameters
----------
uids : iterable of uuid.UUID or None
When the uids are provided, then the points are returned in the
same order the uids are returned by the iterable. If uids is None,
then all points are returned by the iterable and there is no
restriction on the order that they are returned.
Yields
------
point : Point
"""
@abstractmethod
def iter_edges(self, uids=None): # pragma: no cover
""" Returns an iterator over edges.
Parameters
----------
uids : iterable of uuid.UUID or None
When the uids are provided, then the edges are returned in the same
order the uids are returned by the iterable. If uids is None, then
all edges are returned by the iterable and there is no restriction
on the order that they are returned.
Yields
------
edge : Edge
"""
@abstractmethod
def iter_faces(self, uids=None): # pragma: no cover
""" Returns an iterator over faces.
Parameters
----------
uids : iterable of uuid.UUID or None
When the uids are provided, then the faces are returned in the same
order the uids are returned by the iterable. If uids is None, then
all faces are returned by the iterable and there is no restriction
on the order that they are returned.
Yields
------
face : Face
"""
@abstractmethod
def iter_cells(self, uids=None): # pragma: no cover
""" Returns an iterator over cells.
Parameters
----------
uids : iterable of uuid.UUID or None
When the uids are provided, then the cells are returned in the same
order the uids are returned by the iterable. If uids is None, then
all cells are returned by the iterable and there is no restriction
on the order that they are returned.
Yields
------
cell : Cell
"""
@abstractmethod
def has_edges(self): # pragma: no cover
""" Check if the mesh has edges
Returns
-------
result : bool
True of there are edges inside the mesh,
False otherwise
"""
@abstractmethod
def has_faces(self): # pragma: no cover
""" Check if the mesh has faces
Returns
-------
result : bool
True of there are faces inside the mesh,
False otherwise
"""
@abstractmethod
def has_cells(self): # pragma: no cover
""" Check if the mesh has cells
Returns
-------
result : bool
True of there are cells inside the mesh,
False otherwise
"""
@abstractmethod
def count_of(self, item_type): # pragma: no cover
""" Return the count of item_type in the container.
Parameters
----------
item_type : CUDSItem
The CUDSItem enum of the type of the items to return the count of.
Returns
-------
count : int
The number of items of item_type in the container.
Raises
------
ValueError :
If the type of the item is not supported in the current
container.
"""
|
import linkedlist
def addList():
li = linkedlist.LinkedList()
li.add(0, 2)
li.add(1, 1)
li.add(2, 5)
li.add(3, 2)
li.add(4, 3)
li.add(5, 6)
li.add(6, 7)
return(li)
#1
def listPartition(LinkedList,k):
li = list()
node = LinkedList.head
while(node):
li.append(node.data)
node = node.next
li.sort()
return(li)
#2
def partition(Node,k):
before = linkedlist.LinkedList()
after = linkedlist.LinkedList()
idx1 = 0
idx2 = 0
while(Node):
if(Node.data<k):
before.add(idx1,Node.data)
idx1+=1
elif(Node.data>=k):
after.add(idx2,Node.data)
idx2+=1
Node = Node.next
head = after.head
idx = before.size
while(head):
before.add(idx,head.data)
idx += 1
head=head.next
return(before)
if __name__ == "__main__":
li = addList()
print(listPartition(li,3))
head = li.find(0)
node = partition(head,3)
node.printNode()
|
def main():
print("iterable_example")
iterable_example()
def iterable_example():
iterable = ['Spring', 'Summer', 'Autumn', 'Winter']
iterator = iter(iterable)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
try:
print(next(iterator))
except StopIteration:
print("No items left")
if __name__ == '__main__':
main() |
class WordDictionary:
class Node:
def __init__(self):
self.is_word = False
self.next = [None for _ in range(26)]
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = WordDictionary.Node()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
size = len(word)
cur_node = self.root
for i in range(size):
alpha = word[i]
next = cur_node.next[ord(alpha) - ord('a')]
if next is None:
cur_node.next[ord(alpha) - ord('a')] = WordDictionary.Node()
cur_node = cur_node.next[ord(alpha) - ord('a')]
if not cur_node.is_word:
cur_node.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return self.__match(word, self.root, 0)
def __match(self, word, node, start):
if start == len(word):
return node.is_word
alpha = word[start]
# 关键在这里,如果当前字母是 "." ,每一个分支都要走一遍
if alpha == '.':
# print(node.next)
for i in range(26):
if node.next[i] and self.__match(word, node.next[i], start + 1):
return True
return False
else:
if not node.next[ord(alpha)-ord('a')]:
return False
return self.__match(word, node.next[ord(alpha) - ord('a')], start + 1)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
if __name__ == '__main__':
wd = WordDictionary()
wd.addWord("bad")
wd.addWord("dad")
wd.addWord("mad")
# search("pad") -> false
# search("bad") -> true
# search(".ad") -> true
# search("b..") -> true
#
res1 = wd.search("pad")
res2 = wd.search("bad")
res3 = wd.search(".ad")
res4 = wd.search("b..")
print(res1)
print(res2)
print(res3)
print(res4)
|
class WordDictionary:
class Node:
def __init__(self):
self.is_word = False
self.next = dict()
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = WordDictionary.Node()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
cur_node = self.root
for alpha in word:
if alpha not in cur_node.next:
cur_node.next[alpha] = WordDictionary.Node()
cur_node = cur_node.next[alpha]
if not cur_node.is_word:
cur_node.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return self.__match(word, self.root, 0)
def __match(self, word, node, start):
if start == len(word):
return node.is_word
alpha = word[start]
# 关键在这里,如果当前字母是 "." ,每一个分支都要走一遍
if alpha == '.':
for next in node.next:
if self.__match(word, node.next[next], start + 1):
return True
return False
else:
if not alpha in node.next:
return False
return self.__match(word, node.next[alpha], start + 1)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
|
"""
This program is used to scrape NBA data and separate into a different
file for each year between 1989 and 2019 for all NBA players (31 years).
The website used is https://www.basketball-reference.com
"""
# Imports
from bs4 import BeautifulSoup
import requests
import csv
# This part creates a dictionary of URLs
baseURL_left = "https://www.basketball-reference.com/leagues/NBA_"
baseURL_right = "_advanced.html"
URL = {}
for year in range(1989, 2020):
URL[year] = baseURL_left + str(year) + baseURL_right
# This part scrapes data from the NBA database and creates a table for all stats
for year in URL:
print("Getting stats from " + str(year))
source = requests.get(URL[year]).text
soup = BeautifulSoup(source, 'lxml')
player_table = soup.find('table', {'class': 'sortable stats_table'})
full_table = player_table.find('tbody').findAll('tr', {'class': 'full_table'})
total_table = []
for table in full_table:
player_name = table.find('td', {'data-stat': "player"}).get_text()
stats = table.findAll('td', {'class': 'right'})
team = table.find('td', {'data-stat': "team_id"}).get_text()
temp = [player_name, team]
# Cleaning up empty columns and adding data to overall table
column = 0
for stat in stats:
column += 1
if column == 16 or column == 21:
continue
playerstats = stat.get_text()
if not playerstats:
playerstats = "0"
temp.append(playerstats)
else:
temp.append(playerstats)
total_table.append(temp)
# Exporting data to csv file
filename = "AvgPlayerStats" + str(year) + ".csv"
with open(filename, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(total_table)
print("Done")
print("All tasks complete") |
# 辅助函数
def select_count(cursor, table):
sql = "select count(*) from {}".format(table)
cursor.execute(sql)
rows = cursor.fetchall()
return rows[0][0]
def insert_person(cursor, id, name):
sql = "insert into person values('{}', '{}')".format(id, name)
cursor.execute(sql)
return cursor.rowcount
def insert_teacher(cursor, id, birthday, rank):
sql = "insert into teacher values('{}', '{}', '{}')".format(
id, birthday, rank)
cursor.execute(sql)
return cursor.rowcount
def insert_student(cursor, id, enrolmentdt, stuclass):
sql = "insert into student values('{}', '{}', '{}')".format(
id, enrolmentdt, stuclass)
cursor.execute(sql)
return cursor.rowcount
def insert_others(cursor, id, work):
sql = "insert into others values('{}', '{}')".format(
id, work)
cursor.execute(sql)
return cursor.rowcount
def insert_dormitory(cursor, dno, dadmin, dtel, dfloor):
sql = "insert into domitory values('{}', '{}', '{}', '{}')".format(
dno, dadmin, dtel, dfloor)
cursor.execute(sql)
return cursor.rowcount
def insert_card(cursor, id, cdno='null', remainingsum=0, carddate='now()', passwd='000000', valid=1):
sql = "insert into card values('{}', '{}', '{}', '{}', {}, '{}')".format(
id, remainingsum, carddate, passwd, cdno, valid)
cursor.execute(sql)
return cursor.rowcount
def insert_canteen(cursor, wno, wname, wadmin, wtel):
sql = "insert into canteen values('{}', '{}', '{}', '{}')".format(
wno, wname, wadmin, wtel)
cursor.execute(sql)
return cursor.rowcount
def insert_gate(cursor, gno, gname, gadmin, gtel):
sql = "insert into gate values('{}', '{}', '{}', '{}')".format(
gno, gname, gadmin, gtel)
cursor.execute(sql)
return cursor.rowcount
def insert_consume(cursor, wno, ID, cuisineid, amount):
count1 = select_count(cursor, 'consume')
sql = "call eat('{}', '{}', '{}', '{}')".format(
ID, wno, cuisineid, amount)
cursor.execute(sql)
count2 = select_count(cursor, 'consume')
return (count2 - count1)
def insert_record(cursor, ID, gno, inout):
count1 = select_count(cursor, 'record')
sql = "call in_and_out('{}', '{}', '{}')".format(
ID, gno, inout)
cursor.execute(sql)
count2 = select_count(cursor, 'record')
return (count2 - count1)
def insert_access(cursor, ID, dno):
count1 = select_count(cursor, 'access')
sql = "call back('{}', '{}')".format(
ID, dno)
cursor.execute(sql)
count2 = select_count(cursor, 'access')
return (count2 - count1)
|
"""
Check 2 binary trees for equality
- same sructure
- same values at each node
n1
/ \
n2 n3
/ \ \
n4 n5 n6
n1
/ \
n2 n3
/
n4
n1
/ \
n2 n3
\
n4
"""
import collections
class Node:
left = None
right = None
val = None
def make_tree(drop_last=False):
n1 = Node()
n2 = Node()
n3 = Node()
n4 = Node()
n5 = Node()
n6 = Node()
n1.left = n2
n1.right = n3
n1.val = 1
n2.left = n4
n2.right = n5
n2.val = 2
if not drop_last:
n3.left = n6
# else:
# n3.right = n6
n3.val = 3
n4.val = 4
n5.val = 5
n6.val = 6
return n1
def make_tree2(drop_last=False):
n1 = Node()
n2 = Node()
n3 = Node()
n4 = Node()
n1.left = n2
n1.right = n3
n1.val = 1
if drop_last:
n2.right = n4
else:
n2.left = n4
n2.val = 2
n3.val = 3
n4.val = 4
return n1
def bfs_tree(root):
queue = collections.deque([root.left, root.right])
print root.val
while len(queue):
n = queue.popleft()
if n.left:
queue.append(n.left)
if n.right:
queue.append(n.right)
print n.val
def dfs_tree(root):
stack = [root.right, root.left]
print root.val
while len(stack):
n = stack.pop()
if n.right:
stack.append(n.right)
if n.left:
stack.append(n.left)
print n.val
def bfs_compare_tree(tree1, tree2):
queue1 = collections.deque([tree1.left, tree1.right])
queue2 = collections.deque([tree2.left, tree2.right])
if tree1.val != tree2.val:
return False
while len(queue1) and len(queue2):
n1 = queue1.popleft()
n2 = queue2.popleft()
if n1 != n2:
return False
if not n1 and not n2:
break
if n1 and n2 and n1.val != n2.val:
return False
queue1.append(n1.left)
queue2.append(n2.left)
queue1.append(n1.right)
queue2.append(n2.right)
return True
def recursive_compare(tree1, tree2):
if not tree1 or not tree2:
return tree1 == tree2
if tree1.val != tree2.val:
return False
return (recursive_compare(tree1.left, tree2.left) and
recursive_compare(tree1.right, tree2.right))
if __name__ == "__main__":
tree1 = make_tree2()
print "BFS Tree1"
bfs_tree(tree1)
print "DFS Tree1"
dfs_tree(tree1)
tree2 = make_tree2(True)
print "BFS Tree2"
bfs_tree(tree2)
print "DFS Tree2"
dfs_tree(tree2)
print "BFS tree compare not equal...ok"
assert(bfs_compare_tree(tree1, tree2) is False)
print "BFS tree compare equal...ok"
assert(bfs_compare_tree(tree1, tree1))
print "Recursive tree compare not equal...ok"
assert(recursive_compare(tree1, tree2) is False)
print "Recursive tree compare equal...ok"
assert(recursive_compare(tree1, tree1))
|
## The Pythonic Way!
import random
names = [ 'Raffaello', 'Donatello', 'Michelangelo', 'Leonardo']
instruments = [ 'daggers', 'no-idea1', 'No-idea2', 'pole']
'''
for name in names:
print name
print
for i,name in enumerate(names, 10):
print i, name
print
for name in reversed(names):
print name
for name, instrument in zip(names, instruments):
print name, instrument
print
for size in map(len, names):
print size
'''
def mymap(function, iterable):
result = []
for element in iterable:
result.append(function(element))
return result
## How Itearation Works
class Iterable:
'an iterable can be for-looped'
def __init__(self,maximum=0):
self.maximum = maximum
def __getitem__(self,index):
if index >= self.maximum:
raise IndexError(index)
return index
class Iterator:
'kind-of like the basic iterator type'
def __init__(self, sequence):
self.sequence = sequence
self.current = 0
# Fixed in python 3 as __next__
def next(self):
try:
value = self.sequence[self.current]
except IndexError:
raise StopIteration
self.current += 1
return value
class Shuffled:
'custom iterator for looping in random order'
def __init__(self, sequence):
self.sequence = sequence
self.indeces = range(len(sequence))
random.shuffle(self.indeces)
def next(self):
try:
index = self.indeces.pop()
except IndexError:
raise StopIteration
return self.sequence[index]
# every iterator returns itself as an iterator
def __iter__(self):
return self |
import requests
import datetime
import time
import xlsxwriter
class Tweet: # Class to hold data related to tweets
def __init__(self, text=None, date=None):
self.text = text
self.d = date
class Day: # Class to track tweets on a certain date
def __init__(self, date):
self.d = date
self.tweets = []
def add_tweet(self, t):
self.tweets.append(t)
bear_file = open('bear.txt','r') # Gets Bearer token from file
TOKEN = bear_file.read()
bear_file.close()
def search_twitter(query, tweet_fields, start, end, depth, bearer_token=TOKEN):
'''
:param query: The query to search
:param tweet_fields: Data to collect for each result
:param start: Start time of search
:param end: End time of search
:param depth: Depth of search (max 100)
:param bearer_token: Token to access API
:return: json data of response
'''
headers = {"Authorization": "Bearer {}".format(bearer_token)} # Sets request header
url = "https://api.twitter.com/2/tweets/search/recent?query={}&{}&{}&{}&{}".format( # Generates API request
query, tweet_fields, start, end, depth
)
response = requests.request("GET", url, headers=headers) # Makes API request
if response.status_code != 200: # Checks if we got an error
raise Exception(response.status_code, response.text)
return response.json() # Returns API response
def get_minute(offset, s, e):
'''
:param offset: Number of minutes to offset by
:param s: Search start time
:param e: Search end time
:return: Array of text representing all tweets gathered for a specific minute
'''
query = "doge%20(%23doge)%20-is:verified" # Query to search
fields = "tweet.fields=text,created_at" # Fields of tweet to return
depth = "max_results=100" # Max results per query
start_date = (s - datetime.timedelta(hours=offset)).replace(microsecond=0).isoformat() # Sets start time
end_date = (e - datetime.timedelta(hours=offset)).replace(microsecond=0).isoformat() # Sets end time
start = "start_time=" + str(start_date) + "Z" # Configures param
end = "end_time=" + str(end_date) + "Z"
resp = search_twitter(query, fields, start, end, depth) # Sends search info to func
text = []
for r in resp['data']: # For all tweets
encoded = str(r['text']).encode("ascii", "ignore") # Remove non ascii chars
text.append(encoded.decode()) # Add to data set
return text
def get_hour(offset, s, e):
'''
:param offset: Number of hours to offset by
:param s: Search start hour
:param e: Search end hour
:return: Array of minutes, where each minute is an arrya of up to 100 tweets from that minute
'''
start_date = (s - datetime.timedelta(hours=offset)).replace(microsecond=0) # Sets start time
end_date = (e - datetime.timedelta(hours=offset)).replace(microsecond=0) # Sets end time
text = []
x = 0
while x < 60: # Loops through all minutes of hour
text.append(get_minute(x, start_date, end_date)) # Appends data to array
x += 1
time.sleep(5) # Sleeps to not stress out the API
return text # Returns hour worth of data
def get_day(offset):
'''
:param offset: Number of days to offset by
:return: Array of hours, where each hour is an array of minutes,
where each minute is up to 100 tweets from that minute
'''
start_date = (datetime.datetime.utcnow() - datetime.timedelta(days=offset, minutes=1)) # Increments start time
end_date = (datetime.datetime.utcnow() - datetime.timedelta(days=offset, minutes=2)) # Increments end time
x=0
text = []
while x < 24: # Loops through all hours of day
text.append(get_hour(x, start_date, end_date)) # Searches for an hour of data and appends to day array.
x += 1 # Increments hour index
return text # Returns data for day
x = 1 # Sets counter var
while x < 4: # Number of recent days to collect data for
workbook = xlsxwriter.Workbook(str((datetime.datetime.utcnow()
- datetime.timedelta(days=x)).replace(microsecond=0)
.isoformat())[0:10] + ".xlsx") # Opens excel workbook for day
sheet = workbook.add_worksheet() # Adds base sheet to workbook
# output_file = open(str((datetime.datetime.utcnow()
# - datetime.timedelta(days=x)).replace(microsecond=0)
# .isoformat())[0:10]+".txt", 'w+')
data = get_day(x) # Gets a day's worth of data
row = 0
col = 0
for hour in data: # Inserts data in sheet
for min in hour:
for t in min:
sheet.write(row, col, t)
row += 1
# output_file.write(t+'\n')
# output_file.close()
x += 1
workbook.close() # Closes workbook
|
"""
Ticket numbers usually consist of an even number of digits.
A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
Given a ticket number n, determine if it's lucky or not.
"""
def isLucky(n):
num=[int(i) for i in str(n)]
if len(num)%2!=0:
return False
l=int(len(num)/2)
if sum(num[:l])==sum(num[l:]):
return True
return False
|
"""
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network
that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses.
One of them is the IPv4 address.
Given a string, find out if it satisfies the IPv4 address naming rules.
"""
def isIPv4Address(inputString):
b=[i for i in inputString]
if '.' not in b:
return False
a=inputString.split('.')
print(a)
if len(a)!=4:
return False
if "" in a:
return False
for i in a:
if i.isnumeric()==False:
return False
if int(i)>255:
return False
if i[0]=='0' and len(i)>1:
return False
return True
|
"""
Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
"""
def reverseInParentheses(inputString):
s=''
e=''
c=0
r=inputString
l=True
while l==True:
for i,j in enumerate(r):
if j=='(':
s=i
c=1
o=[]
continue
if j==')':
c=0
e=i
a="("+"".join(o)+")"
o=o[::-1]
b="".join(o)
r=r.replace(a,b)
if c==1:
o.append(j)
if "(" in r and ")" in r:
l=True
else:
l=False
return r
|
"""
Given integers a and b, determine whether the following pseudocode results in an infinite loop
while a is not equal to b do
increase a by 1
decrease b by 1
Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever.
"""
def isInfiniteProcess(a, b):
if a>b:
return True
if a<b:
while a!=b:
if a>b:
return True
a+=1
b-=1
return False
def isInfiniteProcess(a, b):
return ((b-a)%2==1) or a>b
|
"""
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a and b, check whether they are similar.
"""
def areSimilar(a, b):
count = 0
A = []
B = []
for i in range(len(a)):
if (a[i]!= b[i]):
count +=1
A.append(a[i])
B.append(b[i])
if (count ==0):
return True
elif count ==2:
return set(A)==set(B)
else:
return False
|
"""
Given two cells on the standard chess board, determine whether they have the same color or not.
"""
def chessBoardCellColor(cell1, cell2):
if ord(cell1[0])%2==ord(cell2[0])%2:
if int(cell1[1])%2==int(cell2[1])%2:
return True
if ord(cell1[0])%2!=ord(cell2[0])%2:
if int(cell1[1])%2!=int(cell2[1])%2:
return True
return False
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 3 14:44:31 2017
@author: missyallan
Missy is practicing Python with NYU DataCamp GitBook
"""
a = "some"
b= "thing"
c = a + b
print('c =', c)
#%%
x = 2
y =3
z = x/y
print('z =', z)
4+5 # add 4 and 5
print(4+5)
#%%
f = "I don't believe it"
print(f)
longstring = """
Four score and seven years ago
Our fathers brought forth. """
print(longstring)
#%%
bad_string = "Sarah's code"
print(bad_string)
#%%
s = '12'
i = int(s)
type(i)
#%%
x = 'abc'
y = list(x)
print(y)
#%%
# convert integer i to list
i = 1234
istring = str(i)
print(istring)
#%%
#year is a string representing a year. how to construct a string for the FOLLOWING year
year = '2015'
intyear = int(year)
nextyear = intyear + 1
print(nextyear)
#%%
numberlist = [1, 5, -3]
numberlist.append(7)
print(numberlist)
#%%
#convert a string with a comma to a float
z = '12,234.5'
replaced = z.replace(',',' ')
print(replaced)
nospace = replaced.replace(' ', '')
print(nospace)
b = 0.0
finalfloat = float(nospace) + b
print(finalfloat)
print(type(finalfloat))
#%%
|
def InsertSort(Array):
for i in range(1,len(Array)):
temp = Array[i]
Index = i
while Index > 0 and Array[Index - 1] > temp :
Array[Index] = Array[Index - 1]
Index = Index - 1
Array[Index] = temp
def QuickSort(Array):
if len(Array) <= 1 :
return Array
else:
Pivot = Array[0]
less_A = []
Upper_A = []
for i in range(1,len(Array)):
if Array[i] < Pivot :
less_A.append((Array[i]))
else:
Upper_A.append(Array[i])
less_A = QuickSort(less_A)
less_A.append(Pivot)
Upper_A = QuickSort(Upper_A)
return less_A + Upper_A
print("Prueba InsertSort")
arreglo = input().split(",")
for i in range(len(arreglo)):
arreglo[i] = int(arreglo[i])
arreglo = QuickSort(arreglo)
print(arreglo) |
# Person class
# Creates a Person object that Fellow and Staff classes inherit from
class Person(object):
"""Creates a Person object that Fellow and Staff class inherit from"""
def __init__(self, name):
self.name = name
def __repr__(self):
return "<Person %s>" % self.name |
#Vous pouvez suprimer ce code c'est juste pour le test
def main():
print("Hello World!")
print("Langage disponibles :\n\t-Java (J) \n\t-Python3 (PY3)")
Langages = ["PY3", "J"]
LangageInitial = input("Quel est le langage du programe Initial:")
if LangageInitial.upper() not in Langages:
print("Langage non disponible")
exit()
LangageFinal = input("Quel est le langage du programe Final :")
if LangageInitial.upper() not in Langages:
print("Langage non disponible")
exit()
if LangageInitial.upper() == LangageFinal.upper():
print("Traduction en cours...")
print("Ah non, pas besoin de traduction, c'est le même langage!")
if LangageInitial.upper() == "J" and LangageFinal.upper() == "PY3":
JavaToPython3()
if LangageInitial.upper() == "PY3" and LangageFinal.upper() == "J":
Python3ToJava()
def JavaToPython3():
print("Java vers Python3")
def Python3ToJava():
print("Python3 vers Java")
if __name__ == "__main__":
main()
|
def print_evens(start):
''' function: counts by two from a starting number to 100 inclusive
parameters: starting number
returns: printed counting by twos from start to 100'''
start = 0
while start < 99:
start += 2
print(start)
def main():
count_from = 0
print_evens(count_from)
main()
|
##def main():
##
## for i in range(-1,-101,-1):
## print(i)
##
##
##main()
##def main():
## data = ["hello", 9002, 8, 3.0, 5]
##
## for i in range(len(data)):
## print(data[i])
## i +=1
##
##main()
def spread_strings(list_of_strings):
i = 0
spaced_word = " "
while i < len(list_of_strings):
spaced_word += list_of_strings[i] + " "
return spaced_word
i += 1
def main():
list_of_strings = ["Ahh", "This", "WAS", "Difficult"]
print(spread_strings(list_of_strings))
main()
|
def convert_tuple(user_tuple):
'''function: takes tuple input and returns a list that contains same elements and order
parameters: one tuple
return: list with same elements and order as tuple'''
new_list = []
i = 0
while i < len(user_tuple):
new_list.append(user_tuple[i])
i += 1
return new_list
def main():
user_tuple = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
tuple_as_list = convert_tuple(user_tuple)
print(tuple_as_list)
print(type(tuple_as_list))
main()
|
def spread_strings(word):
index = 0
spaced_word = ""
while (index < len(word)):
spaced_word += word[index] + " "
index += 1
return spaced_word
def main():
word_list= ["Hello", "howdy", "Hiya"]
word_one_list = word_list[0]
word_two_list = word_list[1]
word_three_list = word_list[2]
print(spread_strings(word_one_list))
print(spread_strings(word_two_list))
print(spread_strings(word_three_list))
main()
|
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import sklearn.metrics as sm
'''scikit-learn, an estimator for classification is a Python object that implements the methods fit(X, y) and predict(T)'''
'''scikit-learn comes with a few standard datasets, for instance the iris and digits datasets for classification and the boston house prices dataset for regression.'''
list1 = [0, 1, 2] #?
def rename(s): #to alter mixed vlues
list2 = []
for i in s:
if i not in list2:
list2.append(i)
for i in range(len(s)):
pos = list2.index(s[i])
s[i] = list1[pos]
return s
iris_dataset = load_iris()
X = iris_dataset["data"]
y = iris_dataset["target"] #actual output
#print(X)
print(y)
# k-means
kmeans = KMeans(n_clusters=3)
kmeans.fit(X) #train with data x- unsupervised learning-without considering target
y_kmeans = kmeans.predict(X)
print(y_kmeans)
plt.scatter(X[:, 0], X[:, 1],c=y_kmeans s=40, cmap='viridis') #scatter(x axis(all rows,1st column),y axis(all rows ,2nd column),content,size,type of map)
print(y_kmeans)
km = rename(y_kmeans)
print(km)
print("Accuracy KM : ", sm.accuracy_score(y, km))
plt.show()
# EM part
gmm = GaussianMixture(n_components=3)
gmm.fit(X)
y_kmeans = gmm.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=40, cmap='viridis')
print(y_kmeans)
em = rename(y_kmeans)
print(em)
print("Accuracy EM : ", sm.accuracy_score(y, em))
plt.show()
|
#ARMANDO DANIEL SAUCEDO ALEGRIA#
#COBOS VALDEZ JESUS RICARDO#
def entrada(matriz,fila,columna):
M = len(matriz)
for i in range(columna):
if matriz[fila][i] == "2":
return False
for i in range(columna,M,1):
if matriz[fila][i] == "2":
return False
for f,c in zip(range(fila,-1,-1), range(columna,-1,-1)):
if matriz[f][c] == "2":
return False
for f,c in zip(range(fila, M, 1), range(columna,-1,-1)):
if matriz[f][c] == "2":
return False
for f,c in zip(range(fila,-1,-1), range(columna,N,1)):
if matriz[f][c] == "2":
return False
for f,c in zip(range(fila,M,1), range(columna,N,1)):
if matriz[f][c] == "2":
return False
return True
def iterar(matriz,columna):
X = len(matriz)
if columna >=X:
return True
if colmOcupada(matriz,columna):
if iterar(matriz,columna + 1)== True:
return True
for i in range(X):
if entrada(matriz,i,columna):
matriz[i][columna] = "2"
if iterar(matriz, columna + 1) == True:
return True
matriz[i][columna] = 0
matriz[i][columna] = 0
return False
def colmOcupada (matriz,columna):
X = len(matriz)
for i in range(X):
if matriz[i][columna]== "2":
return True
return False
def impMatriz(matriz):
X = len(matriz)
for i in range(X):
for j in range(X):
print(matriz[i][j],end = " ")
print()
def reina(matriz):
if iterar(matriz,0)== False:
print("\n No hay Solución")
return False
print ("\n Solucion")
impMatriz(matriz)
return True
def Ceros(N):
Lista = []
for i in range(N):
Lista.append(0)
return Lista
N = int(input("Cual es el tamaño de la matriz"))
f = int(input("Fila en donde se encuentra la reina"))
c = int(input("Columna donde se encuentra la reyna"))
matriz = []
for i in range(N):
matriz.append(Ceros(N))
matriz[f][c]="2"
reina(matriz)
|
""" Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two.
If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same."
Try the following test cases for lists one and two:"""
def compareLists(list1, list2):
result = True
if len(list1) != len(list2):
result = False
else:
for i in range(len(list1)):
if list1[i] != list2[i]:
result = False
if result:
print('The lists are the same')
else:
print('The lists are not the same.')
list_one = [1, 2, 5, 6, 2]
list_two = [1, 2, 5, 6, 2]
list_one1 = [1, 2, 5, 6, 5]
list_two1 = [1, 2, 5, 6, 5, 3]
list_one2 = [1, 2, 5, 6, 5, 16]
list_two2 = [1, 2, 5, 6, 5]
list_one3 = ['celery', 'carrots', 'bread', 'milk']
list_two3 = ['celery', 'carrots', 'bread', 'cream']
compareLists(list_one, list_two)
compareLists(list_one1, list_two1)
compareLists(list_one2, list_two2)
compareLists(list_one3, list_two3)
|
# parkhaus.py
# Angabe für das Beispiel: siehe Moodle
a = 0;
print("Linienbus Simulator 2018!")
haltestellen = input("Wie viele Haltestellen gibt es? ")
haltestelle = int(haltestellen)
i = 0
while(i < haltestelle):
i= i + 1
y = a
print("Sie sind an der Haltestelle " , i , ". Wie viele Personen steigen ein?")
einsteiger = input()
person = int(einsteiger)
print("Wie viele Personen steigen aus?")
aussteiger = input()
draußen = int(aussteiger)
a = a + person
a = a - draußen
print("Es sind zurzeit", a ," Personen im Bus")
if(a > 60):
print("Hallo steigen sie bitte aus, die maximale Anzahl an Passagieren ist überschritten!!")
u = a - 60
print("Es dürfen ", u ," Personen nicht mitfahren.")
a = 60
if(a < 0):
i = i - 1
print("Achtung! Es sind zurzeit ", y ," Personen im Bus!")
a = y
print("Die Anzahl der eingestiegenen Personen beträgt " , a) |
import random
from hangman_art import stages, logo
from hangman_words import word_list
# import only system from os
from os import system, name
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
end_of_game = False
lives = 6
print(logo)
#Create blanks
display = ["_" for letter in chosen_word]
while not end_of_game:
guess = input("Guess a letter: ").lower()
#Clear the screen
clear()
if guess in display:
print(f'You\'ve already guessed {guess}')
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
#Check if user is wrong.
if guess not in chosen_word:
print(f'You guessed {guess}, that\'s not in the word. You lose a life.')
lives -= 1
if lives == 0:
end_of_game = True
print("You lose.")
#Join all the elements in the list and turn it into a String.
print(f"{' '.join(display)}")
#Check if user has got all letters.
if "_" not in display:
end_of_game = True
print("You win.")
print(stages[lives]) |
from art import logo
import random
# import only system from os
from os import system, name
#Define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal_card(hand):
hand.append(random.choice(cards))
return hand
def handle_ace(hand):
if sum(hand) > 21 and 11 in hand:
ace_index = hand.index(11)
hand[ace_index] = 1
return hand
def play_blackjack():
continue_game = True
user_wants_play = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")
if user_wants_play == 'y':
clear()
print(logo)
user_hand = []
computer_hand = []
#Deal 2 cards for the user and 2 cards for the computer
for _ in range(2):
deal_card(user_hand)
deal_card(computer_hand)
handle_ace(user_hand)
handle_ace(computer_hand)
#If you or Computer have a natural Blackjack
if sum(user_hand) == 21 or sum(computer_hand) == 21:
if sum(user_hand) == 21:
print(f' Your cards: {user_hand}, current score: 0')
print(f' Computer\'s first card: {computer_hand[0]}')
print(f' Your final hand: {user_hand}, final score: 0')
while sum(computer_hand) < 17:
deal_card(computer_hand)
handle_ace(computer_hand)
print(f' Computer\'s final hand: {computer_hand}, final score: {sum(computer_hand)}')
if sum(computer_hand) == 21:
print("It's a tie. 🙃")
play_blackjack()
else:
print("You win with a natural Blackjack! 🙌")
play_blackjack()
else:
print(f' Your cards: {user_hand}, current score: {sum(user_hand)}')
print(f' Computer\'s first card: {computer_hand[0]}')
print(f' Your final hand: {user_hand}, final score: {sum(user_hand)}')
print(f' Computer\'s final hand: {computer_hand}, final score: 0')
print("You lose! Your opponent has a natural Blackjack. 😢")
play_blackjack()
#If no natural blackjack
else:
print(f' Your cards: {user_hand}, current score: {sum(user_hand)}')
print(f' Computer\'s first card: {computer_hand[0]}')
draw = input("Type 'y' to get another card, type 'n' to pass: ")
while draw == 'y':
deal_card(user_hand)
handle_ace(user_hand)
print(f' Your cards: {user_hand}, current score: {sum(user_hand)}')
print(f' Computer\'s first card: {computer_hand[0]}')
if sum(user_hand) > 21:
print(f' Your final hand: {user_hand}, final score: {sum(user_hand)}')
while sum(computer_hand) < 17:
deal_card(computer_hand)
handle_ace(computer_hand)
print(f' Computer\'s final hand: {computer_hand}, final score: {sum(computer_hand)}')
print("Bust! You lose. 🤬")
draw = 'n'
continue_game = False
play_blackjack()
else:
draw = input("Type 'y' to get another card, type 'n' to pass: ")
if continue_game:
print(f' Your final hand: {user_hand}, final score: {sum(user_hand)}')
while sum(computer_hand) < 17:
deal_card(computer_hand)
handle_ace(computer_hand)
print(f' Computer\'s final hand: {computer_hand}, final score: {sum(computer_hand)}')
if sum(computer_hand) > 21:
print("Your opponent has busted. You win! 😁")
play_blackjack()
else:
if sum(user_hand) == sum(computer_hand):
print("It's a tie. 🙃")
play_blackjack()
elif sum(user_hand) == 21:
print("You win. 😁")
play_blackjack()
elif sum(computer_hand) == 21:
print("You lose! 😢")
play_blackjack()
else:
if sum(user_hand) > sum(computer_hand):
print("You win! 😁")
play_blackjack()
else:
print("You lose. 😢")
play_blackjack()
else:
print("Bye! See you next time. 👋")
play_blackjack() |
'''sort a dictionary by key or value'''
dict1={}
n=int(input("enter the number of element in dict1: "))
while n>0:
key=input("enter the key: ")
value=int(input("enter the value: "))
dict1.update({key:value})
n-=1
dict1=sorted(dict1.items(),key=lambda x:x[0])
print(dict1) |
def add1(a, b):
return a + b
def func2(add1):
def innerf(a,b):
print("this function subtract also")
c=a-b
#print(c)
return add1(a,b)
return innerf
ans=func2(add1)
print(ans(5,3)) |
def repeatingElement(a):
result = a[0]
for i in range(1,len(a)):
result = result ^ a[i]
print (result)
repeatingElement([1,2,3,4,5,5,6,7,8]) |
#simulation for two players at a time
#Players are chosen with uniform sampling
#Feel free to change parameters p,d,p,etc.
import random
'''fixes the bet for all games'''
#p players
p = 7
#d dollars
d = 77
#fixes the bet for all games
k = 11
Counts = []
num_iterations = 10000
for i in range(num_iterations):
count = 0
L = [d]*p
while len(L)>1:
#pick two poeple to play from the list
L2 = [L.pop(random.randrange(len(L))) for _ in range(2)]
#record where those two people are
#both players put some money in the pot (bet)
for i in range(len(L2)):
L2[i] = L2[i] - k
#pick a random person to win
index = random.choice(range(len(L2)))
#winner collects his earnings
L2[index] = L2[index] + 2*k
#put those players back in
L = L + L2
#zero out this mofo
while 0 in L:
del L[L.index(0)]
#counts the number of rounds
count = count + 1
Counts.append(count)
#prints the average
print(sum(Counts)/len(Counts))
###############################################
import random
'''changes the bet each time (most realistic)'''
#p players
p = 7
#d dollars
d = 7
Counts = []
num_iterations = 100000
for i in range(num_iterations):
count = 0
L = [d]*p
while len(L)>1:
#pick two poeple to play from the list
L2 = [L.pop(random.randrange(len(L))) for _ in range(2)]
#record where those two people are
k = random.randint(1,min(L2))
#both players put some money in the pot (bet)
for i in range(len(L2)):
L2[i] = L2[i] - k
#pick a random person to win
index = random.choice(range(len(L2)))
#winner collects his earnings
L2[index] = L2[index] + 2*k
#put those players back in
L = L + L2
#zero out this mofo
while 0 in L:
del L[L.index(0)]
#counts the number of rounds
count = count + 1
Counts.append(count)
#prints the average
print(sum(Counts)/len(Counts))
###############################################
import random
#Displays the rounds from a single game (out of the for-loop)
d = 77
p = 7
L = [d]*p
count = 0
Total = []
while len(L)>1:
#pick two poeple to play from the list
L2 = [L.pop(random.randrange(len(L))) for _ in range(2)]
#record where those two people are
k = random.randint(1,min(L2))
print(k)
#both players put some money in the pot (bet)
for i in range(len(L2)):
L2[i] = L2[i] - k
#pick a random person to win
index = random.choice(range(len(L2)))
#winner collects his earnings
L2[index] = L2[index] + 2*k
#put those players back in
L = L + L2
print(L)
#zero out this mofo
while 0 in L:
del L[L.index(0)]
#counts the number of rounds
count = count + 1 |
# author:JinMing time:2020-05-11
# -*- coding: utf-8 -*-
# 在一个内部函数里边,对在外部作用域(不能是全局作用域)的变量进行调用
# 那么这个内部函数就被称之为闭包
def outer():
x = 10
def inner():
print(x)
return inner
outer()() # inner()
# 可以拆为下面两行
a = outer() # a = inner
a() # inner()
|
# author:JinMing time:2020-04-10
alist = [9,2,6,0]
alist.sort(reverse=True)
print(alist)
print(alist[::-1])
# alist.reverse()# 翻转顺序--不排序
# print(alist)
|
class Tiger:
nickName = '老虎' #静态属性
def __init__(self,inWeight):#实例属性
self.weight = inWeight
#实例方法--
def roar(self):
print('我是老虎---wow!,体重减5斤')
self.weight -= 5
def feed(self,food):
if food == 'meat':
self.weight += 10
print('恭喜,喂食正确,体重增加10斤')
else:
self.weight -= 10
print('抱歉,喂食错误,体重减少10斤')
class Sheep:
nickName = '羊' #静态属性
def __init__(self,inWeight): #实例属性
self.weight = inWeight
#实例方法--
def roar(self):
print('我是羊---mie~~,体重减5斤')
self.weight -= 5
def feed(self,food):
if food == 'grass':
self.weight += 10
print('恭喜,喂食正确,体重增加10斤')
else:
self.weight -= 10
print('抱歉,喂食错误,体重减少10斤')
class Room:
def __init__(self,inNum,inAnimal):
self.num = inNum
self.animal = inAnimal
from random import randint
#---------游戏初始化---------------
roomList = []#元素---房间实例
for one in range(1,11):
if randint(0,1) == 1:
ani = Tiger(200)
else:
ani = Sheep(100)
room = Room(one,ani)
roomList.append(room)
print()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.