text
stringlengths
37
1.41M
import dns.resolver import whois import sys #file with hostnames hostFile = "dns_file.txt" #read sys.argv arg=sys.argv #convert txt file to array def toArray(file): f = open("dns_file.txt", "r") arr = [fileLine.strip() for fileLine in f] f.close() return arr hostnames = toArray(hostFile) def getMX(): fo...
print("1. feladat") while True: try: ket_szam = input("Adjon meg 2 egész számot 0-100 között: ") a, b = ket_szam.split() a, b = int(a), int(b) if a < 0 or a > 100 or b < 0 or b > 100: raise Exception("Nem megfelelő szám!") if (a+b)/2 < 60: rai...
#Finding the number of divisors #Lets input a number first number=int(input("Enter a number: ")) print('Divisors Are:') divisor_counter=0 for i in range(1,number+1): if (number%i) == 0: divisor_counter+=1 print(i) print('Divisor Count=',divisor_counter)
# property()函數的作用是在新的類別中返回屬性。並且在裝飾法中,表示該屬性不能被更改。 # syntax: class property([fget[, fset[, doc]]]) # 參數 # fget -- 獲取屬性值的函數 # fset -- 設置屬性值的函數 # fdel -- 刪除屬性值的函數 # doc -- 屬性描述信息 # 定義一個可控屬性的x class C(object): def __init__(self): self._x = None def getx(self): """ The doc of getx ...
# enumerate()函數用於將一個可遍歷的數據對象(如列表,元組或字符串)組合為一個索引序列,同時列出數據和數據下標,一般用在for循環中。 # syntax: enumerate(sequence, [start=0]) # 參數: # sequence -- 一個序列 迭代器 或其他支持迭代的對象 # start -- 下標起始位置 # 返回值 # 返回enumerate(枚舉)對象。 seasons = ['Spring', 'Summer', 'Fall', 'Winter'] print("If there is not type for enumerate, it will return object...
def Btree_create(btree_deep, data): btree = [0]*pow(2, btree_deep) for i in range(1, len(data)): level = 1 while btree[level] is not 0: if data[i] > btree[level]: # if the max value is inside the tree, compare them with child tree level = level * 2 + 1 el...
# 筆記:一開始以為只是單純比較字符,後來發現題目用意是要比較兩邊字串內的元素均要一致!所以需要考驢到存在/存在個數於是決定用dictionary來做~ a = 'abbc' b = 'dog cat cat tiger' # b = 'abe' b = 'aebb' # since the original declaration of python is list, # no need to separate or claim an array to store it # check string length # check exists # check each elements length # create a m...
def hanoi(n, p1, p2, p3): if n == 1: # recursive exit print('ring move from %d to %d' % (p1, p3)) else: hanoi(n - 1, p1, p3, p2) print('ring move form %d to %d' % (p1, p3)) hanoi(n - 1, p2, p1, p3) j = int(input('please enter the total ring want to move: ')) hanoi(j, 1, 2, 3)...
MAXSTACK = 100 # define the max stack global stack stack = [None] * MAXSTACK # claim the stack array top = -1 # define the top of stack # check whether this is an empty stack def isEmpty(): if top == -1: return True else: return False # put data into stack def push(data): global top ...
# 檢索和替換 # re.sub 提供了re.sub用於替換字串中的匹配項 # syntax: re.sub(pattern, repl, string, count=0, flags=0) # par1: # pattern : 正則中的模式字符串 # repl : 替換的字符串,也可為一個函數 # string : 要被查找替換的原始字符串 # count : 模式匹配後替換的最大次數,默認0表示替換所有的匹配 # -*- coding: UTF-8 -*- import re phone = "2004-959-559 # 這是一個國外的電話號碼 ----- 4023985" # 删除字符串...
import random val = 0 data = [0] * 80 for i in range(80): data[i] = random.randint(1, 15) def bin_search(data, val): low = 0 high = 49 while low <= high and val != -1: mid = int((low + high) / 2) if val < data[mid]: print('%d is between %d[%3d] and %d[%3d] from left hand ...
import numpy as np x =np.random.normal(size=5) # 數據轉型 http://www.lianzai.me/article/285.html y=(x>0).astype(np.float) print(x) print(y) # 利用numpy的newaxis轉變矩陣的形狀 http://ben-do.github.io/2016/09/15/change-shape-of-matrix-by-numpy/ # print(x[:,np.newaxis]) # 將-5到10之間的數列等分成300個數字 # X_test = np.linspace(-5, 10, 300) # pr...
# # In Python, List is used as array data structure # list1 = [1, 2, 3] # print(type(list1)) # <class 'list'> # # list2 = [[1, 2], [3, 4]] # print(type(list2)) # <class 'list'> # import sys MAX = 10 queue = [0] * MAX front = rear = -1 choice = '' while rear < MAX - 1 and choice != 'e': choice = input('enter [a] t...
from chapter03_sort.show_data import show_data data = [16, 25, 39, 27, 12, 8, 45, 63] def select(data): for i in range(len(data) - 1): for j in range(i + 1, 8): if data[i] > data[j]: data[i], data[j] = data[j], data[i] print() print("Raw data is ") show_data(data) sele...
from abc import ABCMeta, abstractmethod class IStream(object): # python2 method # class IStream(metaclass=ABCMeta): #python3 method @abstractmethod def read(self, maxbytes=-1): # print('interface') pass @abstractmethod def write(self, data): pass class SocketStream(IStr...
# 考慮repl參數是一個函數的情況 # !/usr/bin/python # -*- coding: UTF-8 -*- import re # 将匹配的数字乘以 2 def double(matched): value = int(matched.group('value')) return str(value * 2) s = 'q(^(*+_341BA23G4HFD567' print(re.sub('(?P<value>\d+)', double, s))
list1 = [20, 45, 51, 88, 99999] list2 = [98, 10, 23, 15, 99999] list3 = [] def select_sort(data): size=len(data) for base in range(size): small = base for j in range(base + 1, size): if data[j] < data[small]: small = j data[small], data[base] = data[base], d...
import wikipedia import traceback while True: page = input("What wikipedia page do you want? \n") number = input("How many sentences do you want from said wikipedia page? \n") try: print(wikipedia.summary(page, sentences=int(number))) break except ValueError: ...
one = "1" zero = "0" one_hundred = int(one+zero+zero) useless = 0 while(useless < one_hundred): print("Useless "+str(useless+1)) useless = useless + 1 if 100 == useless: print("Uselessness unconfirmed") else: print("Uselessness confirmed")
# Написать функцию которая принимает на вход число от 1 до 100. Если число равно 13, функция поднимает исключительную # ситуации ValueError иначе возвращает введенное число, возведенное в квадрат. Далее написать основной код программы. # Пользователь вводит число. Введенное число передаем параметром в написанную функци...
# Решить с помощью генераторов списка. # 1: Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках. # # Примечание: Списки фруктов создайте вручную в начале файла. fruits1 = ['яблоки', 'груши', 'вишня', 'агава', 'клубника', 'манго', 'инжир', 'банан', 'ананас', 'черника', 'голубик...
""" Python Space Fighter Game - Powerup class Copyright 2008-2010 Kevin Lange <kevin.lange@phpwnage.com> Written for the Strongsville High School Computer Club This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as publis...
#!/usr/bin/env python # -*- coding:utf-8 -*- re = iter(range(5)) try: for i in range(4): print re.next() except Exception as StopIteration: print 'end come' else: pass finally: pass try: print 'abc StopIteration' raise StopIteration except StopIteration: print 'throw except' finally: print 'fina...
#!/usr/bin/env python # -*- coding:utf-8 -*- dictt = {'tom':11,'sam':37,'lily':100} print dictt['tom'] print type(dictt) dictt['tom'] = 40 print dictt['tom'] newdict = {} newdict['jery'] = 90 print newdict for key in dictt: print dictt[key] print dictt.keys() print dictt.values()
#!/usr/bin/env python # -*- coding:utf-8 -*- fun = lambda x : x + 3 print fun(9) def funclamb(f,a,b): print type(f) print f(a,b) return True print funclamb((lambda x,y : x*10+y),1,2) print map((lambda x : x*10 ),[1,4,5]) def filterfun(x): if x > 100 : return True else: return False print filter...
import string from copy import copy import numpy as np from cipher import Cipher class VigenereTableau(object): """ Generate the tableau used within the Vigenere cipher """ def __init__(self, alphabet=None, row_fill=0, col_fill=0): """ Parameters ---------- alphabet (...
print("hello world!")#hello world를 출력 print("안녕 파이썬!")#안녕 파이썬만 출력 x="안녕" y="파이썬" z=x+y print(x) print(y) print(x+y)
while True: v = int(input('Write value for converting seconds: ')) def converter(v): sec_value = v % (3600 * 24) min = sec_value * 60 print("Converted minute value to seconds: ", min) converter(v)
import math def getfstring(a, b): c = math.sqrt(a ** 2 + b ** 2) # print(a + '^2 '+ b +'^2 = ' + c + '^2') # says unsupproted operand # print(a, '^2 +', b, '^2 = ', c, '^2') return f'output is: {a}^2 + {b}^2 = {c}^2'
#!/usr/bin/env python3 import argparse import re """ Part 1: Read in a set of ship movement actions and compute the manhattan distance from the starting point after applying each action in turn. Possible actions: N: move north by the given value. S: move south by the given value. E: move east by the given value...
#!/usr/bin/env python3 import argparse """ Part 1: Count the sum of the number of unique letters in each input group, where the groups are separated by a blank line Part 2: Count the sum of the number of shared letters in each input group Assumption: well-formed input """ def parse_file(input_file_name): groups ...
import numpy as np import matplotlib.pyplot as plt def read_data(): data = np.array([[1, 2.1], [2, 1.1], [1.3, 1], [1, 1], [2, 1]]) label = [1, 1, -1, -1, 1] return data,label if __name__ =="__main__": data,label = read_data() x =data[:,0] y =data[:,1] # print(x) plt.scatter(x,y,c=la...
### IAL002 - Primeira Lista ### 5. Escreva um programa que leia um número inteiro N e em seguida leia N números reais, ### calculando a soma de todos os valores digitados. ### Program for calculate total of determined-by-user number of values ### print('\n'); print("### Program for calculate total of determined-by-u...
### IAL002 - Primeira Lista ### 7. Escreva um programa que calcule os N primeiros termos de uma PG com razão R e ### primeiro termo P1 fornecidos palo usuário. Também deve ser calculada e apresentada a ### soma desses N termos. ### Calculates the sum of geometric progression given N of terms, the ratio R and first ...
import numpy as np from sphtocart import sphtocart def dircosaxes(tX1,pX1,tX3): ''' dircosaxes calculates the direction cosines of a right handed, orthogonal X1,X2,X3 cartesian coordinate system of any orientation with respect to North-East-Down USE: dC = dircosaxes(tX1,pX1,tX3) ...
import node import threading from debug import * #The graph object contains a bunch of nodes and is responsible for maintaining #the datastructure of nodes. and having physics act upon them #the main datastructure is a dictionary of nodes. where the key is the UID and the value is the node #the other datastructure is ...
# this script was used to find the 3 longest gene sequences in the NC_002695.1.fasta file from Bio import SeqIO # this imports the correct programmes in Biopython filename = "NC_002695.1.fasta" outputfile = "longest_genes.fasta" output_handle = open(outputfile, 'w') # this assigns the filenames and opens a file for the...
def validate(value): try: float(value) return True except: return False def averagecalc(a, b, c): a = float(a) b = float(b) c = float(c) sum = a + b + c result = sum / 3 if result >= 7: print("Aprovado!") else: print("Necesário inserir a ...
def ref_func(x, y): return x + y def main(): f = (lambda x, y: x + y)(4,5) print(f) ff = lambda p: lambda b: b**p square = ff(2) cube = ff(3) print(square(3)) print(cube(3)) if __name__ == '__main__': main()
y = 10 def my_func(): global y print(y) y += 1 def outer(): x = 10 def inner(): nonlocal x print(x) x += 1 return x return inner def main(): pass if __name__ == '__main__': main()
# coding: utf-8 # util def mkRand(num = 10000): result = [] for i in range(num): result.append(random.randint(0, 999)) return result def show(lis): for i in range(len(lis)): print(lis[i]) def swap(lis, i, j): result = copy.deepcopy(lis) tmp = result[i] result[i] = result[j] result[j] = tmp ...
import itertools # prime numbers' limits limits = 3, 110 # how many divisors should Carmichael number have divisors = 8 # find primes in limits primes = [] for el in range(*limits): is_prime = True for num in range(2, int(el ** 0.5) + 1): if el % num == 0: is_prime = False brea...
from cmath import sqrt number = 5 if number == int(number): print("The number is an interger") else: print("The number is not an interger") a = 10 b = 2 print("Yes") if a < b else print("no") print('yes') if a < b else print("winner") x = 100 if sqrt(x) < 5: print("square root is less than 5") if sqrt...
# for l in range(0,10): # for w in range(0,10): # print('*', end=" ") # print() for l in range(0,5): for a in range(): print('*', end=" ") print()
class MenuRegistry(object): def __init__(self, menuRegistry=None): if(menuRegistry == None): self._menuRegistry = [] else: self._menuRegistry = menuRegistry def addMenuToRegister(self, menu): if(menu in self._menuRegistry): prin...
# funcion filter (funciones de orden superior, programación funcional) # python es multiparadigma: POO y multifunción # comprueba si los elementos de una lista cumplen una condición # devolviendo un iterador con los elementos que la cumplen # ej: devuelve número pares ''' def impar(num): if num%2: return True '''...
# función map (funciones de orden superior) # aplica una función a cada elemento de una lista iterable (lista, tupla, ...) # devolviendo una lista con los resultados # filter aplica una condición (construida incluso con una función lambda) # map, en vez de una condición, aplica una función class empleado: def __in...
""" You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics. Input Format The first line cont...
""" A 'Decent' Number has - 3 or 5 or both as its digits. No other digit is allowed. Number of times 3 appears is divisible by 5. Number of times 5 appears is divisible by 3. """ __author__ = 'Danyang' class Solution(object): def solve(self, N): """ mod :param cipher: the ...
""" A clique in a graph is set of nodes such that there is an edge between any two distinct nodes in the set. It is well known that finding the largest clique in a graph is a computationally tough problem and no polynomial time algorithm exists for it. However, you wonder what is the minimum size of the largest cliq...
""" Borussia Dortmund are a famous football (soccer) club from Germany. Apart from their fast-paced style of playing, the thing that makes them unique is the hard to pronounce names of their players. The team's coach is your friend. He is in a dilemma as he can't decide how to make it easier to call the players by...
# Problem 1 and Problem 2 were objective type questions and therefore not listed ############################################################################### # Problem 4 def primes_list(N): ''' N: an integer Returns a list of prime numbers ''' # Your code here L = [2] for n in range(3,N+1...
a = int(input("Enter 1st number: ")) b = int(input("Enter 2nd number: ")) c = a+b print(c)
class Rectangle: """définit un rectangle avec les arguments longueur et largeur""" def __init__(self, longueur:float, largeur:float) -> None: self.longueur = longueur self.largeur = largeur def perimetre(self): """Périmètre : 2*Longueur + 2*Largeur""" return self.longueu...
#!/usr/bin/env python3 # coding: utf-8 pairs = {"g @": 'ɟ', "i @": 'ɯ', "k @": 'c', "l @": 'ʎ', "o @": 'ø', "u @": 'y', "a @": 'aː', "c @": 't ʃ', "s @": "ʃ", "y @": "yː", "ɯ @": "ɯː"} with open('tell.txt', 'r') as f: with open('Lea...
# combine text print('Hello' + ' ' + 'World') # print number print(10+20) # print number and text print('Hello ' + str(20)) print('Hello',20,sep='_') # print to the same line from time import sleep print('Downloading....10%',end='\r') sleep(1) print('Downloading....29%',end='\r',flush=True) sleep(1) print('Downloadi...
day = 'Sunday' year = 2021 # Method 1: % sign print('Today is a %s of %s' % (day,year)) # Method 2: format print('Today is a {} of {}'.format(day,year)) print('Today is a {date_name} of {year}, and last {date_name} is also in {year} as well'.format(date_name=day,year=year)) # Method 3: fstring print(f'Today is a {da...
import sqlite3 import datetime song_db = "__HOME__/songs.db" def handle_post(request): """ Handles a POST request to server/score_server.py. Expects the following arguments: - userName (str): a string corresponding - songId (int): the id of an existing song - score (int): the scor...
import unittest class BinaryTreeTest(unittest.TestCase): def initialize(self): self.node_one = new Node(5) self.node_two = new Node(4) self.node_three = new Node(2) self.node_four = new Node(10) self.node_five = new Node(-5) self.node_six = new Node(20) ...
""" matrice saisie: [[2 3] [5 7]] """ from tkinter import * import numpy as np root = Tk() root.title = "Calcul Inversation de Matrice" root.geometry("600x300") def determinant(matrice): ''' Retourne le determinant ''' if len(matrice) == 2 and len(matrice) == 2: det = matri...
# -*- coding: utf-8 -*- """ Created on Mon Apr 15 18:49:08 2019 @author: Tara """ p = [-4, 6, 2, 0] #my polynomial is 2x^2 + 6x - 4 j = [] h = [] def polynomial(x): for ii in range(len(p)): k = x**i j.append(p[ii]*l) return sum(j) print(sum(p(-4))) def p_derivative(n): for i...
def countCharacters(words, chars): good_arr = [] for word in words: str = chars good = True print("word is",word) print ("str is", str) for letter in word: print("letter is", letter) if letter in str: index = str.find(letter) str = str[:index] + str[(index +1):] ...
# You are given a pointer to the root of a binary tree. You need to print the # level order traversal of this tree. In level order traversal, we visit the # nodes level by level from left to right. You only have to complete the # function. from collections import deque class Node: def __init__(self, info): ...
# Search In Sorted Matrix # You are given a two-dimensional array (matrix) of distinct integers where each # row is sorted and each column is also sorted. The matrix does not necessarily # have the same height and width. You are also given a target number, and you # must write a function that returns an array of the ro...
def canCross(stones): for i in range(3, len(stones)): if stones[i] > stones[i - 1] * 2: return False lastStone = stones[-1] positions = [] # stack jumps = [] # stack stonePositions = {} for stone in stones: stonePositions[stone] = True positions.append(0) ju...
# Treasure Island II # You have a map that marks the locations of treasure islands. Some of the map # area has jagged rocks and dangerous reefs. Other areas are safe to sail in. # There are other explorers trying to find the treasure. So you must figure out # a shortest route to one of the treasure island. # Assume the...
from Bintree import Bintree import random import time tree = Bintree() print("This program compares search-time between linear search and BST-search") totalEntries = int(input("Please enter how many total entries there should be : ")) numberArray = [x for x in range(totalEntries)] random.shuffle(numberArray) #R...
class Bintree(): #Binary Search Tree "Controller". def __init__(self): self.root = None def put(self,x): #For adding value to the tree if self.root == None: self.root = Node(x) else: self._put(self.root,x) def _put(self,node,x): #Recursively finds were to put that value. if x > node.x : if node....
# Exposes HashTable(int {size of table}) class. # Collision-sorting: Linked List # KeyError : Raises KeyError class Node(): def __init__(self,key,payload): self.key = key self.payload = payload self.next = None class HashTable(): def __setitem__(self, key, value): #HashTable[key] = Value self.put(key,va...
class LinkedQueue: def __init__(self): self.top = None def put(self,x): new = Node(x) if self.isEmpty(): #Inserted Node will be refered to as both top and bottom. self.top = new self.bottom = new else: self.bottom.next = new #When only one Node in queue this is also self.top self.bottom = new...
def rollLengthFunc(twoChars): #Tar en sträng "AB" och returnerar längden som alla bokstäver ska "rullas" length = ord(twoChars[1]) - ord(twoChars[0]) if(not length == abs(length)): #Blir start - stop negativt? length = 26 - abs(length) return length def convertLine(line,rollLength): #Line = rad från filen. rollLe...
class Cell: # values that Cell.color can take: BLACK = "." WHITE = "-" def __init__(self, x, y, color, number=None, content=None, answer=None, circled=False, clue_across=None, clue_down=None): self.color = color self.number = number # the clue number of the cell, or None if cell is not numbered sel...
Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Type "copyright", "credits" or "license()" for more information. >>> n=8 >>> for i in range(0,n): for k in range(i,n): print(" ",end="") for j in range(0,i): print("*",end="") for i in range(1,i): print("*",end="") print("\n") ...
import random # Подключение библиотеки random # инициализируем переменные счета для игрока и компьютера player_score = 0 computer_score = 0 restart ="д" variants = ["камень", "ножницы", "бумага"] # список возможных вариантов выбора print("Возможные варианты выбора: камень, ножницы, бумага") while restart == "д": # цикл...
import pygame from pygame.sprite import Sprite white = (255,255,255) # This class represents the ball # It derives from the "Sprite" class in Pygame class Block(pygame.sprite.Sprite): # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): ...
''' expr : term ((PLUS | MINUS) term)* term : factor ((MUL | DIV) factor)* factor : (PLUS | MINUS) factor | INTEGER | LPAREN expr RPAREN ''' from enum import Enum from typing import Any # ==== Lexical Analyzer ==== class TokenType(Enum): START = 0 INTEGER = 1 PLUS = 2 MINUS = 3 ...
# def stars(arr): # s=0 # for x in range(len(arr)): # s=arr[x] # sarr="" # while s>0: # sarr+="*" # s-=1 # print sarr # stars([1,2,6]) def stars(arr): s=0 for x in range(len(arr)): if type(arr[x])==int: s=arr[x]...
# let's create a function that will take two numbers as parameters and add them together. # Call this function many times in your program, each time with different parameters. print ("Input two numbers, which should be added together") def number_calculator (number1, number2): solution = number1 + number2 ...
dict1={"a":2,"b":1,"c":3} dict2={"d":5,"e":43,"f":32} fdict= dict(dict1, **dict2) print(fdict)
def gather_info(): h = float(input("enter h : ")) w = float(input("enter w : ")) s = input("enter s : ").lower().strip() return (h,w,s) def cal(h,w,s='metric'): if s == 'metric': bmi = (w/(h**2)) else: bmi = 703 * (w/(h**2)) return bmi while True: h,w,s=gather_info() ...
'''funciones matematicas''' import math num1, num2, num, men=12.572, 15.4,4,'1234' print(math.ceil(nume1),'\t', type (mun),'\t',type(men)) #funciones de cadenas mensaje='Hola'+'mundo'+'Python' men1=mensaje.split() men2=''.join(men1) print(mensaje[0],mensaje[0:4],men1,men2) print(mensaje.find(''mundo''),mensaje...
"""input is passed as number of users, then username and marks for 3 subjects and finally the student whose average you want to display 3 Krishna 67 68 69 Arjun 70 98 63 Malika 52 56 60 Malika""" import math if __name__ == '__main__': n = int(input()) student_marks = {} for i in range(n): name, *li...
# Enter your code here. Read input from STDIN. Print output to STDOUT import calendar,datetime date = input() born = datetime.datetime.strptime(date, '%m %d %Y').weekday() print((calendar.day_name[born]).upper(), end =" ")
def withdraw( money, request): paperValues= [ 100, 50, 10, 5, 1] remaining= money - request if request <= 0 : print "Invalid input !" ; elif request > money : print "Balance Not Enough !" ; else: print "Current Balance: "+ str(money) print "Delivering "+ str(reques...
# Uses python3 import sys #from gcd import gcd # def lcm_naive(a, b): # for l in range(1, a*b + 1): # if l % a == 0 and l % b == 0: # return l # # return a*b # # if __name__ == '__main__': # input = sys.stdin.read() # a, b = map(int, input.split()) # print(lcm_naive(a, b)) def g...
class _node_: def __init__(self, key, value): """Nodes of the linked list""" self.key = key self.value = value self.next = None class linked_list: """A object containing a pointer to the head of a linked list""" def __init__(self, key, value): self.count = 0 # Number...
import matplotlib.pyplot as plt from matplotlib import * from numpy import * from matplotlib.animation import * name = "Fermat Spiral" def r_(u): r = sin(a*u)**2 + cos(b*u)**2 + tan(c*u) return r a = 1 b = 1 c = 1 u = linspace(0, 2 * pi,100) r = r_(u) ax = plt.subplot(111, projection='polar') ax.xaxis.set_tick_...
import queue class Node: def __init__(self, val): self.val = val self.left = None self.right = None # Tree root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) ############### # DFS # ############### # Root Left Right def dfs_p...
class CircularQueue: def __init__(self, maxSize): self.queue = list() # kullanıcı girdisi üzerine maxBoyut self.maxSize = maxSize self.head = 0 self.tail = 0 # Eleman ekleme def enqueue(self, data): # BufferDolu mu(Kuyruk) kontrolü if self.size() == (self.maxSize - 1): return...
"""The UDPClient class implements a client using the UDP Protocol. """ import socket from datetime import datetime from Networking.UDPPinger import utils class UDPClient: """Implements a UDP Client that waits `timeout` seconds for responses. Parameters ---------- timeout: int The number of s...
#!/usr/bin/python3 # encoding = utf-8 # # python实现栈 class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): return self.items.append(item) def pop(self): return self.items.pop() def peek(self): # 返回栈顶端元素 return self.items[len(self.items) -...
''' CODE CHALLENGE: Pattern Count Problem. Input: Two strings, Pattern and Genome. Output: Count of appearance of Pattern in Genome. Sample Input: ATAT GATATATGCATATACTT Sample Output: 3 ''' s1=str(input()) s2=str(input()) num=0 start=0 while start!=-1: start= s2.find(s1, start, len(s2)) if(start...
''' CODE CHALLENGE: Reverse Complement Problem. Input: A DNA string Pattern. Output: Pattern, the reverse complement of Pattern. Sample Input: AAAACCCGGT Sample Output: ACCGGGTTTT ''' s=str(input()) s=s[::-1] i=0 for i in range (len(s)): if s[i]=='A': s = s[:i] + "T" + s[i+1:] continue...
counties = ["Arapahoe","Denver","Jefferson"] counties.insert(1, "El Paso") print(counties) counties.pop(0) print(counties) #counties.pop #counties.insert(1, "Jefferson ") #print(counties) #counties.insert(2,"Denver") counties.remove("Denver") counties.append("Denver") counties.append("Arapahoe") print(counties) print(c...
import json class User: def __init__(self,name,age): self.name = name self.age = age user = User('Max',27) def encode_user(o): if isinstance(o, User): return {'name':o.name, 'age':o.age, o.__class__.__name__:True} else: o_name = o.__class__.__name__ return TypeE...
""" 날짜 : 2020-06-22 이름 : 김나연 내용 : 집합 자료형 실습하기 p97 """ # 집합 생성하기 set1 = set([1, 2, 3, 4, 5]) set2 = set([4, 5, 6, 7, 8]) # 집합 출력하기 : 리스트, 튜플로 변환 후 출력 ls = list(set1) tp = tuple(set2) print('ls : ', ls) print('tp : ', tp) # 교집합 print('set1과 set2 교집합 : ', set1 & set2) # 합집합 print('set1과 set2 합집합 : ', set1 ...
N = int(input()) used_words = [] pre_word = input() used_words.append(pre_word) state = "Yes" for i in range(N-1): W = input() if pre_word[-1] != W[0]: state = "No" break for uw in used_words: if uw == W: state = "No" break if state == "No": b...
import math import numpy as np def count_2(n): i = 0 while True: if n % 2 == 0: i += 1 n = n // 2 else: break return i N = int(input()) a = [int(b) for b in input().split()] sum = 0 for aa in a: sum += count_2(aa) print(sum)...
#"""Exercício 03 #3.1) Crie um programa que cadastre o id, nome, sexo e a idade de 5 clientes. #3.2) Depois mostre os dados dos 5 clientes. #3.3) Peça para que o usuário escolha um id de um cliente e mostre as informações deste cliente. #3.4) Crie um filtro que ao digitar um id de um cliente mostre as seguintes inf...
def main(): segundos=int(input()) segundos_restantes=segundos%3600 segundos_horas=segundos//3600 segundos_minutos=segundos_restantes//60 segundos_restantes=segundos%60 segundos_segundos=segundos_restantes//1 print(f'{segundos_horas} : {segundos_minutos} : {segundos_segundos}') if __n...