text
stringlengths
37
1.41M
import logging import threading import time logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-2s) %(message)s') class Taller(object): def __init__(self, start=0): self.condicionMangasMAX = threading.Condition() self.condicionMangasMIN = threading.Condition() ...
#Программы,которые предстоит мне сделать #Нормальный калькулятор с интерфейсом #Змейка #Тетрис #Игру, где нужно угадать число, загаданное компьютером #Сумма натуральных чисел в заданном диапазоне. Дата: ? num = [] for value in range(1,3002): num.append(value) print(sum(num)) #Игра где нужно угадать ч...
def soma(entradas, pesos): soma = 0 for i, j in zip(entradas, pesos): soma += i * j return soma def step_function(soma): return soma >= 1 entradas = [-1, 7, 5] pesos = [0.8, 0.1, 0] soma = soma(entradas, pesos) print("Resultado da soma:") print(soma) resultado = step_function(soma) print("R...
import socket import time HEADERSIZE = 10 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #AF_INET = ipv4, Stock_stream = tcp s.bind((socket.gethostname(),1239)) # 1234 --> PORT Number ## The bind() method of Python's socket class assigns an IP address and a port number to a socket instance. The bind() method is...
# Task # You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. # Function Description # Complete the split_and_join function in the editor below. # split_and_join has the following parameters: # string line: a string of space-separated words # Returns # string: the resulting str...
squares = [1, 4, 9, 16, 25] squares.append(36); print(squares) print(squares[1]) print(squares[-3:]) # return a new copy of the list sq = squares[:] squares.append(49) print(sq) squares = squares + [36, 49, 64, 81, 100] print(squares) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] letters[2:5] = ['C', 'D', 'E'] print...
""" Helpers """ import time from functools import wraps class TimeRec: """ Calculate time of excecution. How to use it: tm = TimeRec() # (1) ... exec_time = tm.step() # (2) exec_time is time from (1) to (2) ... exec_time2 = tm.step() # (3) exec_time is time f...
# The basic approach of this alogorithm is to rollback to previous step if the current step is not going to give you a correct solution def can_be_extended_to_solution(perm): """This function checks whether the solution is correct i.e if any the queen placed in current step is attacked by previously placed queens ...
#!/usr/bin/python """ Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess? Input format The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid....
#!/usr/bin/env python3 from random import randint, choice from ships import * import sys from time import sleep #Text to help the player with the how-to of the game def ui(): """Includes How-to-play of the original board game. Just some stuff to be printed. Not much!""" print("Hello!") print("--...
#!/usr/bin/env python3 import sys import math from common import print_solution, read_input def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) def solve(cities): N = len(cities) dist = [[0] * N for i in range(N)] for i in range(N): for j ...
import pandas as pd import json from pymongo import MongoClient def write_in_mongodb(dataframe, mongo_host, mongo_port, db_name, collection): """ :param dataframe: :param mongo_host: Mongodb server address :param mongo_port: Mongodb server port number :param db_name: The name of the database ...
import pandas as pd import requests def fetch(url): params = dict( origin='Chicago,IL', destination='Los+Angeles,CA', waypoints='Joplin,MO|Oklahoma+City,OK', sensor='false' ) resp = requests.get(url=url, params=params) data = resp.json() return data def json_to_dataf...
import matplotlib.pyplot as plt import numpy as np import math def love7(): x = np.linspace(-2, 2, 1000) f = np.sqrt(2 * np.sqrt(x * x) - x * x) g = -1 * 2.14 * np.sqrt(math.sqrt(2) - np.sqrt(np.abs(x))) plt.plot(x, f, color='red', linewidth=2) plt.plot(x, g, color='red', linewidth=2) plt.tit...
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. #22/9/20 import datetime x = datetime.datetime.now().strftime("%y") xi = datetime.datetime.now().month print(x) print(xi) class MyNumbers: def __iter__(self): self.a = 1 return s...
from turtle import * from random import random from freegames import line def draw(): "Draw maze." color('black') width(5) for x in range(-200,200,40): for y in range(-200,200,40): if random() > 0.5: line(x,y, x + 40 ,y + 40) else: line(x,y+40, x+40 , y) update(...
class myclass(): def __str__(self): return "4" print(myclass()) def my_function(fname,lname): print(fname + lname+" Refsnes") my_function("Emil","ee") my_function("Emiel","ee") def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias"...
# -*- coding: utf-8 -*- """ Created on Wed Apr 25 16:53:41 2018 @author: root """ """ animate the contour of a field in a surface. input: *field*: the field you want to animate *extension*: the slice surface you want to animate *proc*: the processor number that slices data from *filename*: th...
import sys def reverse_txt(file_name): f = open(file_name, "r") lines = f.readlines() f.close() f = open(file_name, "a") for i in range(len(lines) - 1, -1, -1): f.write(lines[i]) f.close() if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python3 reverse_txt.py <txt_file>") else: file = sy...
""" To evaluate the good or bad score of a tweet, we first tokenize the tweet, and then stemmize each word in our tweet. We also associate each stem with positive and negative values, respectively, using a dictionary. Finally, we caculate the average word weight of a tweet, and decide if it's a good or bad one based on...
""" 1. Requirement: Create an API Service to fetch the statistics of the contributors of user specified GitHub repositories in the Amazon Web Services Environment. 2. Identify and list unique domains to the specified repository and sort them by the number of commits per contributor for all the branches. 3. The Rep...
#!/usr/bin/env python #-*- coding:utf-8 -*- # li1 = [1,2,3] # print(li1) # # li2 = ["a", "sdf", li1, [6,7,8]] # print(li2) # # li2[0] # # li2.append("world") # print(li2) # # li2.remove("sdf") # print(li2) # # del li2[0] # print(li2) # # li1 # del li1 # #li1 # # li1 = [1,2,3] # li1 # li1.clear() #清空列表,列表为空但是仍存在 # li1...
#!/usr/bin/env python #-*- coding:utf-8 -*- # author:Administrator # datetime:2018/12/16 9:33 # software: PyCharm import socket class ClientSocket: def __init__(self): self.client = socket.socket() def conn_server(self): # self.client.connect(('192.168.2.125',8888)) self.client.conne...
# TODO # 1. Create a list of "person" dictionaries with a name, age, and list of hobbies for each one <**DONE**> # 2. Use a list comprehension to convert this list of persons into a list of names (of the persons) <**DONE**> # 3. Use a list comprehension to check whether all persons are older than twenty <**DONE**> # 4....
""" Algorithms.py ==================================== Module containing all graph algo i use in my Graph-rendering project """ import collections from typing import Optional from graph.Graph import Graph from graph import GifMaker def graph_pass_and_gif(graph: Graph, node: int, method, draw=False) -> list: """...
################# # # get_program_version # written by: Andy Block # date: Jan 3, 2021 # ################# # # this program simply prints out the version number of a given Windows executable. # the only argument required is the file path of the exexcutable you want the version of. # # for example, the file path for chr...
# practice 4 user_input = int(input("Enter a number:")) i = 0 for i in range(user_input): i = user_input*2 user_input += user_input print(i)
#Problem: Extracting data from XML #visit this url for the problem - https://www.py4e.com/tools/python-data/?PHPSESSID=f2d57a1839533b3bf8e7129dcb08d0e0 import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET input_url = input('enter URL - ') data = urllib.request.urlopen(input_ur...
a=input("enter a string to reverse : ") revs="" for s in a: revs=s+revs print(revs)
a=[1,3,2,4,5,6,5,8] import collections print([item for item, count in collections.Counter(a).items() if count > 1])
import random import math class Electric: def __init__(self, name): self.name = name class Load(Electric): def __init__(self, name, resistance, reactance): super().__init__(name) self.resistance = resistance self.reactance = reactance self.__n = (random.randint(1, 1...
# Permutations # Given a collection of numbers, return all possible permutations. # For example, # [1,2,3] have the following permutations: # [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. class Premu: dlist = [1,2,3] vlist = [0,0,0] rlist = [] def __init__(self): pass def __del__(self): pass d...
# File Name: days_in_month.py # Name: Kit Wei Min # Description: Displays the number of days in the month of a year entered by the user. # Prompts user to input the month and year. yr = int(input("Enter a year: ")) mth = int(input("Enter the month: ")) # Determines the number of days in the month of the year entered...
# Filename : ASCII_character # Name : Kit Wei Min # Description : Displays the character of an ASCII code. # Prompts for an ASCII code code = int(input("Enter ASCII code (between 0-127 exclusive): ")) # Converts ASCII code character = chr(code) print("Character of code: " "{0}". format(character))
#!/usr/bin/python import sys from datetime import datetime COLOURS = [1,2,3,4,5,6,7] class rainbow: """ The rainbow class provides static, scrolling or pulsating rainbow colouring of text. Exports pulsebar() and scrollbar(). """ odd = speed = colidx = lasttime = -1 def __init__(self, fps=10):...
#Desenvolva um programa que pergunte a distancia de uma viagem em KM. #Calcule o preço da passagem, cobrando R$0,50 por km para viagens de ate 200 Km # e R$0,45 para viagens mais longas. dist = float(input('Qual a distancia em Kilometros até o seu destino? ')) if dist <= 200.00: d1 = dist * 0.50 print(f'O valo...
#Crie um programa que leia um numero real qualquer pelo teclado e mostre na tela a sua porção inteira #ex: Digite um numero 6,127 "O numero 6,127 tem a parte inteira 6" from math import trunc num = float(input('Digite qualquer valor: ')) print(f'O valor de {num} tem como numero inteiro {trunc(num)} ')
#Crie um programa que leia o nome de uma pessoa e diga se ela tem "silva" no nome name = str(input('Digite o seu nome completo? ')).strip().title() n1 = name.split() print(f'Seu nome completo é {name} e é {"Silva" in n1} que vc tem Silva no seu nome ')
users = [ { 'name': 'Rolf', 'age': 34 }, { 'name': 'Anna', 'age': 28 } ] def print_users_list(user_list): for i, user in enumerate(user_list): print_user_details(i, user) def print_user_details(number, user): print("{} | name: {}, age: {}...
# -*- coding: UTF-8 -*- import numpy as np from scipy.integrate import quad # Funcion a integrar: cos²(e^x) def f(x): return np.cos(np.exp(x)) ** 2 # Integrar la función en los límites 0, 3 # quad devuelve un arreglo con 2 elementos: el primero, la solución # el segundo, el error solucion = quad(f, 0, 3) print...
# -*- coding: utf-8 -*- import pylab as pl # Definición de funciones auxiliares def f1(x): return x**2 def f2(x): return x**3 def f3(x): return 1./x def f4(x): return pl.sqrt(x) X = pl.arange(1,100) fig = pl.figure("Varios plots") # Vamos a crear un grid de 2x2 con 4 subplots sp1 = fig.add_subplot...
import pandas as pd from sklearn.cluster import KMeans def kmeans(): df = pd.read_csv('clusters.txt', names=['x','y']) # initialize the KMeans class with the # of clusters kmeans = KMeans(n_clusters=3) kmeans.fit(df) centroids = kmeans.cluster_centers_ print("Centroids:") for i in centroi...
phone = input('Phone: ') dict_phone = { '1':'One','2':'Two','3':'Three','4':'Four','5':'Five', '6':'Six','7':'Seven','8':'Eight','9':'Nine' } output = "" for ch in phone: output += dict_phone.get(ch,"!") + " " print(output)
#!/usr/bin/python2.5 from nltk.stem.wordnet import WordNetLemmatizer from nltk.corpus.reader import VERB from nltk.corpus.reader import NOUN from sys import stdin, argv if len(argv) == 2: splitby = eval(argv[1]) else: splitby = '\t' lemmatizer = WordNetLemmatizer() # # we assume the file is built of pos/wor...
# @author: Ashish Shetty aka AlphaSierra # Fibonacci sequence generator my implementation fibonacci_list = [0, 1]# List created with twi initial numbers hardcoded in it. Now ask user for input for ranging last = int(input("Please input the limit of Fibonacci series you want to enlist: ")) def fib():# define fib...
length=int(input("enter any length")) breadth=int(input("enter of rectangle")) if length==breadth: print("it is square") else: print("it is not square")
# Write a python program to enter two numbers and perform all arithmetic operations. num1=int(input("enter a num1")) num2=int(input("enter a num2")) sum=num1+num2 sub=num1-num2 mul=num1*num2 divide=num1/num2 mod=num1%num2 print(sum,"num1+num2") print(sub,"num1-num2") print(mul,"num1*num2") print(divide,"num/num2")...
girls=int(input("enter the girls =")) bed=int(input("enter the bed =")) if girls==bed: print("bed girls is equal") elif girls>bed: print("bed is less",girls-bed) else: print("girls is more",bed-girls) file=open("Q3.txt","a") file.write("navgurukul is the best place for learning") file.write('\n') file.c...
# Write a python program to calculate profit or loss. cost_price=int(input("enter a cost price ")) selling_price=int(input("enter a seeling price")) if cost_price>selling_price: print("profit") elif cost_price==selling_price: print("no profit no loss") else: print("loss")
def getminsteps(a): steps=[0 for x in range(len(a))] if(a[0]==0 or len(a)==0): return(float('inf')) for i in range(1,len(a)): steps[i]=float('inf') for j in range(i): if((i<=j+a[j]) and (a[j]!=float('inf'))): steps[i]=min(steps[i],steps[j]+1) ...
import math def check(a,b): ch=0 while(a%2==0): ch+=1 if(ch==b): return(2) a=a//2 for i in range(3,int(math.sqrt(a))+1,2): while(a%i==0): ch+=1 if(ch==b): ...
import math def check(a): out=[] while(a%2==0): out.append(2) a=int(a//2) for i in range(3,int(math.sqrt((a)))+1,2): while(a%i==0): out.append(i) a=int(a//i) if(a>2): out.appe...
import random import time class Game_2048(): """ This class represent gamegrid and function""" def __init__(self): """ Create new grid """ self.grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.score = 0 self.status = True self.max...
# Задание 2.3. # По аналогии с тем, как я поступил с факториалом, сделайте вывод каждого # шага вычисления функции fibo на экран, чтобы понять что реально тут # происходит и почему функция работает медленно. # def fibo(n): # if n == 0: return 0 # if n == 1: return 1 # return fibo(n - 1) + fibo(n - 2) # htt...
def mult(*args): result = 1 for arg in args: result *= arg return result print(mult(1,2,3,4)) def sumpowers(*args, power=1): result = 1 for arg in args: result *= arg ** power return result print(sumpowers(1,2,3,4)) print(sumpowers(1,...
def main(): print() i = 0 for i in range (0, 256): n = chr (i) print(str(i) + ":", end='') print(n) print() main()
var = input("var: ") try: var != int(var) except ValueError: print ("var is a str")
# LARISSA TENORIO E THALES VALDSON from random import shuffle def geraLista(tam): lista = list(range(1, tam + 1)) shuffle(lista) return lista def not_bubble_sort(lista): elementos = len(lista)/2 ordenado = False ordenado2= False while not ordenado: ordenado = True for i ...
def maxSubArray(nums): max_so_far = curr_so_far = -float('inf') for i in range(len(nums)): curr_so_far += nums[i] # Add curr number print('1',curr_so_far) curr_so_far = max(curr_so_far, nums[i]) # Check if should abandon accumulated value so far if it's a burden due to negative value acc...
# *-* encoding: utf-8 *-* import re from abc import ABC, abstractmethod from typing import Dict class Factor(ABC): @abstractmethod def __init__(self): pass @abstractmethod def compute(self, segment: str): """ Computes the factor on the tokens in the segment. """ ...
def checkio(*args): if len(args) == 0: return 0 big, small = args[0],args[0] for num in args: if num > big: big = num if num < small: small = num return big - small print(checkio(1,2,3)) # ! optimized def checkio(*args): if a...
def sort_by_ext(files): # your code here return files a = ['1.cad', '1.bat', '.aba','2.aa'] # => [['1', 'cad'], ['1', 'bat'], ['1', 'aa']] a = [x.split('.') for x in a] print(sorted(a,key=lambda k: (k[0],k[1]))) # ! checkio version def sort_by_ext(files): # no_name = [] res = sorted([x.sp...
def yaml(a): # your code here dic = {} # split based on \n # find pos of ':' [0:index] => key [index+1:]=>value # if value isdigit => int(value) a = a.split('\n') for word in a: # remove line without content if len(word): word = word.replace('"', '').replace...
import sys import urllib.request import os def main(): if (len(sys.argv) >= 3): filename = sys.argv[1] directory = sys.argv[2] if not os.path.exists(directory): os.makedirs(directory) f = open(filename, "r") i = 0 urls = f.readlines() for url in u...
WELCOME = "Welcome to the family, {}" PERSON_EXISTS = "Sorry {} already exists!" SPOUSE_EXISTS = "Sorry {} is already married!" RELATIONSHIPS = set(["father", "mother", "grandfather", "grandmother", "daughters", "sons", "brothers", "sisters", "uncles", "aunts", "cousins", "gran...
# encoding: utf-8; from __future__ import generators import re from tokenexceptions import * # # Token Class. Now we're getting somewhere. # class Token( object ): """ A Token is the smallest unit of a program that can be considered in abstraction. It has a type, which should probably be an Enu...
Nama = input(str("Masukkan Nama Anda: ")) Umur = int(input("Masukkan Umur Anda: ")) Tinggi = float(input("Masukkan Tinggi Anda (cm): ")) txt = "Nama saya {}, umur saya {} tahun dan tinggi saya {} cm".format(Nama, Umur, Tinggi) print(txt)
my_list = [1, 1, 1, 1] print(my_list) my_list[0] = 3 print(my_list) my_dict = { "nama" : "Andy", "umur" : "30" } print(my_dict)
#!/usr/bin/env python from __future__ import print_function from builtins import input from builtins import str import sys import pmagpy.pmag as pmag def main(): """ NAME stats.py DEFINITION calculates Gauss statistics for input data SYNTAX stats [command line options][< fil...
#!/usr/bin/env python from __future__ import print_function from builtins import input from builtins import str from builtins import range import sys import pmagpy.pmag as pmag def main(): """ Welcome to the thellier-thellier experiment automatic chart maker. Please select desired step interval and uppe...
def bubble_sort(arr:list, reverse=False): n = len(arr) if n <= 1: return if reverse: for i in range(n-1, -1, -1): for j in range(0, i): if arr[j] < arr[j+1]: tmp = arr[j] arr[j] = arr[j+1] arr[j+1] = tmp...
# 2019-9-24 class Solution: def domino(self, n: int, m: int, broken: list) -> int: # count <= n*m-1 # 返回下一个空白格的坐标 def get_next_ord(count: int): if count <= LIMIT: x, y = count // m, count % m #print(x, y) while not chess[x][y]: ...
# 2020-01-20 from typing import List class RedBlackTree: """ CLRS: 1. Each node is either red or black. 2. The root of a rbt is black. 3. Leaves are black. 4. A red node must have 2 black children. 5. For each node A, all simple paths from A to a descendant leaves, contain the same number ...
def merge_sort(arr:list, reverse=False): def inner_sort(left: int, right: int, rev=False): if left+1 < right: mid = (left + right) >> 1 inner_sort(left, mid) inner_sort(mid, right) merge(tmp_list, arr, left, mid, right, reverse) n = len(arr) if n == ...
import re def is_palindrome(text): return processing_text(text) == processing_text(reverse(text)) def reverse(text): return text[::-1] def remove_punctuation(text): return re.sub(r'[?!.\"\'\[\]();:\-\\,]', '', text) def remove_space(text): return text.replace(" ", "") def low_case(text): r...
""" CP1404/CP5632 Practical Demos of various os module examples """ import os def main(): """Process all subdirectories using os.walk().""" os.chdir('Lyrics') for directory_name, subdirectories, filenames in os.walk('.'): print("Directory:", directory_name) print("\tcontains subdirectorie...
"""Generate random grids """ import networkx as nx from .random_graph import cut_across, hidden_graph def random_grid(side, p_not_traversable=0.5, n_hidden=0, max_length=3): """ Generate a subgraph of a grid by removing some edges and declaring other edges as hidd...
from familytree import FamilyMember def create_tree_structure(): tree_root = FamilyMember('Nancy') tree_root.add_child('Nancy', 'Adam') tree_root.add_child('Nancy', 'Jill') tree_root.add_child('Nancy', 'Carl') tree_root.add_child('Carl', 'Catherine') tree_root.add_child('Carl', 'Joseph') t...
file = open ("words.txt") required = input ("Enter the alphabet:") def uses_all(words, required): for letters in required: if letters not in words: return False return True count = 0 tcount = 0 for line in file: tcount += 1 words = line.strip() if uses_all(words, required) == ...
file = open("words.txt") def avoids (words,forbidden): for letter in words: if letter in forbidden: return False return True forbidden = input ("Enter letter not to apprear: ") count = 0 wordcount = 0 for lines in file: words = lines.strip() wordcount +=1 if avoids(...
import math """Area of a square""" a = int (input("Enter the side for square's area:")) b = int (input("Enter the radius for circle's area:")) c = int (input("Enter the radius for sphere's area:")) def area_square(side): area_square = side * side return area_square """Area of a circle""" def area_circle(radiu...
class point: """this is a point class""" def __init__(self,x,y): """constructor for point""" self.x = x self.y = y def __str__(self): return ("The point is" + str (self.x) + "," + str (self.y)) def __add__(self,other): my_point = point (self.x+other.x,self.y+other...
from pyspark.sql import SparkSession spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate() data = ["Project Gutenberg’s", "Alice’s Adventures in Wonderland", "Project Gutenberg’s", "Adventures in Wonderland", "Project Gutenberg’s"] rdd = spark.sparkContext.paralleli...
import math def binary_numbers(a): alist = [] digits = a numbers = 2**digits-1 for i in range(numbers+1): a = list(bin(i)) a = a[2:][::-1] for i in range(digits-len(a)): a.append(0) for i in range(len(a)): a[i] = int(a[i]) ...
def eat_junk(food): assert food in ["pizza", "shaworma", "ice_cream"] , "food must be junk food" return f"NOM NOM NOM I am eatin {food}" food = input("enter a food please:") print(eat_junk(food)) def add(a,b): """ >>> add (2,3) 5 >>> add(100 ,200) 300 """ return a+b with open("...
def square_of_6(): return 6**2 result = square_of_6() print(result) from random import random def flip_coin(): r=random() if r>0.5: return "Heads" else: return "Tails" print(flip_coin()) def square(num): return num*num print(square(5)) print(square(2)) def number_default(num, po...
from datetime import * def diffDate(x): x = x.split('-') tgl= date(int(x[0]),int(x[1]),int(x[2])) datenow = datetime.date(datetime.now()) result = tgl - datenow result = result.days print("Tanggal sekarang : ",datenow) print("Tanggal yang diminta : ",tgl) print("Selisih ...
cake = input("Do you want cake? (yes or no)") if cake == "yes" or cake == "Yes" or cake == "y": print("have some cake") elif cake == "no" or cake == "No" or cake == "n" : print("no cake for you!!!") else: print("Nope: sorry, I dont understand")
import random """ 3.6 3.08 3.092 3.142 3.1422 3.141512 3.1401636 3.14184416 10^8 losowan """ def in_circle(x, y): return x ** 2 + y ** 2 < 1 def calc_pi(n=100): inside_count = 0 for _ in range(n): if in_circle(random.random(), random.random()): inside_count += 1 pi = (inside_cou...
import random import math import cmath def swap(L, left, right): """Zamiana miejscami dwoch elementow na liscie.""" item = L[left] L[left] = L[right] L[right] = item def random_list(size, maxVal): return [random.randint(0,maxVal) for r in range(size)] def nearly_sorted(size, maxVal): ...
"""Iterator Pattern""" """ 迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。 这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。 """ """ 意图: 提供一种方法 -> 顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。 主要解决:不同的方式来遍历整个整合对象。 何时使用:遍历一个聚合对象。 如何解决:把在元素之间游走的责任交给迭代器,而不是聚合对象。 关键代码:定义接口:hasNext, next。 应用实例: JAVA 中的 iterator。 ...
class Node: def __init__(self, data,next=None,previous=None,child=None): self.data = data self.next = next self.previous = previous self.child = child def printListRecursive(head, level=0): aux = head while aux is not None: print " "*level +...
import time # Square of Sum def sq_o_sm(n): start = time.time() sum_10 = 55 for i in range(1,n//10): new_sum = int(str(i)+"00")+55 sum_10+=new_sum square_of_sum = sum_10**2 return square_of_sum,start square_of_sum,time_tkn = sq_o_sm(100) print("Time taken: {} milliseconds".format((time.time()-time_tk...
from math import pi from time import sleep #Problem 1 - Count even integers in list def count_evens(L): count = 0 for i in L: if i % 2 == 0: count+=1 return count #Problem 2 - List to string without str(list) def list_to_str(lis, separator=', '): #List start s = "[" #Items ...
#------------------------------------------------------------------------------- # Name: quickSort.py # Purpose: Implementing the quickSort algorithm for different values of pivot. # # Author: Denado Rabeli # # Created: 12/06/2020 # Copyright: (c) denad 2020 # Licence: <your licence> ...
#------------------------------------------------------------------------------- # Name: Shopping List (Summative) # Purpose: # # Author: Ryelee McCoy # # Created: 11/10/2019 # Copyright: (c) ryelee.mccoy 2019 # Licence: <your licence> #----------------------------------------------------------------...
#!/usr/bin/python class Heap: def __init__(self, a): self.a = a self.size = len(a) def max_heapify(self, i): while 1: l = i * 2 + 1 r = i * 2 + 2 largest = i if l < self.size and self.a[l] > self.a[i]: largest = l ...
#!/usr/bin/env python import random def random_sampling_no_duplicate(a, n): for i in range(n): index = random.randint(i,len(a)-1) a[i],a[index] = a[index],a[i] return a[:n] def random_sampling_with_duplicate(a, n): result = [] for i in range(n): index = random.randint(0,len(a)-...
############################################################## # server.py # Part of UnSH, and insecure protocol to connect devices. # # Michael Yoder # v. 1.0 ############################################################## import socket import os import sys import subprocess import struct HOST = '' ''' Command line...
from tkinter import * def sum(): r.set(float(n1.get()) + float(n2.get())) def subtraction(): r.set(float(n1.get()) + float(n2.get())) def multiplication(): r.set(float(n1.get()) + float(n2.get())) root = Tk() root.config(bd=15) n1 = StringVar() n2 = StringVar() r = StringVar() Label(root, text="Num 1").pack()...