text stringlengths 37 1.41M |
|---|
class student:
def set id(self,id):
self.id=id
def getid(self):
return self.id
def set Name(self,Name):
self.Name=Name
def get Name(self):
return self.Name
s=student()
s.setid(123)
s.setName("Ashish")
print(s.getid())
print(s.get... |
class countdown:
def __init__(self):
self.a = 1
def final(self):
print(type(self.a))
c = countdown()
c.final()
c.final()
#what's the output
def swap(a,b):
b,a = a,b
a,b = 2,203
swap(a,b)
print(a-b) |
#Write a Python program to count the number of occurrence of a specific character in a string.
s = "this is a cir"
print(s.count("i"))
#Write a Python program to check whether a file path is a file or a directory.
import os
path = "abc.txt"
if os.path.isdir(path):
print("\nIT is a directory")
elif os.path.isfile(p... |
# -*- coding: utf-8 -*-
# Criando minha própria exceção através da classe Exception.
class ValorRepetidoErro(Exception):
def __init__(self, valor):
self.valor = valor
def __str__(self):
return "O valor %i já foi digitado antes." %(self.valor)
lista = []
for i in range(3):
try:
... |
import tkinter as tk
from tkinter import Menu
janela = tk.Tk()
# Método para sair da aplicação.
def _sair():
janela.quit()
janela.destroy()
exit()
# Criando barra de menu e adicionando-a à janela.
barra_menu = Menu(janela) # Barra de menu.
janela.config(menu=barra_menu)
# Criando menus.
# O tearoff serv... |
# Lendo um arquivo e salvando suas linhas em uma lista.
arquivo = open('arquivo.txt', 'r')
# Lista, onde cada elemento representa uma linha do arquivo.
linhas = arquivo.readlines()
for l in linhas:
print(l)
arquivo.close() |
# coding: utf-8
import os
os.system("clear")
#fila - FIFO
F = ["primeiro","segundo","terceiro","quarto","quinto"]
print("------------------")
print("Fila: ")
print(F)
while len(F) > 0:
print("Removendo o %s da fila. " %(F[0]))
F.pop(0)
print(F)
#pilha - LIFO
#pilha - LIFO
P = ["primeiro","segundo","terceiro","qu... |
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def info(self):
print(f'Plane brand {self.brand}, {self.model}', end=' ')
class Destroyer(Plane):
def __init__(self, brand, model):
super().__init__(brand, model)
self.can_fire... |
from threading import Thread, Lock
import time
import random
from threading import Condition
buffer = []
lock = Lock()
MAX_NUM = 5
condition = Condition()
class ConsumidorThread(Thread):
def run(self):
global buffer
while True:
condition.acquire() #entrar na região crít... |
# -*- coding: utf-8 -*-
__author__ = 'vincent'
# property, 负责把一个方法变成属性调用
class Student(object):
# score is a property object, property 是一个内置的装饰器
# 加@property, 把一个get_score方法变成属性
# 只定义getter方法,不定义setter方法就是一个只读属性:
@property
def score(self):
return self._score
@score.setter
def scor... |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-08-08
# @Last Modified by:
# @Last Modified time:
# @Title : Generate sequence in list and tuple
# '''
values = input("Input sequence of number seprated by comma: ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple) |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-09-08
# @Last Modified by:
# @Last Modified time:
# @Title :Write a Python program to remove an item from a tuple.
# '''
mytuple = (2, 4, 5, 67, 7, 4)
print("Tuple:-",mytuple)
tempTuple = list(mytuple)
tempTuple.pop(3)
print("Tuple after removing single element:-",tuple(tem... |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-05-08
# @Last Modified by:
# @Last Modified time:Sanket
# @Title : Power of 2 till N
# '''
N = int(input("Enter N value:- "))
if N < 0 or N > 31:
print("Please enter positive value less then 31")
else:
for x in range(N):
print(2**x) |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-09-08
# @Last Modified by:
# @Last Modified time:
# @Title :Write a Python program to create a tuple.
# '''
"""
Description:
created function for as unpack_tuple with argument as x passes through tuple.
Parameter:
used n1, n2, n3, n4 to store the element after its g... |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-09-08
# @Last Modified by:
# @Last Modified time:
# @Title :Write a Python program to sum all the items in a list..
# '''
"""
Description:
created function for as sum_of_list.
Parameter:
declare total as 0 initially and assign values to the num in form of list.
Ret... |
word=str(input())
a=list(word)
count=0
for i in a:
if i.isnumeric()==True:
count=count+1
print(count) |
#!/usr/bin/python3
# inputs are tensors which are defined as Python lists with dimensions like so:
# [batch, channel, 2-D numpy array]
#
# in some cases, they are expressed as [layer, batch, channel, 2-D numpy array]
import numpy as np
class ANN:
def __init__(self, layers, numChannels, actFunc, beta = 0.9):
... |
import time
from random import randrange
def minimumValue(values):
overallMin = values[0]
for i in values:
smallest = True
for j in values:
if i > j:
smallest = False
if smallest:
overallMin = i
return overallMin
for listSize in range (100, 1001, 100):
values = [randrange(1000) f... |
'''
autor : Geovanna Alves Magalhães
data : 17/05/18
'''
nota1 = float(input('Digite sua primeira nota'))
nota2 = float(input('Digite sua segunda nota'))
nota_total = nota1+nota2
print('Sua nota total é ' , nota_total)
media = nota_total / 2
print ('Sua média é ' , media)
if media >= 9.0 and media <= 10.0 :
prin... |
"""
File: boggle.py
Name: Wilson Wang
----------------------------------------
This program recursively finds all the vocabs for the word input by user in boggle.
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
# global vari... |
"""
File: caesar.py
name: Wilson
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic seq... |
"""
File: quadratic_solver.py
Name: Wilson Wang
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math... |
# Convert Input values to SI's (Standard units)
#
import math
# Other Functions for this Module
def KTS_to_MS(x): return x * .514447
def MPH_to_MS(x): return x * .44704
def KPH_to_MS(x): return x * .2777778
def FT_to_M(x): return x * .3048
def FAT_to_M(x): return x * 1.829
def MTR_to_M(x): return x * 1
def NMI_to_M(x):... |
class Texts(object):
def intro():
print(
"¡Welcome to Pyshion! \n\nIn this application you can find the complementary, splitcomplementary and triad colors \n"
"By using the following syntax: \n"
"\tcolor\n"
"\tcomplementary color\n"
"\tsplitcomplem... |
#This code is an edited version of an example referenced from
#(https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/planetary_motion_three_body_problem.ipynb), which discussed different constant step size ordinary differential equation (ODE) solvers (such as Forward Euler, Explicit Trapezoid, Midpoint Rule... |
# Method 1
def feb(n):
if n == 1 or n == 2:
result = 1
else:
result = feb(n-1) + feb(n-2)
return result
# Method 2
def feb2(n):
memo = [None] * (n+1)
return feb_memo(n,memo)
def feb_memo(n,memo):
if memo[n] is not None:
return memo[n]
if n == 1 or n == 2:
... |
"""
set method
add()
clear()
copy() - return a copy of set
implement - to work it out, to figure it out, to write the detail
"""
# copy()
A = {1,2,3,4,5}
# copy A to B
B = A.copy()
print(B)
# our solution of copy
C = set()
for i in A:
print(i)
C.add(i)
print(C)
print(C is A)
# upgrade our code
def mycop... |
"""
start the game, the entrance of the game
init() - initializing
loadImage() - load background image
loadSound() - load background music
loadAcctInfo() - load user's account information
start()
user selects a level
sys loads level data and all resources (import load)
user plays game
user select exit... |
"""
part 2
question 2
"""
"""
function: ok 5/5
structure: ok 1.25/1.25
convention: ok 1.25/1.25
comment: ok 1.25/1.25
user-friendly: failed to use exception 0.75/1.25
subtotal: 9.5
"""
... |
"""
Quiz 5
"""
# question 6.2
# list1 = [1,2,3,4,5,6]
# print(list1[0], list1[5])
# question 6.3
# list1[3] = 999
# print(list1)
# question 6.4
# tuple1 = (21,31,41,51,61,17)
# print(tuple1[0], tuple1[5])
# question 6.5
# a tuple is unchangeable
# question 6.6
# set1 = {1,1,2,2,3,3}
# print(set1)
# question 6.7
... |
"""
positional argument
"""
print("Hello {0}, your balance is {1}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:9f}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:9.3f}".format("Adam",230.2346))
|
# Issa - me
# copy()
A = {1, 2, 3, 4, 5}
# copy A to B
B = A.copy()
print(B)
# Another way
a = {2, 3, 1, 6, 2, 9, 4}
b = a
print(b, a)
|
"""
Password v3
Guang Zhu Cui
2020-06-21
v3. Encrypting Password
For security reasons, the password should not directly be persisted into databases in original form.
It is recommended that every character should get right shifted for 3 steps.
For example,
a -> d, b -> e, c -> f, …, 0 -> 3
print out the encrypted pa... |
"""
encrypting a password
decrypting a password
"""
char = '%'
print("original char :",char)
# encrypting
# get ascii number
asc_no = ord(char)
print(asc_no)
print()
asc_no += 3
en_char = chr(asc_no)
print("en_char :",en_char)
# decrypting
pwd_asc_no = ord(en_char)
print(pwd_asc_no)
print()
pwd_asc_no -= 3
de_c... |
"""
loop
condition at the top
"""
a = 10
b = 5
while a > 0 and b < 15:
print()
|
"""
membership operator
in, not in
"""
# case 1. list
list1 = [1,2,3,4,5,6,7]
print(8 in list1)
print(8 not in list1)
print()
print(3 in list1)
print(3 not in list1)
print()
# case 2. tuple
tuple1 = ('a','b','c','d')
print('b' in tuple1)
print('b' not in tuple1)
print()
print('z' in tuple1)
print('z' not in tuple1)... |
"""
[Homework]
1. Search and Download an html file
Read it and print out
html - Hypertext Markup Language
render
2. Search and Download a CSV file
Read it and print out
"""
print("Starting load html document...")
try:
file = open("home1.html")
content = file.read()
print(content)
file.close()
ex... |
"""
set
remove items from a set
discard() - remove a specified item
remove() - remove a specified item
pop() - remove an item randomly
clear() - remove all items
"""
# remove items by discard()
myset1 = {2, 3, 4, 5, 67, 7, 9, 45, 77, 51, 88, 91, 31}
myset1.discard(88)
print(myset1)
# myset1.discard()
# print(myset... |
"""
Homework 10
click button [Click me]
create a Label object
set text
display the Label
"""
from tkinter import *
def response():
"""
create a Label object
set text
display the Label
:return:
"""
print("I was clicked!")
root = Tk()
root.title('Python GUI - Button')
root.geometry('64... |
"""
solving problem
1,2,3,4,5,6,7,8,9,....,1000
how to calculate the sum of this sequence of number
"""
sum = 0
for i in range(1,1001):
print(i)
sum = sum + i
print(sum) |
"""
string - join()
"""
words = ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
result = ' '.join(words)
print(result, type(result))
print()
result = ''.join(words)
print(result, type(result))
print()
nums = [str(1),str(2),str(3),str(4),str(5),str(6),str(7)]
result = ','.join(nums)
print(result, type... |
"""
dictionary - iterating
"""
dict1 = {1:1, 2:4, 3:9, 4:16}
print(type(dict1))
for key in dict1:
print(key)
print()
for i in dict1.items():
print(i, type(i))
print(f"{i[0]}:{i[1]}")
# print("{}:{}".format(i[0], i[1]))
print()
print(type(dict1.keys()))
for i in dict1.keys():
print(i)
print()
... |
"""
[Homework]
1. Write a Python program to get a list, sorted in increasing order
by the last element in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
2. Write a Python program to remove dupli... |
"""
local scope
local variable
"""
def foo():
y = "local"
print("inside foo() y is ",y)
foo()
# NameError: name 'y' is not defined
print(y)
|
"""
tell if a given number n is a prime number
if n is a prime number
print out : Yes, the number of {} is a prime number
else
print out : No, it is not a prime number
"""
# n = 11
#
# 1,2,3,4,5,6,...,11 (n times)
# i = 2 .. (n-1)
#
# 11 % i == 0
# not a prime number
# input a number
number = int(input("... |
"""
membership
in, not in
"""
# list membership
list1 = [1,2,3,4,5,6]
item = 4
result = item in list1
print(result)
result2 = item not in list1
print(result2)
# iterating through a list
for i in list1:
print(i)
|
"""
my text
goal: to replace all 'my' with 'your'
1. convert the sentence into a list of words
string.split()
2. iterate over the list
for-loop
if the current word == 'my'
then replace with 'your'
3. combine all words in the list into a string
' '.join(iterable)
4. output
print()
"""
... |
"""
func9. variable arguments
default argument
rule:
positional arguments stay before all the default(keyword) arguments
"""
# def greeting(words="Good morning,", friendname):
# print(words, friendname, "!")
def greeting(friendname, words="Good morning,"):
print(words, friendname, "!")
# friendname1 = "P... |
"""
fromkeys()
"""
str1 = "python is a good language"
keys = set(str1)
print(keys)
charcount = {}
# charcount = charcount.fromkeys(keys)
charcount = charcount.fromkeys(keys, 0)
print(charcount)
for char in str1:
charcount[char] += 1
print(charcount)
|
"""
lambda, high order function
"""
# input a number
# output a mulplication table (a x 1 to a x 10)
"""
input : 3
3 x 1 = 3
3 x 2 = 6
...
3 x 10 = 30
"""
# return a lambda function
def table(n):
return lambda a : a * n
# input a number
n = int(input("Enter an integer (n>0):"))
# get the function with n
b ... |
"""
Quiz 8
"""
# 8.
sentence = input("Enter a sentence:")
if "A" in sentence or "a" in sentence:
print("There is an A")
else:
print("There is no A")
# 9.
list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 4, 5]
print(list1 == list2)
print(list1 is list2)
# 10.
# If it is May 22
days = ['Mon','Tue','Wed','Thu','Fri',... |
"""
sorting in ascending order
numeric : from the smallest to the biggest
string: A->Z a->z
sorting in descending order
"""
"""
a < b < c
ab < ac
acb > abc
ab < abb
"""
# sorting a dictionary
d = {'ca': 2, 'ab': 4, 'bb': 3, 'b': 1, 'aa': 0}
print("before:",d)
# sorted() - built-in
result = sorted(d.items())
# pri... |
"""
a+b*c
user inputs a
user inputs b
user inputs c
to evaluate the expression of a+b*c
print out the result
Please keep in mind:
1. write down your idea
2. translate into your code
3. write a little and test a little
4. input + process + output
"""
"""
print("=== Calculator ===")
print("to evaluate a + b*c ")
# st... |
"""
output print
"""
# syntax
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print(1,2,3,4,5)
print(1,2,3,4,5, sep=',')
print(1,2,3,4,5, end='&&')
print(1,2,3,4,5)
# How can we output a 3X4 matrix and make the layout like 3 rows and 4 columns? (1’)
# x x x x
# y y y y
# z z z z
print("The na... |
"""
module: random
"""
# import math
import random
# get a random number from a specified range
# start, stop
# randrange(start, stop), and the stop number is excluded
for i in range(100):
print(random.randrange(1,6), end=",")
print()
# randint(start, stop)
for i in range(100):
print(random.randint(1,6), en... |
"""
sort()
sort items in a list in ascending order
sort(reverse=True)
descending order
max, min
bubble sorting
quick sort
merge sort
select sort
insertion sort
heap sort
...
"""
odd = [1,2,10,31,5,10,7,9,10,12,14,10]
odd.sort()
print(odd)
odd.sort(reverse=True)
print(odd)
strlist = ['bac','abc','a','aa','bc']
s... |
"""
open a file in read mode
"""
f = open("file5_mode_r.txt",'r')
# read the whole data in the file
print(f.read())
f.close() |
# data type of set
list1 = [1,2,3,4,5]
print(list1, type(list1))
tuple1 = (1,2,3,4,5)
print(tuple1, type(tuple1))
set1 = {1,2,3,4,5}
print(set1, type(set1))
set2 = {1,1,2,2,3,3}
print(set2)
set3 = {3,2,1}
print(set3)
set4 = {'a',2,5.7}
print(set4)
set5 = {1,2,(1,23)}
print(set5)
# convert list to set
print(set(... |
"""
import a module
how to use members of a module
"""
import math
# case1. use constant
a = math.pi
print(a)
# case2. use function
x = 9
b = math.sqrt(x)
print(b)
|
"""
homework: how to prove there is evenly distributed probability of 1-6 with a huge number of trials
f = 1/T
expectation: evenly distributed
"""
import random
for n in range(10000):
res1 = random.randrange(1,7)
# print(res1)
#
# ====================
# dict
frequencies = {}
res1 = str(res1)
for digits... |
"""
truncate against strings
.3
"""
print("{:.3}".format("caterpillar"))
print("{:.4}".format("caterpillar"))
print("{:.5}".format("caterpillar"))
# and padding
print("|{:5.3}|".format("caterpillar"))
print("|{:>5.3}|".format("caterpillar"))
print("|{:^5.3}|".format("caterpillar"))
|
"""
module: random
"""
import random
# randrange(N)
# res1 = random.randrange(6)
# print(res1)
#
# res1 = random.randrange(6)
# print(res1)
for n in range(10):
res1 = random.randrange(6)
print(res1)
print('======')
# randrange(a, b)
for n in range(20):
res1 = random.randrange(1,7)
print(res1)
pri... |
my_dict = {1: 4, 5: 3, 7: 9}
def sort_by_value(my_dict_1):
items = my_dict_1.items()
back_items = [[v[1], v[0]] for v in items]
back_items = sorted(back_items)
print([back_items[i][1] for i in range(0, len(back_items))])
print([v for v in sorted(my_dict_1.values())])
sort_by_value(my_dict)
|
"""
stem1402_python_final_p2_ken
Ken
Commented out is an interactive result inputter.
"""
# results = []
# continues = True
#
# while continues:
# results.append(input("Please write the team's number: "))
# results.append(input("Please write the team's name: "))
# results.append(input("Please write the t... |
"""
datatype
Knowing Datatype, then knowing the operations on the data
Every value in python has a datatype
Numbers (int, float, complex)
"""
# type() - built-in function in python
a = 10
print(a, type(a))
# integer , int
# isinstance() - return True or False
value = 99
print(isinstance(value, int))
print(isi... |
"""
Welcome back to python class!
"""
print()
"""
this is a multiple line comment
this is a multiple line comment
"""
'''
this is a multiple line comment
this is a multiple line comment
'''
# comments - single line comment
# what is comment?
# what is comment for?
# how many types?
# a = 1
# what is variable?
... |
"""
set symmetric difference
Symmetric Difference of A and B is a set of elements
in both A and B except those that are common in both.
"""
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
result = A ^ B
print(result)
result = A.symmetric_difference(B)
print(result)
result = B.symmetric_difference(A)
print(result)
# A -... |
"""
infinite loop
"""
flag = True
while flag:
print("infinite loop")
# without any condition
flag = False
|
"""
"""
with open('colors.txt') as file:
colors = file.readlines()
print(type(colors))
for color in colors:
color = color.strip()
print(color,end='') |
list2 = [1, 2, 3, 4, 5]
x = 1
for i in list2:
x = x * i
print(x)
|
mydict = {1: 2, 3: 4, 5: 3, 4: 3, 2: 1, 0: 0}
result = mydict.items()
key = lambda item:item[1]
# sorted(iterable, key, reverse)
sorted_result = sorted(result, key=lambda item:item[1], reverse=True)
sorted_dict = dict(sorted_result)
print(sorted_dict) |
"""
2. Python Program to Display the 9X9 multiplication Table
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8... |
"""
number formatting with alignment
<
^ centered
>
= forces the sign(+/-) to the leftmost position
"""
# align to right by default
print("|{:5d}|".format(12))
print("|{:6d}|".format(12))
# centered
print("|{:^6d}|".format(12))
# left
print("|{:<6d}|".format(12))
# right
print("|{:>6d}|".format(12))
# leftmos... |
"""
Clock: v1
NOTE: root = window
1. Write a GUI program of clock
Requirements:
(Function)
Show current time in the pattern of HH:mm:ss.aaa
i.e.
10:12:45.369
(UI)
Display a title, main area for clock, and footer for the date
Due date: by the end of next Friday
Hint:
import datetime
strftime
review datetime
1. to get... |
"""
open a file
operate
close
file path(location)
file name
file path + file name
When to omit file path?
under the same directory or path
file path:
1. absolute path
D:\workspace\pycharm201803\stem1401python_student\py200912b_python2m6\day11_201121\file_1.txt
2. relative path
py200912b_python2m6/day11_201121/file_... |
"""
sorted()
Return a new sorted list from elements in the set(does not sort the set itself).
"""
A = {3,2,4}
result = sorted(A)
print(result, type(result))
#
A = {'b','c','a'}
result = sorted(A)
print(result, type(result))
#
# A = {'b','c','a',2,3,1}
#
# result = sorted(A)
# print(result, type(result)) |
"""
datatype conversion of collection
list(), tuple(), dict(), set()
"""
# case 1. list to tuple
list1 = [1,2,3]
print(list1)
print(tuple(list1))
# case 2. tuple to list
tuple1 = (1,2,3)
print(tuple1)
print(list(tuple1))
# case 3. str (tuple) to list
str1 = 'hello'
print(list(str1))
print(list('hello'))
# case 4. l... |
"""
"""
"""
matrix = [[11,12,13,14],[21,22,23,24],[31,32,33,34]]
# print(matrix)
for row in matrix:
# print(row)
for col in row:
print(col, end="\t")
print()
print()
matrix = [[11,12,13],[21,22,23],[31,32,33]]
# print(matrix)
for row in matrix:
# print(row)
for col in row:
print... |
"""
set - method
"""
# copy()
# copy a set and return
# is it a built-in function?
A = {1,2,3}
B = A.copy()
print(B)
print(B is A)
# isdisjoint()
print()
A = {1,2,3}
B = {4,5,6}
print("A is disjoint to B?",A.isdisjoint(B))
# subset and superset
A = {1,2,3}
B = {1,2,3}
B = {1,2}
B = {1,2,5}
print("A = ",A)
pr... |
"""
to check if a path is existing
"""
import os
# case 1. directory or folder
path = '../day12_201219'
result = os.path.exists(path)
print(f"The path of {path} exists? {result}")
# case 2. files or documents
path = '../filedir_1_rmfile.py'
path = r'D:\workspace\pycharm201803\stem1401python_student\py200912f_pyth... |
"""
isdisjoint()
"""
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C = {9,10}
#
result = A.isdisjoint(B)
print(result)
#
result = A.isdisjoint(C)
print(result)
# application
if A.isdisjoint(B):
print("A and B have common items")
else:
print("A and B do not have common items")
|
"""
set operation - set symmetric difference
"""
A = {1,2,3,4}
B = {4,5,6,7}
print(f"Set A: {A}")
print(f"Set B: {B}")
result = A ^ B
print(f"Result Set A^B : {result}")
result = (A-B) | (B-A)
print(f"Result Set A^B : {result}")
result = (A | B) - (A & B)
print(f"Result Set A^B : {result}")
result = A.symmetric_d... |
"""
rename a file or dir
rename(old, new)
"""
import os
# rename a directory
# rename mydir3 -> mydir3a
# old = 'mydir3'
# new = 'mydir3a'
#
# os.rename(old, new)
# rename a file
os.rename("rename_file.py", "rename_file_new.py")
|
"""
symmetric difference
"""
#
A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {3,4,7}
result = A ^ B
print(result)
result = A ^ B ^ C
print(result)
result = C ^ B ^ A
print(result)
result = C ^ A ^ B
print(result)
|
"""
password
v3
encrypt
decrypt
"""
def encrypt(char):
pass
def decrypt(ascii):
pass
pwd = 'asdfsdfasdfas'
encrypt_pwd = []
decrypt_pwd = ""
for c in pwd:
encrypt_pwd.append(encrypt(c))
print("encrypted pwd is:", encrypt_pwd)
for pc in encrypt_pwd:
decrypt_pwd += decrypt(pc)
print("encrypte... |
"""
file operation
read()
read(size)
readline()
readlines()
"""
try:
# step 1. open a file
file1 = open('file_1.txt')
# step 2. operate on the opened file
# round 1
content = file1.read()
print(content)
print("==================")
# file1.close()
# round 2
file1.seek(0)
... |
"""
matrix_homework
"""
a = [[1, 2, 3, 4],
[11, 21, 31, 41],
[42, 53, 64, 75]]
print(a[1][0]) # getting the number 11
print(a) |
# ex 1.
# create a list with 6 items
# i.e
fruits = ['apple','pineapple','orange',
'watermelon','peach','grape']
print(fruits)
sports = ['basketball', 'football', 'hockey',
'baseball', 'soccer', 'gymnastic']
print(sports)
animals = ['dog','cat','horse',
'mouse','cow','bird']
print(anima... |
"""
Exception Handling
1. what is an exception?
error
at runtime
at compile time
validate or syntax checking
python
detect, catch, handle possible exceptions
types of exception:
a. built-in exception
b. user-defined exception
2. why?
to avoid to crash frequently
to improve the tolerance ability of your programs, r... |
"""
docstring in functions
"""
# docstring in function without argument
def foo():
"""
the description of this function
:return:
"""
print("Yes, we entered the function of foo()")
# call a function
foo()
print("Good bye!")
# docstring in function with arguments
def add(num1, num2):
"""
t... |
"""
menu
basic menu and menu option
"""
from tkinter import *
from tkinter import messagebox
def test_menu1():
messagebox.showinfo("Test", "Menu 1 is clicked")
def test_menu2():
messagebox.showinfo("Test", "Menu 2 is clicked")
main = Tk()
main.title("Athensoft Python Course | Menu")
main.geometry("640x4... |
"""
Button
create a Button
and write response code
"""
from tkinter import *
def response():
print("I was clicked.")
win = Tk()
win.title("Tkinter Button")
win.geometry("480x320+300+300")
win.config(bg="#ddddff")
# Button
# command option accepts function only (function name or anonymous function/lambda)
btn1... |
"""
[Challenge] Project. Volume Controller
c04_button/button_03_b.py
Description
Max value and Min value
1. User can press '+' button to increase the number by one per click
2. User can press '-' button to decrease the number by one per click
3. The number shows in a Label
constraints:
the MAX value = 10,
the MIN valu... |
"""
Write a Python program to sum all the items in a list.
[Homework] 2021-01-18
Write a Python program to multiply all the items in a list.
"""
# step 1. to create a list
list1 = [1,2,3,4,5,6]
# step 2. to sum all the items
a = [1, 2, 3, 4, 5]
b = sum(a)
print(b)
# step 2. to sum all the items using for loop
# ho... |
"""
if-statement
if-elif-else statement
elif -> else if
if-elif,elif,...,else
"""
# sample
score = 89
if score >= 90:
print("You got an A")
elif score >= 80:
print("You got a B")
elif score >= 70:
print("You got a C")
elif score >= 60:
print("You got a D")
else:
print("You got a F")
# ex.
# ... |
"""
Python dictionary
Sorting by key
functions:
sorted()
list()
map()
list comprehension
references:
https://blog.csdn.net/buster2014/article/details/50939892
"""
# option 1
def sortedDictValues1(mydict):
items = mydict.items()
# items.sort()
sorted(items)
return [value for key, value in items]
# o... |
"""
Leonj
"""
print("=== Login Form ===")
username = input('Please enter your username:')
# input ('please enter your password')
password = input('Please enter your password:')
number = input('Please enter your number:')
print("Welcome back, ", username, "!")
print("=== Done, ===")
|
"""
quiz 1
My quiz anwsers:
1.a and c
2.a and d
3.b
4.a
5.a
6.a and b
7.a
"""
"""
Homework: forming a triangle with *
"""
# I tried using while loop but i failed
num = 5
row = 0
while row < num:
star = row + 1
while star > 0:
print("*",end=" ")
star = star - 1
row = row + 1
print()
print()... |
"""
to permanently persist into external storage
to append content to an existing file
write a program to save any text-based content
"""
# step 1. prepare data to output
print("Program started.\n")
data = "This is the 4th part of content I would like to save as a new line.\n"
# step 2. writing
print("Writing...")
... |
"""
[Homework]
Date: 2021-02-20
1. Write a GUI program of Label counter for implementing version 3.
Requirements:
(Function)
When the number reaches 10, then it comes to stop and displays the text of 'END'.
If a user clicks to close the main window, the program terminates.
(UI)
Using the layout manager of pack() for th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.