text
stringlengths
37
1.41M
for index in range(10, 1000): for prime_index in range(2,index): if index%prime_index == 0: print(f"{index} is not prime") break else: print(f"{index} is prime")
def is_prime(number): """ This function will help in finding whether the number is prime or not """ for index in range(2,(number//2)+1): if number%index == 0: return False return True def factors(number): """ This method will return the factors """ values = [] ...
# Program to calculate the Grades maths = int(input('Enter the marks in maths: ')) physics = int(input('Enter the marks in physics: ')) chemistry = int(input('Enter the marks in chemistry: ')) english = int(input('Enter the marks in english: ')) average = (maths + physics + chemistry + english) / 4 if average >= 90: ...
index = 2 number = 190 while index < number: if number%index == 0: print('prime') break index += 1 else: print('not prime')
course = 'python' def change_local(): """ This method will change the local value """ course = 'django' print('locals: ',locals()) def print_globals(): """ This method is used to print globas """ print('globals: ',globals()) change_local() print_globals()
import math class Number: def __init__(self, number=0) -> None: """Initalization of the number class Args: number (int) Represents a Number """ self.__number = number def is_even(self) -> bool: """ This method will check if the number is even or not ...
"""This module has utilities """ def collect_number_input(count=1): """ This method will collect the number inputs """ index = 0 numbers = [] while index < count: numbers.append(int(input(f'Enter the number {index+1}: '))) index += 1 return numbers
import datetime def document(func): """This function is a decorated to document the functions getting called """ def document_function(*args, **kwargs): print(f"Running Function: {func.__name__}") print(f"positional args: {args}") print(f"keyword args: {kwargs}") print(f"Exe...
import sqlite3 import models def initialize(): sql_products_create_table = """ CREATE TABLE IF NOT EXISTS products ( id integer PRIMARY KEY, name text NOT NULL, price real NOT NULL, quantity int ) """ sql_sales_create_table = """ CREATE TABLE IF NOT EXISTS sales...
number = int(input()) index = 0 while index < number: print(index**2) index += 1
# This program tries to solve the project euler 6 index = 1 sum_of_numbers = 0 sum_of_squares = 0 while index <= 100: # Calculate the sum of the numbers by adding all numbers sum_of_numbers = sum_of_numbers + index # Caclulating the square og the number and adding it to the index sum_of_squares = sum_of...
def capitalize(function): def inner_function(): result = function() return result.capitalize() return inner_function def detail(function): def wrapper(*args, **kwargs): print(f"Running function {function.__name__}") print(f"Positional Arguments are {args}") print(f"K...
def fibonacci(index: int) -> int: """ This function will return the fibonacci series number Args: index(int): index of the fibonacci series Return: number based on the index pass """ if index == 0: return 0 elif index == 1: return 1 first = 0 secon...
name = "Biljana" age = 29 print(name, age, "Python", 2020) #Biljana 29 Python 2020 print(name, age, "Python", 2020, sep=", ") #Biljana, 29, Python, 2020 each value is separated by comma #sep = separator, it is used when we have more then one value to pass in print menu = [ ["egg", "bacon"], ["egg", "sausage",...
flowers = [ "Daffodil", "Evening Primrose", "Hydrangea", "Iris", "Lavender", "Sunflower", "Tiger Lily" ] # for flower in flowers: # print(flower) separator = ", " output = separator.join(flowers) print(output) #Daffodil, Evening Primrose, Hydrangea, Iris, Lavender, Sunflower, Tiger Lil...
class BSTNode: """ A node in a binary tree. """ def __init__(self, data, left=None, right=None): """ (BSTNode, str, BSTNode, BSTNode) -> NoneType Initialize a new BSTNode with data, left and right children. """ self.data = data self.left = left self.ri...
# Document me if you like. # vowel list VOWEL = list('AEIOUaeiou') def vowel_count_v1(s): ''' (str) -> int Count number of vowel in the string s. O(n) time, exponential space. ''' if len(s) == 0: res = 0 elif len(s) == 1: res = int(s in VOWEL) else: res = int(s[0] ...
def binary_search(L, s): '''(list) -> bool Return True iff s is an element of L REQ: L must be a sorted list ''' # BASE CASE: If L is empty, it's not in the list if (len(L) == 0): result = False # RECURSIVE DECOMP: Pick the middle element, if we found # what we're lookin...
#!/usr/bin/env python #Importing modules for HTTPS Connection import urllib import httplib #Importing modules for parsing JSON import json #Importing modules for reading Command Line Arguments import sys LIMIT=10 # default limit OFFSET=0 # default offset #Function to print the Usage, in case invalid arguments d...
import datetime name = raw_input("Give me your name: ") print "Your name is " + name age = int(raw_input("Give me your age: ")) print "Your age is " + name print "You will be 100 in:" + str(datetime.datetime.now().year + (100-age))
""" Module for plotting the result of the algorithm """ import os from typing import List import matplotlib.pyplot as plt from traveling_salesperson import City def plot_path(filename: str, path: List[str], cities: List[City], total_distance: int) -> None: """Construct and save a plot of the path connecting all...
#!/bin/python3 import math import os import random import re import sys # Complete the checkMagazine function below. def checkMagazine(magazine, note): dictionaryMagazine = {} dictionaryNote = {} ret = 0 for word in magazine: if word not in dictionaryMagazine: dictionaryMagazine[...
def find_longest_word(word_list): return max(word_list, key = len) words = ['monkey','bear','elephant','dog','cat'] print(find_longest_word(words))
from tkinter import * def circle(l,n): if n < (len(l) - 1): return(l[n]) else: return(l[n % (len(l))]) def my_formatting(string): for i in string: if i in ".,1234567890?!;:_;-/()[]{}+-*\"'": string = string.replace(i,'') ...
a = int(input('a = ')) b = int(input('b = ')) step = 0 while a != b: step += 1 if a > b: a = a - b else: b = b - a print(a, step)
import math a = int (input ("Введите 1 число: ")) b = int (input ("Введите 2 число: ")) c = int (input ("Введите 3 число: ")) d = int (input ("Введите 4 число: ")) e = int (input ("Введите 5 число: ")) f = int (input ("Введите 6 число: ")) g = int (input ("Введите 7 число: ")) h = int (input ("Введите 8 число: ")) j =...
""" a = 0 b =1 series = [] while a<10: series.append(a) a=b # series.append(b) b = b+a print(series) # 0 1 1 2 3 5 8 """ def fib(n): a,b = 0,1 list = [] while a< n: list.append(a) a,b = b, a+b print(list) fib(20) #multi-dime...
"""Read from files that have custom format""" # open a file for reading and iterate each line with open('./custom.txt') as f: config = {} for line in f: # assign to multiple variables (tuple unpacking) id, name = line.strip().split(' = ') config[id] = name for id in ["123", "213"]: ...
"""Word Finder: finds random words from a dictionary.""" from random import choice class WordFinder: """Machine for finding random words from dictionary. >>> wf = WordFinder("words.txt") 235886 words read """ def __init__(self, path): """Read dictionary and report number of items read...
import math, random, pygame pygame.init() class Pokemon: """Initializes Pokemon object with base stats, actual stats, experience points, sprite, level, moves, hit points""" def __init__(self, species, base_hp, base_atk, base_defe, base_spd, base_exp, sprite, exp, p_type, moves): self.species = species ...
#!python from linkedlist import Node, LinkedList from hashtable import HashTable class Set(object): def __init__(self, elements=None): # intilaize the size of the set, starts with intial size of 10 if elements is None: initial_size = 10 else: initial_size = len...
#!python def contains(text, pattern): """Return a boolean indicating whether pattern occurs in text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) if len(pattern) == 0: return True patter...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # Floyd's cycle detection algorithm, also known as the hare-tortoise algorithm. class Solution(object): def detectCycle(self, head): if head is None: return None ...
# Oscar Stanley #15-9-2014 #task one number = int(input("what is your first number?: ")) number1 = int(input("What is your second number?: ")) number2 = int(input("What is your third number?: ")) number3 = int(input("What is your fourth number?: ")) answer = (number + number1 + number2 + number3) print("you...
value = int(input()) for x in range (1, 11): print("{n1} x {n2} = {n3}".format(n1 = x, n2 = value, n3 = (x * value)))
count = 0 n1 = float(input()) if(n1 > 0): count += 1 n2 = float(input()) if(n2 > 0): count += 1 n3 = float(input()) if(n3 > 0): count += 1 n4 = float(input()) if(n4 > 0): count += 1 n5 = float(input()) if(n5 > 0): count += 1 n6 = float(input()) if(n6 > 0): count += 1 print("{n} valores positivos".format(n =...
aux = int(input()) hr = aux // 3600 aux = aux % 3600 minut = aux // 60 aux = aux % 60 print("{hora}:{min}:{seg}".format(hora = hr, min = minut, seg = aux))
values = input().split() cd = int(values[0]) qtd = int(values[1]) if(cd == 1): print("Total: R$ {:.2f}".format(qtd * 4.00)) elif(cd == 2): print("Total: R$ {:.2f}".format(qtd * 4.50)) elif(cd == 3): print("Total: R$ {:.2f}".format(qtd * 5.00)) elif(cd == 4): print("Total: R$ {:.2f}".format(qtd * 2.00)) elif(c...
count = 0 n1 = float(input()) if(n1 % 2 == 0): count += 1 n1 = float(input()) if(n1 % 2 == 0): count += 1 n1 = float(input()) if(n1 % 2 == 0): count += 1 n1 = float(input()) if(n1 % 2 == 0): count += 1 n1 = float(input()) if(n1 % 2 == 0): count += 1 print("{n} valores pares".format(n = count))
qtd = int(input()) total = 0 qtdCoelho = 0 qtdRato = 0 qtdSapo = 0 for x in range(0, qtd): amount, tipo = input().split() amount = int(amount) total += amount if(tipo.lower() == "c"): qtdCoelho += amount elif(tipo.lower() == "r"): qtdRato += amount elif(tipo.lower() == "s"): qtdSapo += amount pr...
from random import random import time # deneme = 0 # numbercreate = int(random()*100) # while True: # inputnumber = int(input("0 ile 100 arasında bir sayı tahmin et : ")) # if inputnumber == numbercreate: # print(f"Doğru tahmin ettiniz : {numbercreate} .\nTebrikler\n Deneme Sayınız : {deneme}") # break # ...
def codewar_result(codewarrior, opponent): codewarrior.sort(reverse=True) opponent.sort(reverse=True) points = 0 while len(codewarrior) != 0: for Opp_armySize in opponent: if codewarrior[0] > Opp_armySize: points += 1 result = 'victory' ...
''' 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 ''' class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ cur = 0 while cur < len(nums...
''' 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 示例 1: 输入: 121 输出: true ''' class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False n = x res = 0 while n: res = res * 10 + n % 10 ...
# -*- coding: utf-8 -*- import logging#logging模块可以记录错误信息,打印完错误信息后会继续执行,并正常退出 from functools import reduce try: print ('try..') r=10/int('a') print ('result:',r) except ZeroDivisionError as e: print ('except:',e) except ValueError as e: print ('ValueError:',e) finally: print ('finally..') print ...
""" 购物车小项目 系统:Windows 10 语言:Python 3 IDE:PyCharm 2020.2 """ import json # 初始变量 uName = '' uPwd = '' # 购物车注册,登录 # 1.设置密码和用户名,密码为空 def login(): uName = "" uPwd = "" if uName == "": print("请登录:") uname = input("请输入用户名:") upwd = input("请输入密码:") with open("message.json", 'r', e...
from Helper import Location class Ride: def __init__(self, row_start, col_start, row_end, col_end, earliest_start, latest_finish): self.start = Location(row_start, col_start) self.end = Location(row_end, col_end) self.earliest_start = int(earliest_start) self.latest_finish = int(la...
#!/usr/bin/env python3 """ http://www.checkio.org/mission/break-rings/ """ # how many rings we have to break CURRENT_SOLUTION = 0 def break_rings(rings): def is_optimal(solution): return CURRENT_SOLUTION > solution if __name__ == '__main__': # These "asserts" using only for self-checking and not nec...
""" We have an array of straight connections between drones. Each connection is represented as a string with two names of friends separated by hyphen. For example: "dr101-mr99" means what the dr101 and mr99 are friends. Your should write a function that allow determine more complex connection between drones. You are gi...
def find_word(message): words = message[:-1].split(" ") msg_matrix=[ [0 for i in range(0,len(words))] for j in range(0,len(words))] for i in range(0, len(words)): for j in range(0, len(words)): if words[i] != words[j]: msg_matrix[i][j] = compute_likeness(words[i].lower(...
#!/usr/bin/env python3 """ http://www.checkio.org/mission/pawn-brotherhood/ """ import string LETTERS = string.ascii_lowercase def safe_pawns(pawns): pawn_coords = [] count=0 for pair in pawns: x = LETTERS.index(pair[0]) + 1 pawn_coords.append((x,int(pair[1]))) for row, col in pawn_coords: is_safe = (row -...
class Reverse: classStr = "" def __init__(self,str): if str: self.classStr = str print "initialized with String: " + str def getReverse(self): return self.classStr[::-1] if __name__ == '__main__': myStr = Reverse("abcdefg") print myStr.getReverse()
def pgcd(a, b): a, b = int(a), int(b) #check if a and b are integers while b != 0: r = a % b a, b = b, r return int(a) def fm(number): number = float(number) #check if its a number #if its a whole number, get rid of the decimal part if number.is_integer(): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 13 17:57:25 2018 @author: nhaddad """ import numpy as np def nextpow2(number): """ Find 2^n that is equal to or less than number Syntax: nextpow2(n) ex: nextpow2(350) Utility function used by fft methods to compute the m...
from sys import stdin letter_heights = tuple(int(s) for s in stdin.readline().split()) word = stdin.readline().strip() word_height = max(letter_heights[ord(c) - ord('a')] for c in word) print(word_height * len(word))
def increment(x): num = x num +=1 return(num) z = increment(3)
from math import floor def nestEggFixed(salary, save, growthRate, years): """Returns list of size of retirement account at the end of each year""" account_list = [] for i in range(years): if i == 0: account_list.append(salary * save * 0.01) else: account_list.appen...
def length(ls): """Return length of `ls`""" if ls == []: return 0 return 1 + length(ls[1:]) def total(ls): """Return sum of all numbers inside `ls`""" if ls == []: return 0 return ls[0] + total(ls[1:]) def factorial(num): """Return factorial of `num`""" if num <= 0:...
#Day 1 #strings #Ao declarar variaveis nao e necessario colocar o tipo ou var #points separate decimals myFloat = 3.1415 myString ="this is a phrase" myAnotherString = " but this is not, this is a period" myNumberString = "234" print(myString) print(myFloat) print(myString + myAnotherString) print(myFloat + 1.0) #co...
my_file = open("zen_of_python.txt", "r") lines = my_file.readlines() my_file.close() # print(lines) for line in lines: print(line.rstrip()) # print(line1.rstrip()) # print(line2.rstrip()) # print(line3.rstrip())
#valtozonev, ami jelenleg egy lista, numbers = [5, 7, 9, 11, 13, 12] i = 0 #valtozo lehet tobb eleme is while i < len(numbers) : #muveletes szavak amig i kisebb mint 6 addig mindig belej0n a blokkba es rater az ifre if numbers[i] % 3 == 0: #==maradekos osztas, az osztas maradekat adja vissza, ha oszthato 3-al mara...
y = 6 #print the numbers till y from 0 i = 0 for i in range (0, y + 1): print(i)
#fuggvenyt ami egy listat valt es visszater a lista forditottjaval. bemenetnek kap egy listat es visszater egy listaval ami a forditottja. numbers = [1, 2, 3, 4] def reverse(in_list): output = [] i = len(in_list)-1 while i >= 0: output.append(in_list[i]) i = i - 1 return output print(re...
filename = "alma" #write a function that reads a file and prints how many lines and characters in it # def print_file_lines_with_a(name): file_to_print = open("name") content = file_to_print.read() file_to_print.close() for line in content.split ("\n"): output += "a" + line + "\n" retur...
def get_fizz(number): if number % 3 == 0: return "fizz" else: return number def fizz_buzz(minimum, maximum = 100): n = minimum while n <= maximum: print(get fizz): n += 1 fizz_buzz(1, 50) def is_big_number(number): return number > 100 def dude(number) if is_bi...
#keresztulmegy vmin amig van feltetele a dolognak list = [1,2,3,4,5,6,7] for i in list: print(i)
#data structure ami leirja a koordinatakat, mereteket, vmi ami megjeleniti import unittest from ball import Ball class TestBall(unittest.TestCase): def test_exists(self): ball = Ball(40, 50, 10) def test_position_and_size(self): ball = Ball(40, 50, 10) self.assertEqual(ball, x, 40) ...
aa = [4, 5, 6, 7] #print all the elements of aa i = 0 while i < len (aa): print (aa[i]) i += 1
# create a function that returns it s input factorial def factorial3(num): if num == 1: return 1 else: return factorial3(num - 1) * num print(factorial3(10))
v = [1, 2, 3] out = 0 #if the v list contains one element set the out to 1 #if the v list contains two element set the out to 2 #if the v list contains more than 2 set the out to 10 #if the v contains no elements it should set to -1 if len(v) == 0: out = -1 elif len(v) == 1: out = 1 elif len(v) == 2: out = ...
u = 13 #if u is between 10 and 20 print Sweet if less than 10 print More if more than 20 print less. out = "" if u > 10 and u<=20: print("Sweet") elif u <= 10: print("More") else: print("Less")
# 1. create mysuperstring class #2. receive a string as an argument and store it #3. implement reverse() # !hello" => "olleh" #implement count(char) #implement snake_case() #ujklasszt kell kesziteni, a szamok listajanak kiszamolni az atlagat es visszaadni, uj osztaly Mysupermasterclass #return a new string with spaces ...
# by lamda function even odd from a list by a given list lst=[12,23,23,34,90,100] var=lambda n : n%2==0 var1=lambda n : n%2!=0 print(list(filter(var,lst))) #or- print(list(filter(lambda n : n%2==0,lst))) print(list(filter(lambda n : not n%2==0,lst))) # by not operator print(list(filter(lambda n : n%2!=0,ls...
import random answer = 'yes' A =[] O =[] B =[] while answer != 'no': a = random.randint(0,20) o = random.randint(0,20) b = random.randint(0,20) A.append(a) O.append(o) B.append(b) if (a > o) and (o > b): print("rank: 1. apple, 2. orange, 3. banana") elif (a > b) and (b > o): ...
films = { 'Matilda':[9,7], 'The Blue Duck':[5,10], 'The Bfg':[15,5], 'Sky High':[20,3], 'Finding Dory':[3,15], 'Ask The Story Bots':[5,10], 'Peppa Pig':[1,20], 'Paw Patrol':[7,6], 'Shimer And Shine':[6,5], 'My Little Pony':[8,4], 'Banana World':[2,12], 'When I Grow Up':[4...
import math class Formula: def __init__(self, lat1=None, long1=None): if not lat1: self.lat1 = 52.339428 else: self.lat1 = lat1 if not long1: self.long1 = -7.257664 else: self.long1 = long1 def _calculate(self, lat2: float, lo...
# Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, ...
# There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. # # The cost of painting each house with a certain color is re...
# There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. # # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # # Given the total number of courses and a list of prerequisite pairs, is it possible fo...
# Input: intervals = [[1,3],[2,6],[8,10],[15,18]] # Output: [[1,6],[8,10],[15,18]] # Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ ...
# Given preorder and inorder traversal of a tree, construct the binary tree. # # Note: # You may assume that duplicates do not exist in the tree. # # For example, given # # preorder = [3,9,20,15,7] # inorder = [9,3,15,20,7] # Return the following binary tree: # # 3 # / \ # 9 20 # / \ # 15 7 from idl...
# Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. # # The same repeated number may be chosen from candidates unlimited number of times. # # Note: # # All numbers (including target) wil...
def minHeightBst(array): return consTruct(array, None, 0, len(array) - 1) def consTruct(array, tree, start, end): if start > end: return middle = (start + end) // 2 addV = array[middle] if tree is None: tree = BST(addV) else: tree.insert(addV) consTruct(array, tree,...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def __init__(self): self.diameter = 0 def diameterOfBinaryTree(self, root): """ ...
# Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. # # Note: # # If there are multiple valid itineraries, you should return the itinerar...
# Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters. # 模拟内存buffer读取,先从file读进buf4,再从buf4读进buf中 #Solution1 def readBufFromBuf4(args): pass def read4(buf4): pass def readBufFromBuf4(args): pass class Solution: def read(self, b...
from math import factorial as fact p=1.09/2.09 # print(p) b=0 for i in range(3,7): b+=fact(6)/fact(6-i)/fact(i)*p**i*(1-p)**(6-i) print(b) print(f'{b:.3f}')
import math #Masukan Nilai NilaiMatematika = int(input ("Masukan Nilai Matematika :")) NilaiIpa = int(input ("Masukan Nilai Ipa:")) NilaiBahasaIndonesia = int(input("Masukan Nilai Bahasa Indonesia:")) if NilaiMatematika > 0 and NilaiMatematika <101: if NilaiMatematika >= 0 and NilaiMatematika <=...
""" 储存各类data,用于之后的强化学习训练 """ import numpy as np import random def sample_n_unique(sampling_f, n): """Helper function. Given a function `sampling_f` that returns comparable objects, sample n such unique objects. """ res = [] while len(res) < n: candidate = sampling_f() if candidate n...
import sys import os class Parser(object): lines=[] def __init__(self, filename): self.filename = filename self.fullpath = str() def readlines(self): self.fullpath=self.filename cwd = os.getcwd() if not os.path.isfile(self.filename): self.fullpath = os...
from general.generateSystem import generate_system import numpy as np def rossler_odes(Y, parameters): """ Models the rossler attractor Parameters: Y: a numpy array, representing the current state of the dynamic system Y = [x, y, z] parameters: a numpy array, representing the parameters of the dy...
if __name__=="__main__": op=input("请输入操作符+、-、*、/: ") opa=eval(input("请输入数字A:")) opb=eval(input("请输入数字B:")) if op=="+": result=opa+opb elif op=="-": result=opa-opb elif op=="*": result=opa*opb elif op=="/": try: result=opa/opb except ZeroDi...
from abc import abstractmethod class Subject: def __init__(self): self.__observers = [] @abstractmethod def attach(self, observer): self.__observers.append(observer) @abstractmethod def detach(self, observer): self.__observers.remove(observer) def notify(self): ...
# def job(self): # print("%s is working" % self.name) # # # class Person(object): # def __init__(self, name): # self.name = name # # def eat(self, food): # print("%s is eating %s." % (self.name, food)) # # # d = Person('liming') # choice = input(">>:").strip() # # if hasattr(d, choice): # ...
from abc import * class Component: def __init__(self,name): if isinstance(name,str): self._name=name @abstractmethod def add(self ,c): pass @abstractmethod def remove(self,c): pass @abstractmethod def display(self,depth): pass class Leaf(Com...
import requests #This allows us to manipulate the site from the cloud from bs4 import BeautifulSoup #BeautifulSoup is a webscraping tool kit page = requests.get("https://en.wikipedia.org/wiki/Transhumanism") page #Stores the website as a variable, initializes the variable soup = BeautifulSoup(page.content, 'lxml...
#!/usr/bin/env python import random import string import signal import sys import pyperclip #for copy to clipboard def signal_handler(sig, frame): """ SIGINT signal handling function """ print('\nYou pressed Ctrl+C!') print("Bye!!!") sys....
# 작성일 : 2021.10.14 # 언어 : Python # 출처 : ACMICPC(백준) [1780번 : 종이의 개수] # 메모 : 재귀 함수를 통한 분할과 정복으로 문제 풀이 # 1) 주어진 면적 (초기값은 N X N) 을 일일이 읽어가며, 동일한 색상인지 확인 # 2) 동일한 색상이 확인될 경우, result 배열에 +1 # 3) 다른 색상이 발견되었을 경우, 주어진 면적을 3분할하여, 1)번의 재귀 함수 수행 (주어진 면적인 N//3 X N//3) # 4) 최종적으로 주어진 면적이 한 칸인 경우에는, for 문을 수...
#!/usr/bin/python ##################################################################### # # # This file instantiates the collection and tests various apis. # # # #####################...
''' Write a script that removes all duplicates from a list. ''' list_ = [1, 2, 3, 4, 3, 4, 5, 5,6,2,9,4,3,6,9] # s = set(list_) # l = list(s) # print(l) single_list = [] for num in list_: if num not in single_list: single_list.append(num) print (single_list)