text
stringlengths
37
1.41M
""" 1 비트의 갯수 https://leetcode.com/problems/number-of-1-bits/ 비트 연산 - 원래 데이터 and 원래 데이터 - 1 => 1 비트씩 제거 """ class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n: # 1을 뺀 값과 AND 연산 횟수 측정 n &= n - 1 count += 1 return co...
""" 중복 문자 제거 재귀를 이용한 분리 """ class Solution: def removeDuplicateLetters(self, s: str) -> str: for char in sorted(set(s)): suffix = s[s.index(char):] ## 전체 집합과 접미사 집합이 동일 할 시 if set(s) == set(suffix): return char + self.removeDuplicateLetters(suff...
# 비밀지도 # https://programmers.co.kr/learn/courses/30/lessons/17681 def solution(n, arr1, arr2): answer = [] for i in range(n): new_str = str (bin(arr1[i] | arr2[i])[2:]) print(new_str) new_str = new_str.rjust(n, '0') print(new_str) print("\n") new_str = new_str.rep...
# 셔틀 버스 # https://programmers.co.kr/learn/courses/30/lessons/17678 def timeToMinute (time): lst = time.split(':') return int(lst[0]) * 60 + int(lst[1]) def minuteToTime (minute): div, mod = divmod(minute, 60) return "%02d:%02d" % (div, mod) def crewTime(timetable) : return [timeToMinute(time) for time in timeta...
""" 조합의 합 숫자 집합 candidates를 조합하여 합이 target이 되는 원소를 나열하여라 내 풀이 """ from typing import List class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: result = [] def dfs(elements, start, sum): if sum >= target: if sum ==...
# Hash Tables: Ice Cream Parlor #!/bin/python3 import math import os import random import re import sys import collections # Complete the whatFlavors function below. def whatFlavors(cost, money): product = {} firstIndex = 0 secondIndex = 0 for i in range(len(cost)): secondIndex = i '...
#Write, append and delete in a file #write """ with open ("nurlesenschreiben.txt", "w") as file: file.write("Here you see the students of KU:\n") students = ["Jana", "Alan", "Ellie", "Sophie", "Rowan", "Jake", "Bill", "Ben"] for student in students: file.write(student+"\n") """ #""" #show with ope...
# -*- coding: cp1252 -*- """Enrique Ibáñez Orero - 1º DAW - Practica 6 - Ejercicio 4 - Pràctica 6. Escribe un programa que permita crear una lista de palabras y que, a continuación, pida una palabra y elimine esa palabra de la lista. """ num=int(raw_input("Dime el numero de palabras: ")) cont=1 if num<1: ...
#딕셔너리 자료형(Key,Value) -> (순서x,중복x,수정o,삭제o) #선언 a={'name':'kim','phone':'010-1234-5678','birth':10626} b={0,'Hello World'} c={'arr':[0,1,2,3]} print(type(a),a) #출력 print('a - ',a['name']) print('a - ',a.get('phone')) #get은 없으면 오류가 아니라 none if문 활용 print('c - ',c.get('arr')) #딕셔너리 추가 a['address']='JeonBuk' print('a - ',...
#!/usr/bin/env python3 import time from py_trie import PyTrie from ctrie import cTrie time_fmt = ":5f" def add_sorted_words(trie_constructor): startTime = time.time() tr = trie_constructor() creationTime = time.time() - startTime print("Takes {:5f}s to instantiate before adding sorted words".format...
#!/usr/bin/env python3 # -*-coding:utf-8-*- import itertools natuals = itertools.count(1) cs = itertools.cycle('ABC') ns = itertools.repeat('M', 10) items = itertools.takewhile(lambda x: x < 10, natuals) print(list(items)) for c in itertools.chain('ABC','XYZ'): print(c)
for i in range(1, 10): print("No {0:2} square is {1:3} and cube is {2:4}".format(i, i ** 2, i** 3))
#coding=utf8 def generate_insert_sql(tablename, dict_data): ''' 生成insert的sql语句 :param tablename: :param dict_data: :return tuple: (string sql, list args) tuple的前面一个元素表示格式化好的字符串的sql 后面一个表示参数是list类型 ''' sql = ' INSERT INTO ' + tablename + " " keys = dict_data.keys() ...
""" nur deziamlwerte akzeptieren, dann addieren mit commandline editing und history """ import readline werte = [0, 0] for i in range(2): txt = ("ersten", "zweiten")[i] while True: a = input("bitte ersten "+txt+" eingeben: ") if a.isdecimal(): werte[i] = int(a) break ...
# Create a class that represents a cuboid: # It should take its three dimensions as constructor parameters (numbers) # It should have a method called `get_surface` that returns the cuboid's surface # It should have a method called `get_volume` that returns the cuboid's volume class Cuboid(object): def __init__(se...
import os from random import randint from Bad_Guy import Bad_Guy from Hero import Hero from Goblin import Goblin from Store import Store print "What is thy name, brave adventurer?" hero_name = raw_input("> ") hero = Hero(hero_name) monsters = [] for i in range(0, number_of_enemies): rand_num = randint(0,1) if (r...
# Contrib modules # Core import os from random import randint # 3rd party # pygame for instance here # Custom modules from Good_Guy import Good_Guy from Bad_Guy import Bad_Guy from Battle import Battle from Store import Store from Hero import Hero from Medic import Medic from Goblin import Goblin from Vampire import V...
A = int(input("type an integer:")) B = int(input("another:")) print(str(A)"+"str(B)"="str(A+B))
class CoffeeMachine: def __init__(self): self.products = ['water', 'milk', 'beans', 'cups', 'money'] self.quantity = [400, 540, 120, 9, 550] # ingredients at start self.espresso_rec = [250, 0, 16, 1, 4] # espresso recipe self.latte_rec = [350, 75, 20, 1, 7] # latte recipe ...
numer,denom=1,1 def multiply(i,j,k,num,dum): num*=j dum*=k print i,j,k return num,dum for i in range (1,10): for j in range (10): for k in range(j+1,10): if i==j or i==k: continue if float(str(i)+str(j))/float(str(i)+str(k))==float(j)/float(...
def factorial (x,y=1): if x==0 or x==1: return 1 result=1 while x>y : result*=x x-=1 return result
# coding: UTF-8 #字符、数字转换 if 1: a = 'A' b = ord(a) print b if 1: a = 88 b = chr(a) print b #Unicode字符串:字符串前面加u #a = u'中文' #print a if 1: #Unicode 转换成UTF-8 a = u'你好啊' b = a.encode('utf-8') #这个在命令行里用python交互式进行验证更直观 print b,u'\nb的长度是',len(b) #utf-8 转换成Unicode c = b.decode('utf-8') print c,u'\nc的长度是',len...
import math import numpy as np def read_dataset(path, name='logistic', data_only = False): """ Given a .csv file path, separates the responsevector y from the data matrix X. Assumes all columns have headings, are numerical, and the response vector is the first column. Returns an instance of LogisticMo...
#!/usr/bin/env python3 """ Recursively converts absolute links to relative links and protocol-relative links to https links. """ import argparse import os import sys import lxml.html parser = argparse.ArgumentParser() parser.add_argument('path', help=('The path containing files with links to con...
# Refer to ising_model_1d for a brief introduction to the theory behind the ising model and what the monte carlo methods are. Here, we shall implement the ising model in a 2-dim lattice i.e spins are arranged in a uniform 2-dim grid pattern and given our dependence on nearest neighbor interaction, each spin has 4 neig...
#!/usr/bin/env python #1. Include a section line with your name: # Name: Alison Jing Huang -- jing01ucsb@gmail.com # ID: X111012 # Machine Learning with Tensorflow HW #2 # Due 6/10/2018 # Recreate the graph and visualize it in Tensorboard using: #1. Placeholder for an input array with dtype float32 and shape None #2....
def function(): print("Hello") # 10 if __name__ == '__main__': # print("Hello World") # print(Hello World) # # # x = 5 # variable = 6 # # if x == variable: # print("if", x, variable) # else: # print("else", x, variable) # # x = "hello" # variable = "hello" # # ...
import pandas as pd CITY_DATA = {'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv'} def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str...
#!/usr/bin/env python2 # encoding: windows-1252 import math def circumference(): # Implement your program here. Remember to ask the input from user radius = raw_input('Type the radius: ') result = float(radius) * 2 * math.pi to_print = "Circumference: " + str(result) print(to_print) if __name__ ...
#!/usr/bin/env python2 # encoding: windows-1252 def main(): # Implement your program here. Remember to ask the input from user first = raw_input('Type the first word: ') second = raw_input('Type the second word: ') if first in second: print 'The word ' + first + ' is found in the word ' + sec...
#!/usr/bin/env python2 # encoding: windows-1252 def main(): # Implement your program here. Remember to ask the input from user first = raw_input('First: ') last = raw_input('Last: ') total = 0 while int(first) <= int(last): total = int(total) + int(first) first = int(first) + 1 ...
#!/usr/bin/env python2 # encoding: windows-1252 def main(): # Implement your program here. Remember to ask the input from user first = raw_input('First: ') last = raw_input('Last: ') while int(first) <= int(last): print first first = int(first) + 1 if __name__ == "__main__": mai...
#!/usr/bin/env python2 # encoding: windows-1252 def multiplication(): a = 1337 b = 42 # Program your solution here. Remember to use variables a and b! result = a * b toPrint = str(a) + " * " + str(b) + " = " + str(result) print(toPrint) if __name__ == "__main__": multiplication()
#!/usr/bin/env python2 # encoding: windows-1252 def main(): list = [] list.append(1) list.append(2) list.append(3) list.append(4) list.append(5) print 'The sum: ' + str(sum_array(list)) # implement here the method sum_array def sum_array(list): # write your code here # note th...
#lex_auth_01269442963365068878 def find_factors(num): #Accepts a number and returns the list of all the factors of a given number factors = [] for i in range(2,(num+1)): if(num%i==0): factors.append(i) return factors def is_prime(num, i): #Accepts the number num and num/2 --> i...
#lex_auth_01269446157664256093 def check_prime(number): #remove pass and write your logic here. if the number is prime return true, else return false for i in range(2, number // 2 + 1): if number % i == 0: return False return True def rotations(num): l = [num] no_of_digits = ...
#lex_auth_0127382283825971201450 def max_frequency_word_counter(data): word = "" frequency = 0 data = data.lower() #start writing your code here #Populate the variables: word and frequenc unique_words = dict.fromkeys(set(data.split()), 0) for word in set(data.split()): unique_words...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool': self.x_depth = 0 self.y_depth = 0 self.x_par...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: index_dict = "abcdefghijklmnopqrstuvwxyz" def smallestFromLeaf(self, root: 'TreeNode') -> 'str': if root == None: ...
"""Function creates an astropy table containing information that is useful to generate postage stamp images with appropriate distributions of shapes, colors, fluxes, etc. TODO: 1) Add script to load DC2 catalog 2) Add option to load multiple catlogs(eg star , galaxy) """ import os import astropy.table def load_catlog...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 20 14:22:55 2019 @author: jerald """ import os from PIL import Image # resize the image class ResizeFile: def __init__(self): print("Resize File is ready") def getValue(self): #filePath,resizeFactor print("enter...
import csv import requests from bs4 import BeautifulSoup class WebScraping(): def test(self): page = requests.get("https://en.wikipedia.org/wiki/Bangalore") soup1 = BeautifulSoup(page.content, 'html.parser') all_text = [] #Getting the heading heading = soup1....
import pygame import math class Button: def __init__(self, text, shape, color, coords): self.text = text self.coords = coords self.color = color self.shape = shape def draw(self, win): if self.shape == 'p': font = pygame.font.SysFont('Arial', 17) ...
def JosephusProblem(n , k): if n==1: return 1 else: return (JosephusProblem(n-1 , k) + k-1) % n +1 print("JosephusProblem(43,2) = " , end=' ') print(JosephusProblem(43,2))
import heapq def HeapSort(A): output = [] heapq.heapify(A) while len(A) > 0: output.append(heapq.heappop(A)) return(output) def HeapSortInNondecreasingOrder(A): # Write your code here nd_heap = A[:] sorted_nd_heap = HeapSort(nd_heap) return(sorted_nd_heap)
# FOR LOOP # #range # # 1 argument, only stop, start is 0 by default # range(5) # # # 2 arguments, start and stop (inclusive and exclusive) # range(0, 5) # # # 3 arguments, start and stop (inclusive and exclusive) 3rd is the stepper # range(0, 5, 2) for i in range(0, 10): print(i) print("Give me a number") numb...
# TIMES TABLE # # 7 x 1 = 7 # 7 x 2 = 14 # 7 x 3 = 21 # ... # 7 x 10 = 70 # # ASK THE USER FOR A NUMBER AND SHOW THE TIMES TABLE FOR THAT NUMBER # # step 1 - do a loop and show the counter from 1 to 10 # step 2 - show the counter from 1 to 10 multiplied by the number variable. ex: number = 7 [7, 14, 21, ...] # step 3 -...
person = { "name": "Joe", "city": "HH", "age": 32 } person2 = { "name": "Mary", "city": "Berlin", "age": 33 } ppl = [] ppl.append(person) ppl.append(person2) print(ppl[1]["name"])
import math import random def circlePerimeter(radius): return radius * 2 * math.pi def circleArea(radius): return math.pow(radius, 2) * math.pi def somethingSilly(): x = random.randrange(0, 2) if x == 0: return print("I WILL MAYBE BE... 50% chance") print("What is the radius?") r = i...
# # def someFunction(number): # number = 21 # # a = 10 # someFunction(a) # print(a) person = { "name": "Joe", "age": 10 } listOfPpl = [] listOfPpl.append(person) person["name"] = "Mary" person["age"] = 21 listOfPpl.append(person) print(listOfPpl)
# # print("What's your name?") # name = input("> ") # # print("Hi " + name) a = 60 b = 7 c = 500 if a > b: if a > c: print(a) else: print(c) else: if b > c: print(b) else: print(c)
# PyBank homework assignment # First, import os and csv import os import csv # declare some variables vMonths = 0 vPL = None vDeltaPL = 0 vDeltaTotal = 0 vDeltaPLMax = ["MaxMon", 0] vDeltaPLMin = ["MinMon", 0] vTotalPL = 0 # set the path for the budget_data.csv file budget_csv = os.path.join("Resources", "budget_data...
import random import sys def startup(): a = "-" a1 = a.center(24, "-") game_name = "!GUESS THE NUMBER! |" game_name1 = game_name.center(25) print(a1+"\n|"+game_name1+"\n"+a1) range_num = random.randrange(1,100) ans_num = random.randrange(1,range_num) counting_tries = 0 chances = 5 startup() prin...
def dec(x): x=x-1 return x def add(x,y): return x+y class electro_bike: def __init__(self, speed, color): self.speed = speed self.color = color def 1_more_speed(self): self.speed += 1 x=3 y=2 if x>y: print(add(x,y)>dec(x))
#!/usr/bin/python3 if __name__ == "__main__": import sys len_argv = len(sys.argv) if len_argv == 1: sum = 0 else: sum = 0 while len_argv > 1: sum = sum + int(sys.argv[len_argv - 1]) len_argv -= 1 print("{}".format(sum))
#!/usr/bin/python3 """ Unittest for rectangle class""" import unittest from models.base import Base from models.rectangle import Rectangle from models.square import Square class testSquare(unittest.TestCase): """"Clase for unittest of Square class""" def setUp(self): """setup for all methods""" ...
#!/usr/bin/python3 def simple_delete(a_dictionary, key=""): all_keys = a_dictionary.keys() for i in all_keys: if i == key: del a_dictionary[i] return a_dictionary return a_dictionary
#!/usr/bin/python3 """request to the URL and displays the body of the response""" from urllib.request import urlopen from urllib.error import HTTPError from sys import argv if __name__ == "__main__": url = argv[1] try: with urlopen(url) as response: html = response.read() print...
''' This problem was asked by Google. Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): ...
''' The Fibonacci sequence is defined as follows: the first number of the sequence is 0, the second number is 1, and the nth number is the sum of the (n - 1)th and (n - 2)th numbers. Write a function that takes in an integer n and returns the nth Fibonacci number. Sample input: 6 Sample output: 5 (0, 1, 1, 2, 3, 5)...
import tensorflow as tf import numpy as np # Declare list of features. We only have one real-valued feature. There are many # other types of columns that are more complicated and useful. features = [tf.contrib.layers.real_valued_column("x", dimension=1)] # An estimator is the front end to invoke training (fitting) an...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair. MIT Licensed. Contact at www.sinclair.bio """ # Built-in modules # from datetime import datetime # Internal modules # from plumbing.cache import property_cached from plumbing.color import Color ############################################...
class Employee: def __init__(self, id, first_name, last_name): self.id = id self.first_name = first_name self.last_name = last_name self._salary = 0.0 def set_salary(self, salary): if not isinstance(salary, float) and salary <= 0.0: raise ValueError("Pay...
def shorten(text): """Make text shortened. :param str text: some text :rtype: str :return: shortened text """ text_split = text.split() result = [] for word in text_split: result.append(word[0]) short = ''.join(result).upper() return short def shorten2(text): "...
# Thanks to input() we can get information from users terminal name = input('Write your name: ') year = input('Write the year of your birth: ') year = int(year) age = 2021 - year print(f'{name} is {age} years old')
import random def get_number(): """Get number from user. Try until user give proper number. :rtype: int :return: given number as int """ while True: try: result = int(input("Chose the number: ")) break except ValueError: print("It's not a num...
import random def random_average(n): lst = [] while len(lst) < n: lst.append(random.randint(1, 100)) average = sum(lst) / len(lst) return f'Your numbers are: {lst}. Average is {average}' print(random_average(2))
def is_even(num): if num % 2 == 0: return True else: return False print(is_even(111)) def iterate_through(num): for i in range(1, num): if is_even(i): print(i, 'jest parzyste') else: print(i, 'jest nieparzyste') print(iterate_through(11))
def user_input(): """Return proper value provided by user. :rtype: str :return: value provided by user from ["too small", "too big", "you won"] """ possible_input = ["too small", "too big", "you won"] while True: user_answer = input().lower() if user_answer in possible_input: ...
def square_area(num1, num2): result = num1 * num2 return result print(square_area(2, 8))
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] summary = 0 for item in my_list: summary = summary + item print(summary)
class Sing: def __init__(self, text): self.text_list = text.splitlines() def __iter__(self): self.pointer = 0 return self def __next__(self): if self.pointer >= len(self.text_list): raise StopIteration result = self.text_list[self.pointer] self.p...
def insertion_sort(srcList): for r_idx in range(1, len(srcList)): key = srcList[r_idx] l_idx = r_idx - 1 while l_idx >= 0 and srcList[l_idx] > key: srcList[l_idx + 1] = srcList[l_idx] l_idx = l_idx - 1 srcList[l_idx + 1] = key print(srcList) lista = [...
import heapq import random def merge(lists): merged_list = [] heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) while heap: val, list_ind, element_ind = heapq.heappop(heap) merged_list.append(val) if element_ind + 1 < len(lists[list_ind]): ...
# Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. # # For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". def longest_substring(s, k): max_longest = "" for x in range(len(s)): used_...
def square(x): return x * x print(square(5)) def sum_of_square(x, y): return square(x) + square(y) print(sum_of_square(2, 3)) def a(x): return x * x print(a(5))
def sqrt(x): return sqrt_iter(1.0, x) def sqrt_iter(guess, x): if good_enough(guess, x): return guess else: print('1') return sqrt_iter(improve(guess, x), x) def good_enough(guess, x): return self_abs(guess * guess - x) < 0.001 def improve(guess, x): return (guess + (x ...
#! /usr/bin/python3 # 并发编程 # 2 判断线程是否已经启动 # 1 启动和停止线程 threading import time def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep(5) from threading import Thread #t = Thread(target=countdown, args=(10,)) t = Thread(target=countdown, args=(5,), daemon=True) # 后台执行 t.st...
#!/usr/bin/python3 #+ # A random scattering of coloured stars against a black background. # # Copyright 2015 by Lawrence D'Oliveiro <ldo@geek-central.gen.nz>. This # script is licensed CC0 # <https://creativecommons.org/publicdomain/zero/1.0/>; do with it # what you will. #- import sys import os import math import arr...
#!/usr/bin/python3 #+ # Generate discs with a Gray code <https://en.wikipedia.org/wiki/Gray_code>. # # Copyright 2018 by Lawrence D'Oliveiro <ldo@geek-central.gen.nz>. This # script is licensed CC0 # <https://creativecommons.org/publicdomain/zero/1.0/>; do with it # what you will. #- import sys import os import math i...
''' Write a main function to create an empty dictionary and a user-controlled loop to prompt for a widget name and quantity. Add the values to the dictionary as key(widget name) and value(quantity) pairs. After user decides to exit write data to file . ''' from src.homework.homework8 import add_inventory, remov...
''' DO NOT USE LISTS Create a function get_point_mutations that accepts two string parameters, dna_string1 and dna_string2 and returns the hamming distance of the strings., Problem Figure 2. The Hamming distance between these two strings is 7. Mismatched symbols are colored red. Given two strings s and t of...
import unittest #write the import statements to bring in homework 4 functions #valid_letter_grade, get_credit_points, get_grade_points, and get_grade_point_average from src.homework.homework4 import sample_function from src.homework.homework4 import valid_letter_grade from src.homework.homework4 import get_credi...
"""Path finder contains Actions for finding paths between nodes.""" import logging from typing import List import networkx as nx from Arbie.Actions import Action from Arbie.Variables import Pool, Token, Tokens, Trade from Arbie.Variables.graph import FilteredTradingGraph, TradingGraph class Node(object): """A ...
# -*- coding: utf-8 -*- """Object oriented grading of python modules. Defines an abstract base class, Tester, to be used for grading python modules. This module differs from standard testing strategies in two major ways. First, it relies on a correct implementation of the module, making the creation of test cases ver...
"""Command Line Interface (CLI) for the Phonebook project. To populate the phonebook, pass a csv file of data to stdin, formatted like this: Name,Phone Number Bob Smith,0123 45678 ... """ import csv import sys from .phonenumbers import Phonebook def determine_consistency(infile): book = Phonebook() reader...
def quarter_of(month): if month <= 3: return 1 if month <=6: return 2 if month <=9: return 3 if month <=12: return 4 elif month >= 13: return ('Bad number :(') print(quarter_of(11))
def div_con(x): str_list = [] num_list = [] for item in x: if isinstance(item, str): str_list.append(int(item)) else: num_list.append(int(item)) return (sum(num_list)-sum(str_list)) """" def div_con(lst): return sum(n if isinstance(n, int) else -int(n) for ...
def sort_reindeer(reindeer_names): lt = [x.split(' ')[1] for x in reindeer_names] return sorted(reindeer_names, key=lambda name: name.split()[1]) print(sort_reindeer(['Kenjiro Mori', 'Susumu Tokugawa', 'Juzo Okita', 'Akira Sanada']))
""" Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. """ class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return...
#Artilery Computer for Arma 3 import math #imports math functions for sqrt and sin cosine usage def angleinputA(): #prompts user to put compass bearing when pointing compass at target A = float(input('\nEnter the angle that the compass shows when pointing at the TARGET ')) return A def angleinputB():#prompts user ...
import cx_Oracle class Oracle(): """Esta clase conecta con la base de datos, ademas tambien podemos hacer insert, select, delete y update""" def __init__(self, host, user, password, port, tsname): """Constructor de la clase""" self.__host = host self.__user = user self.__password = password self.__port =...
#menghitung luas layangan diagonal1 = int(input("masukkan d1:")) diagonal2 = int(input("masukkan d2:")) #proses luas = 0.5*(diagonal1*diagonal2) #print print("Luas Layangan", luas) #menghitung rata-rata uang saku anak anakpertama = int(input("Uang saku anak pertama:")) anakkedua = int(input("Uang saku anak kedua:"))...
# %load student2.py class Student(object): def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age @property def age(self): return self._age @age.setter def age(self, age): if type(age) is not i...
""" Задание 2 Вычислить сумму кубов тех нечетных чисел от 0 до 1000, сумма цифр которых делится на 7 """ BASE = 10 # основание системы счичления def is_divides(number, divider=7): # возвращает True, если число делится на divider(по умолчанию 7) if number % divider == 0: return True return False de...
""" Задание 7 Реализовать проект «Операции с комплексными числами». Создать класс «Комплексное число». Реализовать перегрузку методов сложения и умножения комплексных чисел. Проверить работу проекта. Для этого создать экземпляры класса (комплексные числа), выполнить сложение и умножение созданных экземпляров. Проверить...
""" Задание 4 Реализуйте базовый класс Car: - у класса должны быть следующие атрибуты: speed, color, name, is_police (булево). А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда); - опишите несколько дочерних классов: TownCar, SportCar, WorkCar, Polic...
""" Задание 1 Написать функцию email_parse(<email_address>), которая при помощи регулярного выражения извлекает имя пользователя и почтовый домен из email адреса и возвращает их в виде словаря. Если адрес не валиден, выбросить исключение ValueError. """ import re def email_parse(email_address: str): """ Ret...
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread("../res/messi5.jpg", cv2.IMREAD_GRAYSCALE) # define kernel k_width = 3 k_height = 3 k_size = 3 kernel = [] # ## high pass filters (HPF): helps in finding edges in images # gradient is a directional change in the intensity / color of a...
"""Generate Markov text from text files.""" from random import choice def open_and_read_file(file_path): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ # your code goes here tex...