text
stringlengths
5
121k
import turtle def spezzataQuad(t, lato, livello): if livello == 0: t.forward(lato) else: spezzataQuad(t, lato / 3, livello - 1) t.right(90) spezzataQuad(t, lato / 3, livello - 1) t.left(90) spezzataQuad(t, lato / 3, livello - 1) t.left(90) ...
from pygame.locals import * import pygame, sys import maze_generator WIDTH = 800 HEIGHT = 800 BLACK = (0, 0, 0) RED = (255, 20, 0) YELLOW = (255, 255, 0) GRAY = (100, 100, 100) GREEN = (0, 200, 0) speed = 3 px = 100 py = 100 status = "new_game" direction = "" tile_x = 0 tile_y = 0 pygame.init() screen = pygame.dis...
a = input("Masukkan angkan: ") print (type(a)) print("Nilai a: {0}".format(a)) remainder = a%2 if remainder > 0: print("Nilai a adalah bilangan ganjil") else: print("Nilai a adalah bilangan genap")
class RectangularRoom: SQUARE_FEET_TO_SQUARE_METER_CONVERSION = 0.09290304 lengthFeet = 0.0 widthFeet = 0.0 def __init__(self, length, width): self.lengthFeet = length self.widthFeet = width def areaFeet(self): return self.lengthFeet * self.widthFeet def areaMeters(sel...
class Student(object): def __init__(self,name): self.name=name def __str__(self): return 'Student object (name: %s)'%self.name __repr__=__str__ print(Student('Michael')) s=Student('Michael') print(s) class Fib(object): def __init__(self): self.a,self.b=0,1 def __iter__(se...
class Student(object): def __init__(self,name): self.name=name s=Student('Bob') s.score=90 print(s.__dict__) del s.score print(s.__dict__) class Student1(object): name ='Student' p=Student1() print(p.name) print(Student1.name) p.name='Micheal' print(p.name) print(Student1.name) del p.name ...
board = [0, 1, 'O', 3, 'X', 5, 6, 7, 'X'] free_spaces = list(filter(lambda x: x != 'X' and x != 'O', board)) free_spaces = list(filter(lambda x: x != 'X' and x != 'O', board)) while True: print(free_spaces) player_choice = input('Select your square > ') player_choice = int(player_choice) print(type(p...
import time import dht from machine import Pin class Temperature(): current_temp = 0 system = 'celsius' def __init__(self, system='celsius'): self.system = system def temp(self): if self.system == 'fahrenheit': return self.fahrenheit() return self.celsius() ...
def split(List): index_no = len(List) half = int(index_no/2) print(half) left_List = List[0:half] right_List = List[half:index_no] return left_List, right_List split(split([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]))
def hanoi(n, from_pos, to_pos, aux_pos): if n == 1: print(from_pos, "->", to_pos) return hanoi(n - 1, from_pos, aux_pos, to_pos) print(from_pos, "->", to_pos) hanoi(n - 1, aux_pos, to_pos, from_pos) hanoi(3, 'A', 'B', 'C')
from random import randint def swap(array, i, j): _ = array[i] array[i] = array[j] array[j] = _ def partitioning(array, low, high): pivotIndex = randint(low, high) pivotValue = array[pivotIndex] swap(array, pivotIndex, high) storeIndex = low for i in range(low, high): if ...
list1 = [123, 456] list2 = [124, 789] print(list1 > list2) print(list1 + list2) list1 *= 5 print(list1) print(123 in list1) dir(list1) print(list1.count(123)) print(list1.index(123)) print(list1.reverse()) print(list1) list1.sort() print(list1) list1.sort(reverse=True) print(list1)
class PKCS7Encoder(object): """ Technique for padding a string as defined in RFC 2315, section 10.3, note #2 """ class InvalidBlockSizeError(Exception): """Raised for invalid block sizes""" pass def __init__(self, block_size=16): if block_size < 2 or block_size > 255: ...
from abc import ABC, abstractmethod class Optimizer(ABC): def __init__(self, heuristic_factory, collision_checker, initial_guess, configuration): self.tube_num = configuration.get("tube_number") self.precision = configuration.get("optimizer_precision") self.configuration = configuration ...
from banco import Cinema,Filme, Programacao,db db.connect() cine = Cinema.select(Cinema).where((Programacao.filme == 3)& (Programacao.cinema == Cinema.codigo)).join(Programacao).join(Filme).group_by(Cinema.codigo) for c in cine: print(c.nome +" \n")
def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('Введите текск: ') if(is_palindrome(something)): print('Да, это палиндром') else: print('Нет, это не палиндром')
Location = input('Enter your Location:') if Location== 'Dublin': print ('You entered Dublin. Dublin is in Leinster') elif Location == 'Belfast': print ('You entered Belfast. Belfast is in Ulster') elif Location == 'Cork': print ('You entered Cork. Cork is in Munster') elif Location == 'Limerick': print...
def sqroot(number): epsilon = 0.01 step = epsilon**2 numguesses=0 root = 0.0 while abs(number-root **2) >=epsilon and root <=number: root += step numguesses +=1 if numguesses % 100000 == 0: print('Still running. Number of guesses:',numguesses) pr...
def max(a,b): if a>b: return a else: return b number_1 = float(input("Enter a number: ")) number_2 = float(input("Enter another number: ")) print ("The largest of", number_1,"and", number_2, "is", max(number_1, number_2)) print("Finished!")
x = int(input('input an int:')) y = int(input('input another int:')) if x + y > 100: print('That is a big number!') exit()
def palindrome(a): """ This method checks whether a given string is a palindrome """ return a == a[::-1] if __name__ == '__main__': print(palindrome('mom'))
def most_commmon(lst): """ This method returns the most frequent element that appears in a list """ return max(set(lst), key=lst.count) if __name__ == '__main__': numbers = [1, 2, 1, 2, 3, 2, 1, 4, 2] print(most_commmon(numbers))
from PIL import Image, ImageDraw, ImageFont import random as random def rndChar(): return chr(random.randint(65, 90)) def rndColor1(): return (random.randint(64, 256), random.randint(64, 256), random.randint(64, 256)) def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random...
class person: def cry(self): print("大哭") def __init__(self): self.cry() p1 = person() class person2: def __init__(self, sex, name): self.sex = sex self.name = name def speck(self): print(self.name,self.sex) p2 = person2(sex="女",name="张三妹") p2.speck()
class Solution: def isPalindrome(self, s: str) -> bool: return self.isPalindrome__pointers(s) def isPalindrome__reverse_slice(self, s: str) -> bool: if len(s) < 2: return True s = "".join(c.lower() for c in s if c.isalnum()) resul...
from typing import List class Solution: MAIN = "maxProfit" def maxProfit(self, prices: List[int]) -> int: return self.maxProfit__tracking_buy_price(prices) def maxProfit__brute_force(self, prices: List[int]) -> int: max_profit = 0 n = len(prices) if n <...
class Solution: def longestPalindrome(self, string: str) -> str: result = "" for i in range(len(string)): odd_palindrome = self.find_odd_palindrome_from_center(string, i) if len(odd_palindrome) > len(result): result = odd_pal...
no = [1, 2, 3, 4, 5] color = ['red', 'yellow', 'orange', 'silver', 'purple', 'green'] print(color[0:4]) print(color[-5:]) print(color[:3]) print(color[1:-3]) print(color[::2]) nos = [1, 2, 3, 4, 5] nos[1:3] = ['a...
import sys def calc(prev, current, target): Kp = 20 Ki = 0.5 p = (target -current) * Kp i = ((target-current) + (target-prev))*10/2*Ki print("{:.3f}\tp={:.2f} i={:.2f} power={:d}".format(current, p, i, int(p+i))) prev = float(sys.argv[1]) current = float(sys.argv[2]) target = float(sys...
code = input('Please enter the ISBN-13 number with or with \'-\'s: ') codex = '' for each in code: if each is '-': pass else: codex = codex + each code = codex code = code[::-1] code_even = code[1::2] code_odd = code[::2] total = 0 for x in code_odd: y = int(x) total = total + (y * ...
print("Perhatikan bentuk berikut") print("-" * 19) print("| a mod b = hasil |") print("-" * 19) a = int(input("Masukkan a : ")) b = int(input("Masukkan b : ")) if (a > 0 and b > 0) or (a < 0 and b < 0): hasil = a - int(a/b) * b elif (a == 0 and b >= 0): hasil = 0 elif a > 0 and b == 0: hasil = a elif a < ...
Nama = str(input('Masukkan Nama Anda : ')) Nilai = int(input('Masukkan Nilai Anda : ')) if Nilai < 60 : print('Halo,', Nama ,'!', 'Nilai Anda setelah dikonversi adalah E') elif 60 <= Nilai <= 64 : print('Halo,', Nama ,'!', 'Nilai Anda setelah dikonversi adalah C') elif 65 <= Nilai <= 69 : print(...
numero_do_func = int(input()) numero_horas = int(input()) valor_hora = float(input()) horas_x_valor = numero_horas*valor_hora print(f"NUMBER = {numero_do_func}") print(f"SALARY = U$ {horas_x_valor:.2f}")
a = [1, 5, 'Good', 'Bad'] b = [9, 'Blue', 'Red', 11] print(a[1]+b[3]) print(a[2]+b[2]) print(a[0]*b[0]) print(a[1]**b[3]) print(a+b)
from random import * import matplotlib.pyplot as plt import numpy as np N=int(input("Saisir le nombre de tirage : ")) l=np.array([0]*20) for i in range(N): S=0 for d in range(3): S=S+randint(1,6) l[S]=l[S]+1 print ("---") for i in range(len(l)): print(l[i]) z = len(l) x = range(z) plt.bar(x,l) plt...
def even_or_odd(): number = int(input("Enter number:")) if number % 2 == 1: print("{} is odd".format(number)) elif number % 2 == 0: print("{} is even".format(number)) even_or_odd()
class create(object): def original_key(self, key, msg): temp = [] for i in range(len(msg)): temp.append(msg[i]/key[i]) return temp class convert_from(object): def string_to_int(self, array): converted_array = [] array = array.split(", ") for i i...
x = input("Put your number here please:") def func1(x): try: return float(x) except (ValueError): print("Enter the number please.") print(func1(x))
from Card import Card from Card import colors from Card import numbers from random import shuffle class Deck(object): def __init__(self, difficulty): self.cards = [] self.frequencies = [3, 2, 2, 2, 1] self.excluded_colors = ["Unknown"] if difficulty == "Normal": ...
import numpy as np import cv2 import matplotlib.pyplot as plt class NeuralNetwork(): def __init__(self): self.weights = np.random.uniform(-1, 1, size = 1) def segmoid(self, x): return 1 / (1+ np.exp(-x)) def segmoid_derivative(self, x): return x * (1 - x) def train(self, t...
from stack import Stack def is_match(p1, p2): if p1 == '[' and p2 == ']': return True elif p1 == '{' and p2 == '}': return True elif p1 == '(' and p2 == ')': return True else: return False def is_paren_balanced(paren_string): s=Stack() is_balanced=True ...
def minmaxArray(list): x = list[0] y = list[1] if x>y: max=x min=y else: max=y min=x for i in range(2,len(list)): if max < list[i]: max= list[i] elif min > list[i]: min=list[i] return min,max A = [-1,9,0,1, 2, 3, 4, 5, 6,-...
class Trie: def __init__(self): self.root = dict() def insert(self, s: str): traverse = self.root for char in s: if not traverse.get(char): traverse[char] = dict() traverse = traverse.get(char) traverse['*'] = '*' ...
""" Created on 28.03.2019 @author: christian.geissler@gt-arc.com """ ''' A small, simple dirty dictionary database class, that can be used to simply store, save and load data to/from .json. The data is stored in a tree of dictionaries that are automatically created when referenced by a "store" method call. ...
def game(): markers = [[],[]] player = 0 board = [['','',''] , ['','',''], ['','','']] remainingPositions = 9 hasWon = False def init(): markers[0] = input('Player 1 choose your marker: ').upper() markers[1] = input('Player 2 choose your marker: ').upper() def placeInputOn...
if "dog" in "dog": print(True) else: print(False) if "dog" in "god": print(True) else: print(False)
import numpy as np def best_k(nums): biggest = 0 for k in range(0, len(nums) + 1): new_biggest = funkcja(nums, k) if biggest == 0: biggest = new_biggest else: biggest = max(biggest, new_biggest) if type(new_biggest) is str: return new_bigge...
import unittest def is_palindrome(x): x_copy = x rev_x = 0 while x_copy != 0: rev_x *= 10 rev_x += x_copy % 10 x_copy //= 10 return rev_x == x class MyTest(unittest.TestCase): def test_simple(self): self.assertFalse(is_palindrome(12345)) ...
import sys _state = None class MyFileInput(): def __init__(self, files=[]): files_to_read = files if not files_to_read: if len(sys.argv) > 1: files_to_read = sys.argv[1:] if not files_to_read: files_to_read = ['-'] self.__filenameiter = ...
import unittest import random def same_bits_successor(n, width): """ width is the max number of bits we will permit in any successor. """ assert n < 2 ** width if n == 0: return n_str = bin(n)[2:] bits = list(map(int, n_str)) bits = bi...
from copy import deepcopy def run_command(program, ip, acc): command, arg = program[ip] if command == "acc": acc += int(arg) elif command == "jmp": ip += int(arg) - 1 elif command == "nop": pass ip += 1 return ip, acc def run_program(program, acc, print_on_loop): ...
from Card import Card def show_score(card): if card.owner == 'Player': print(f'Your hand is worth {card.points}.') else: print(f'The computer\'s hand is worth {card.points}.') def winner(player,computer): if player.points > computer.points: print(f'\nCongratulations! You beat the c...
d1={"a":1,"b":2,"c":3,"d":4} d2={"b":2,"d":4,"f":6,"g":7} d3={} def disJoint(): union=dict(d1.items() | d2.items()) intersection=dict(d1.items() & d2.items()) d3=dict(union.items() ^ intersection.items()) return d3 print(disJoint())
""" Program for solution problem 9A """ def calculate_probability(): input_numbers = [x for x in input()] big_number = input_numbers[0] if input_numbers[0] >= input_numbers[2] else input_numbers[2] probability = { '1': '1/1', '2': '5/6', '3': '2/3', '4': '1/2', '5'...
def find(parent, u): if u == parent[u]: return u parent[u] = find(parent, parent[u]) print(parent) return parent[u] def merge(parent, u, v): u = find(parent, u) v = find(parent, v) if u == v: return True parent[u] = v return False def solution(n, connections): answer = 0 parent =...
n = 4 def find_not_exist_nums(matrix): nums = [] exist = [] for i in range(n*n+1): exist.append(False) for i in range(0, n): for j in range(0, n): if matrix[i][j] != 0: exist[matrix[i][j]] = True for i in range(1, n*n+1): if ex...
x = lambda: input().lower() a = x() b = x() if a==b: print(0) for i in range(len(a)): if(a[i] > b[i]): print(1) break elif(a[i]<b[i]): print(-1) break
""" 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=[] for i in range(len(inputString)): if (inputString[i] == '('): s.ap...
""" Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. Y...
""" Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. """ def adjacentElementsProduct(inputArray): product=0 for i in range(0,len(inputArray)-1): if inputArray[i]*inputArray[i+1]>product or product==0: product=inputArray[i...
""" 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): n=list(map(int, str(n))) l=len(n) return sum...
import csv def loadCsv(filename): lines = csv.reader(open(filename, "r")) dataset = list(lines) for i in range(len(dataset)): dataset[i] = [float(x) for x in dataset[i]] return dataset
a=input("輸入一整數序列為:").split(' ') tmp=[] ans=0 for i in a: if tmp.count(i)==0: tmp.append(i) for i in tmp: if a.count(i) >= len(a)/2: ans=i if ans ==0: print("過半元素為:NO") elif ans != 0: print("過半元素為:{}".format(ans))
''' Question No. 8 Write a function that takes a list of integers and returns the largest sum of non-adjacent numbers. For example: input:[2,4,6,2,5] ----> Output:13===>2+6+5 input:[5,1,1,5] ----> Output:13===>5+5 ''' def LargeSum(l): incl = 0 excl = 0 for i in l: new_excl = max(excl, incl) ...
from IPython.display import Image Image(filename='img.png') adj =[[0,1,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,0,0,0,1,0,1,0,0], [0,1,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,1,0], [0,0,0,0,1,1,0,0,1], [0,0,0,0,0,0,1,0,0]] i=...
import pandas as pd path = '/home/aniekan/Downloads/numbers2.csv' df = pd.read_csv(path, names=['Data','Index']) df1 = df.reset_index() print("value of df1") print(df1) print("value of k") print("value of df1 tail") print(df1.tail(2)) print("value of df max") print(df.max()) print("checking "...
def printLarg(): x = input("Enter your first number: ") y = input("Enter your second number: ") holder=[x,y] larg = max(holder) print("the larger number is : ") print(larg) return larg printLarg()
def main (): word = input("Please enter an English word: ") vowels = "AEIOUaeiou" if word[0] in vowels: print(word + "yay") else: print(word[1:] + word[0] + "ay") main ()
def count(count): check = 1 for i in range(len(count)): if (i+1 < len(count)) and count[i] != " " and count[i+1] == " ": check = check + 1 return check def test_palindromeTrue(): assert count("maam") == 1 assert count("hi everyone") == 2 assert count("what up bud") == 3 d...
import numpy as np class Barrier(object): ''' This class prevents the agent from going outside the exploration space ''' def __init__(self, explr_space, pow=2, weight=100): self.explr_space = explr_space self.dl = explr_space[1,:] - explr_space[0,:] self.pow = pow ...
import numpy as np import matplotlib.pyplot as plt import math T=100 record=[0] customer=[0] server=[0] time=0 state=-1 maxi=0 while(time<T): if(state==-1): customer=np.random.exponential(0.5,1) time+=customer state+=1 server=np.random.exponential(0.25,1) customer=np.random.exponential(0.5,1...
n = 1 name = 'Sung' n = n + 2 value = 1.2 * n greeting = 'Hello World' numbers = [0, 1, 2, 3] names = ['Kim', 'Lee', 'Park', 'Choi'] array = numbers + names array[3] = 7 person = ('Kim', 24, 'male') print(person) print(person[1]) name, age, gender = person print(gender) print('github 추가 내용입니다.')
inventory = input().split() while True: data = input().split() if data[0] == 'Fight!': break command = data[0] equipment = data[1].split('-')[0] if command == 'Buy' and equipment not in inventory: inventory.append(equipment) elif command == 'Trash' and equipment in inventory: ...
data = input().split('|') data.reverse() list_result = [] for item in data: list_result.extend(item.split()) print(' '.join(list_result))
list_specials = [',', ';', ':', '.', '!', '(', ')', '\"', '\'', '\\', '/', '[', ']'] list_lower = [] list_mixed = [] list_upper = [] data = input() for item in list_specials: data = data.replace(item, ' ') list_data = data.split(' ') for item in list_data: if item != '': if item == item.upper() and...
import re search = input() result = [] sentence_pattern = r'^[A-Z].*[.!?]$' while True: data = input() if data == 'end': break if re.match(sentence_pattern, data): words = re.findall(r'\w+', data) for item in words: symbols = re.findall(search[0], item) if ...
""" Created on Thu Sep 24 12:53:56 2020 @author: DELL """ n = 2 for i in range(1, 11, 1): product = n*i print(product)
def repeatedCharacter(string): i = 0 c = 1 retString = "" while i != len(string): if i != len(string) - 1 and string[i] == string[i + 1]: c = c + 1 elif i != len(string) - 1 and string[i] != string[i + 1]: retString = retString + ...
def file_example(): with open('cool_file_name.format') as my_file: my_file.write('Hello, world!') pass def iostream_example(): my_stdout = StringIO() with redirect_stdout(my_stdout): print('Hello, world!') pass def combine...
def print_two(*args): arg1, arg2 = args print("arg1: %r, arg2: %r" % (arg1, arg2)) def print_two_again(arg1, arg2): print("arg1: %r, arg2: %r" % (arg1, arg2)) def print_one(arg1): print("arg1: %r" % arg1) def print_none(): print("I got nothin'.") print_two("Ben", "Millar") print_two_again("Ben",...
def main(): str = "abcde" result = isUniqueChars(str) print("Unique") if result else print("Not Unique") def isUniqueChars(str): if len(str) > 128: print(len(str)) return False else: charByte = bytearray() for char in str: return False if ord(char) in c...
''' Inew = trapezoid(f,a,b,Iold,k). Recursive trapezoidal rule: old = Integral of f(x) from x = a to b computed by trapezoidal rule with 2ˆ(k-1) panels. Inew = Same integral computed with 2ˆk panels. ''' import math def trapezoid(f,a,b,Iold,k): if k == 1:Inew = (f(a) + f(b))*(b - a)/2.0 else: n = 2**(k...
import csv def csv_dict_reader(file_obj, delimiter=','): reader = csv.DictReader(file_obj, delimiter=delimiter) for line in reader: print(line) print("__________") print(line["first_name"]) print(line["last_name"]) print("__________") with open("data.csv", "r") as file_obj: csv_dict_reader(...
class TicTacToe : def __init__(self) : self.board = [".", ".", ".",\ ".", ".", ".",\ ".", ".", "."] self.current_turn = "X" def set(self, row, col): if self.get(row, col) == ".": self.current_tur...
def add_some(servers): """ - voeg Helsinki toe aan het einde van de lijst - voeg ~Madrid~ toe tussen ~Tokyo~ en ~Paris~ """ def get_five_letter_servers(servers): five_letter_names = ['Paris'] '''Doorloop de list servers. indien de lengte van de servernaam lengte 5 heeft, voeg ...
print("Hello Python!") int1 = 10 + 10j int2 = 20 + 5j int3 = int1 * int2 print(int3) print(5 / 3) print(5 // 3) str1 = "Apple" print(str1[0]) print(str(len(str1))) print(str1.replace("p", "x") + " " + str1.upper() + " " + str1.lower() + " " + str1.swapcase()) tuple1 = ("A", "B", 1, 2, 3.14, 2.73) print(ty...
import pandas as pd xlsx_path = 'test.xlsx' df = pd.read_excel(xlsx_path) y = df.keys() print(y) z = df[['phone']] print(z) a1 = df['postal'].unique() print(a1) print("Length of A1: " + str(len(a1))) a2 = df['ccnumber'] >= 4903431815520553 print(a2) a3 = df[df['ccnumber'] >= 4903431815520553] print("Len...
import numpy as np arr = np.arange(0,11) print(arr[4]) print(arr[1:5]) print(arr[5:]) arr[0:5]=100 print(arr) arr = np.arange(0,11) arr_copy = arr.copy() arr_copy[:] = 100 print(arr) print(arr_copy) arr_2d = np.array([[5,10,15], [20,25,30], [35,40,45]]) print(arr_2d) print(arr_2d[0][0]) print(arr_2d[2,2]) ...
import csv weather_dataset = [] with open('enjoysport.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: weather_dataset.append(row) dataset_attributes = ['Sky', 'AirTemp', 'Humidity', 'Wind', 'Water', 'Forecast'] target_concept = ['0', '0', '0', '0', '0', ...
class Base(object): def __init__(self): print('----Base init----') def get_base(self): return 'Base' def test(self): print('----Base test----') @classmethod def test_class_method(cls): print('----Base class method----') @staticmethod def test_static_meth...
import socket from threading import Thread class ServerThread(Thread): """ 服务端线程类 """ def __init__(self, sock, c_addr): super().__init__() self.__sock = sock self.__c_addr = c_addr def run(self): while True: ret = self.__sock.recv(1024) ...
def f1(): a = [i for i in range(10)] print(a) b = a[::2] print(b) a = set(a) b = set(b) print(type(a)) print(type(b)) b.add(3) b.add(5) b.add(10) print(a & b) print(a | b) print(a ^ b) print(a - b) print(b ^ a) print(b - a) print() def main(...
import types class Person(object): def __init__(self, name, age): self.name = name self.age = age pass def test01(): num = 10 print(locals()) def test02(): p1 = Person('p1', 20) print(p1.name) print(p1.age) p1.address = '背景' print(p1.address) ...
import threading from threading import Thread from queue import Queue import time class Factory(Thread): """ 工厂类 """ def __init__(self, queue): super().__init__() self.queue = queue pass class Producer(Factory): """ 生产者类 """ def run(self): while ...
def test01(num1): print("----test01----") def test(num2): return num1 + num2 return test def test02(): fun1 = test01(100) fun2 = test01(1) print(fun1(100)) print(id(fun1)) print(id(fun2)) a = test01 b = test01 print(a == b) print(a is b) print(id(a)) ...
def decorator(fn): """ 这是一个通用方法装饰器,可以用来装饰无参无返回值、无参有返回值、有参无返回值、有参有返回值的方法 :param fn: :return: """ def inner(*args, **kwargs): print('----inner----') return fn(*args, **kwargs) return inner @decorator def f1(): print('----f1----') @decorator def f2(*args, **kwargs...
class Animal: def __init__(self): pass def eat(self): print('.....eating.....') class C(Animal): def __init__(self, name='Haha', age=15): super().__init__() pass def eat(self): print('=====eating=====') super().eat() def drake...
import os def f1(): while True: pass def main(): t = (1, 2, 3) if t and len(t) % 2 == 0: print('s') pass if __name__ == '__main__': main()
class A: def __init__(self): self.num = 100 self.__num = 200 def test01(self): print('----test01----') def __test02(self): print('----test02----') def test03(self): self.__test02() class B(A): def __init__(self): super().__init__() pass d...
def f1(): """ 这是最简单的用type方法来创建类 :return: """ Bird = type('Bird', (), {'name': 'haha'}) bird1 = Bird() print(Bird.name) pass def main(): f1() pass if __name__ == '__main__': main()