text
stringlengths
37
1.41M
# Import libraries import pandas as pd import numpy as np import math # Load datasets lifespans = pd.read_csv('familiar_lifespan.csv') iron = pd.read_csv('familiar_iron.csv') # Print out the first five rows of "lifespans" dataframe print(lifespans.head()) # Save life spans of subscribers to the "vein" pack into a va...
import random import numpy as np import matplotlib.pyplot as plt # create_binary_samples: # Given the data_size - the amount of samples we want, and the prob # which is the probability for a neuron spike, this outputs a binary # array which is supposed to be the "real" neuron data. def create_binary_samples(data_size...
import sys; sys.path.insert(0, '../') import geoplot as gplt import geoplot.crs as gcrs import geopandas as gpd import pandas as pd import numpy as np import matplotlib.pyplot as plt # Shape the data. manhattan = gpd.read_file("../../data/manhattan_mappluto/MNMapPLUTO.shp") manhattan['YearBuilt'] = manhattan['YearBui...
# Helper code to plot the sigmoid function. # # Eli Bendersky (http://eli.thegreenplace.net) # This code is in the public domain from __future__ import print_function import matplotlib.pyplot as plt import numpy as np from regression_lib import sigmoid if __name__ == '__main__': fig, ax = plt.subplots() fig....
# generates 1-dimensional data for linear regression analysis # # notes for this course can be found at: # https://deeplearningcourses.com/c/data-science-linear-regression-in-python # https://www.udemy.com/data-science-linear-regression-in-python import numpy as np N = 100 with open('data_1d.csv', 'w') as f: X =...
import numpy as np import math_utils import neural_net # Create some toy data to check your implementations input_size = 4 hidden_size = 10 num_classes = 3 num_inputs = 5 # The toy model is a 2-layer network: it has one hidden layer and one output # layer. def init_toy_model(): model = {} # Layer 1 has 10 ...
""" Activation functions implemented in NumPy """ # Sebastian Raschka 2016-2017 # # ann is a supporting package for the book # "Introduction to Artificial Neural Networks and Deep Learning: # A Practical Guide with Applications in Python" # # Author: Sebastian Raschka <sebastianraschka.com> # # License: MIT import nu...
import numpy as np # The Restricted Boltzmann Machine class class RBM: # The RBM Constructor # visible - The number of visible (input) nodes # hidden - The number of hidden (feature) nodes # The learning rate of the RBM, defaults to 0.1 def __init__(self, visible, hidden, learning_rate = 0.1): self.visi...
"""Computes a path between source vertex, s, and every other vertex in undirected graph G.""" class DepthFirstDirectedPaths(object): """This implementation uses depth-first search.""" def __init__(self, G, s): self.s = s # source vertex self.edgeTo = [None for i in range(G.V())] # edgeTo[v] = last edge on...
"""The Interval1D class represents a one-dimensional interval. The interval is closed - it contains both endpoints. Intervals are immutable: their values cannot be changed after they are created. The class Interval1D includes methods for checking whether an interval contains a point and det...
from . import calculation as calc def validate(cnpj_number): """This function validates a CNPJ number. This function uses calculation package to calculate both digits and then validates the number. :param cnpj_number: a CNPJ number to be validated. Only numbers. :type cnpj_number: string :r...
# version code d345910f07ae coursera = 1 # Please fill out this stencil and submit using the provided submission script. ## 1: (Task 1) Movie Review ## Task 1 def movie_review(name): """ Input: the name of a movie Output: a string (one of the review options), selected at random using randint """ ...
import numpy import cupy from cupy import core def arange(start, stop=None, step=1, dtype=None): """Returns an array with evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop). The first three arguments are mapped like the ``range`` built-in funct...
from cvxpy.expressions.expression import Expression def diff(x, k=1, axis=0): """ Vector of kth order differences. Takes in a vector of length n and returns a vector of length n-k of the kth order differences. diff(x) returns the vector of differences between adjacent elements in the vector, tha...
"""Functions to plot a Binary Search Tree.""" import pydot __copyright__ = "Copyright (C) 2016, DV Klopfenstein. All rights reserved." __author__ = "DV Klopfenstein" # -- Graphing of a Binary Search Tree (BST) --------------------------------- def wr_png(fout_png, nodes_bst, childnames, log): """Save tree figure...
""" Misc utils for deep internal usage of Python. """ import struct def infer_int_pack(arg) -> str: """ Attempt to infer the correct struct format for an int. :param arg: The integer argument to infer. :return: A character for the struct string. """ # Short if (-32768) <= arg <= 32767: ...
# Sebastian Raschka 2014-2017 # mlxtend Machine Learning Library Extensions # # Implementation of the mulitnomial logistic regression algorithm for # classification. # # Author: Sebastian Raschka <sebastianraschka.com> # # License: BSD 3 clause from matplotlib.pyplot import subplots from matplotlib.table import Table ...
class Task(object): ''' A Task defines a particular learning task (including reward-based problems, but not only). A Task also defines when an episode finished. ''' def __init__(self): pass def finished(self,world): ''' Tell if the world is in a final state (no more action can be applied) Args: -worl...
#!/usr/bin/env python2.7 # -*- coding:utf-8 -*- import random def gen_list(nums): res = range(nums) random.shuffle(res) return res #้ป˜่ฎคไปŽๅฐๅˆฐๅคงๆŽ’ๅบ def insertion_sort(sort_list): if len(sort_list) <= 1: return sort_list for i in range(len(sort_list)): for j in range(i,len(sort_list)): ...
frase = 'Curso em video Python' print(frase[2]) print(frase.count('0')) #conta as casas da frase print(len(frase.strip())) print(frase.replace('Python', 'Android')) frase = frase.replace('Python', 'Android') print(frase) dividido = frase.split() print(dividido[0])
pessoas = {'nome': 'FreiFox', 'sexo': 'M', 'idade': 23} print(pessoas) print(pessoas['nome']) print(pessoas.items()) print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos') for k,v in pessoas.items(): print(f'{k} = {v}')
num=int(input('Tabuada de: ')) n=num while
from random import randint p = int() t = 0 ran = randint(0, 10) print(ran) while p != ran: p = int(input('Digite seu palpite ente 0 e 10: ')) t += 1 if p == ran: print('voce acertou com {} tentativas '.format(t)) elif p != ran: print('Tente novamente') i...
def escreva(*lista): pos = 0 while pos < len(lista): print('~'*len(lista[pos])) print(lista[pos]) print('~'*len(lista[pos])) pos += 1 frase1 = 'Frase' frase2 = 'Frase grande' frase3 = 'Frase muito mais grande' escreva(frase1, frase2, frase3) def frase(): print('x...
numeros = list() while True: r = 0 n = int(input('Digite um valor: [000 para sair] ')) if n not in numeros: numeros.append(n) print('Valor adicionado com sucesso...') else: print('Valor duplicado! Nรฃo adicionado.') if n == 000: break print('=-' *30) numeros.sort() pr...
print('Para sair do programa digite -X- ') c = '' while c !='X' : c = str(input('Informe seu sexo: [M/F]')).upper() if c == 'M': print('Masculino') elif c == 'F': print('Femenino') elif c != 'M' and c != 'F': print('Erro digite apenas F ou M')
s = 0 for c in range(1,7): n = int(input('Digite um valor: ')) if n % 2 == 0: s = s + n print('A soma dos pares foi > {}'.format(s))
temp = [] princ = [] while True: temp.append(str(input('Nome: '))) temp.append(float(input('Peso: '))) if len(princ) == 0: mai = men = temp[1] else: if temp[1] > mai: mai = temp[1] if temp[1] < men: men = temp[1] princ.append(temp[:]) ...
# Rock Paper Scissor import random import sys #begin the game and then loop after the first play def play(): while True: p_choice + input ("Choose your weapon") cpu_random = random.randint(1,3) cpu_choice + cpu_random if cpu_random == 1: cpu_choice = "rock" elif...
""" Models: 1. 'distilbert-base-nli-mean-tokens' 2. 'quora-distilbert-multilingual' (multilingual) Steps: 1. Create pytorch model for text classification (explain each step with running the intermediate code) 2. Add Testing with training data using random model 3. Add Optimizer (Adam) and Loss function (CrossEnt...
""" Unit tests for the Ship class """ import unittest from unittest.mock import MagicMock, PropertyMock from bot_heard_round.ship import ShipType, Ship class TestShip(unittest.TestCase): """ Unit tests for the ship class """ def test_can_convert_to_str_and_back(self): """ Test that w...
""" Unit tests for fleet list """ import unittest from bot_heard_round import emoji from bot_heard_round.fleet import FleetList, CombatColumn from bot_heard_round.ship import Ship, ShipType class FleetListTest(unittest.TestCase): """ Tests for fleet list """ def test_base_columns_are_all_waiting(sel...
# The class's name is in snake case, because of the condition of the task. class take_skip: def __init__(self, step: int, count: int): self.step = step self.count = count self.current = 0 self.counter = 1 def __iter__(self): return self def __next__(self): ...
import unittest from currency import * currencytest = Currency(5, "USD") currencytest1 = Currency(4.99, "EUR") currencytest2 = Currency(4.99, "EUR") currencytest3 = Currency(6.99, "EUR") class TestCurrency(unittest.TestCase): def test_eq(self): self.assertTrue(currencytest1 == currencytest2) self...
num=int(input()) result=0 while(num!=0): digit=num%10 result=result*10+digit num=num//10 print(result)
lst=[1,3,4,5,6,7,9,10] #sum=0 # for num in lst: # sum=sum+num # print(sum) print(sum(lst))
num1=10 num2=20 print("before swaping num1=",num1,"num2=",num2) num=num1 num1=num2 num2=num print("after swaping num1=",num1,"num2=",num) #using input functn a=input("enter the num1") b=input("enter the num2") print("before swaping num1=",a,"num2=",b) temp=a a=b b=temp print("after swaping num1=",a,"num2=",b)
# Ler um valor e escrever se รฉ positivo ou negativo (considere o valor zero como positivo) n = float(input('Digite um Numero:')) if n > 0: print('POSITIVO!') elif n == 0: print('POSITIVO!') else: print('NEGATIVO!')
# Escreva um algoritmo para ler um valor (do teclado) e escrever (na tela) o seu antecessor. (SOMENTE NUMERO INTEIRO) num = int(input('Digite um valor na tela: ')) res = num - 1 print(res)
# Uma revendedora de carros usados paga a seus funcionรกrios vendedores um salรกrio fixo por mรชs, # mais uma comissรฃo tambรฉm fixa para cada carro vendido e mais 5% do valor das vendas por ele # efetuadas. Escrever um algoritmo que leia o nรบmero de carros por ele vendidos, o valor total de suas # vendas, o salรกrio fixo e ...
sum = lambda x,y: x+y #i = input() #k = input() #print(sum(i,k)) num_lines = input() for i in range(0,num_lines): two = raw_input() a = int(two.split(' ')[0]) b = int(two.split(' ')[1]) print(sum(a,b))
# This function is used in order to delay AI decisions in order to make them appear "human" from time import sleep import pickle, socket, select, random def main_menu(): """ Purpose: Operate the main menu of the program. Arguments: None. Returns: N...
def pythonic_quick_sort(a): if len(a) <= 1: return a pivot = a[-1] pivots = [i for i in a if i == pivot] left = pythonic_quick_sort([i for i in a if i < pivot]) right = pythonic_quick_sort([i for i in a if i > pivot]) return left + pivots + right
def make_tree(seq): tree = {} for item in seq: tree = _make_tree(item, tree) return tree def _make_tree(item, tree): if not tree: tree[item] = {'left': {}, 'right': {}} else: last_key = tree.keys()[0] if item > last_key: _make_tree(item, tree[last_key]['...
#Brute Force cost=[10,15,20] def minCostClimbingStairs1(cost): n=len(cost) cost.append(0) return minCost1(n,cost) def minCost1(n,cost): if n<0: return 0 elif n==0: return cost[n] elif n==1: return cost[n] return cost[n]+min(minCost1(n-1,cost),minCost1(n-2,cost)) ...
# Import game that allows us to use certain functions. # Import random to allow us to generate random numbers import pygame import random # Initializesz the modules pygame.init() # Create the dimensions of the screen screen_width = 780 screen_height = 340 screen = pygame.display.set_mode((screen_width,screen_height)) #...
""" project euler 15 https://projecteuler.net/problem=15 by: Nir Lattice paths https://www.includehelp.com/python/math-factorial-method-with-example.aspx combinatorics problem- need to get from the top left corner to the bottom right corner of an N*N grid. making N moves right and N moves down in some order. ...
""" project euler 38 https://projecteuler.net/problem=38 by: Nir Pandigital multiples """ def Is_valid_array(array, valid_values): for v in array: if v not in valid_values: return False return True def Set_digits_counter(number, digits_counter): for d in str(number): ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 28 00:53:09 2015 @author: Ashish """ def dec2bin( decnum, width ): ''' converts a decimal number to list of biinary numbers of specified width appends 0's at the MSBs if binary number has bits less than width ''' binlist = [int(x) for x in bin(decnum)...
#1 print("Hello World") #2 print("๊ฐ•ํ•œ์นœ๊ตฌ ๋Œ€ํ•œ์œก๊ตฐ") #3 print("\ /\\") print(" ) ( \')") print("( / )") print(" \\(__)|") #4 print("|\\_/|") print("|q p| /}") print("( 0 )\"\"\"\\") print("|\"^\"` |") print("||_/=\\\\__|") #5 from sys import stdin A, B = map(int, stdin.readline().split()) C = A + B print...
#1.็ˆฌๆฅผๆขฏ def climbStairs(self, n: int) -> int: if n <= 2: return n a = 1 b = 2 for i in range(3,n+1): t = b b = a + b a = t return b
import shape_areas_oop as sao def main(): # circle--- circle = sao.Shape() circle.set_radius(2) print("Area of a circle: ", f"{circle.get_circle_area():.2f}") # square--- square = sao.Shape() square.set_side(3) print("Area of a square: ", f"{square.get_square_area():.2f}") ...
x = input("Skriv inn et tall:") from random import * y = randint(0, 9) y = str(y) z = x + y z = int(z) x = int(x) y = z / x y = round(y, 2) print(z, "/", x, "=", y)
# Lotto coding import random #numbers = random.sample(range(1,46), 6) #numbers.sort() #print("ํ–‰์šด์˜ ์ˆซ์ž๋Š”{}".format(numbers)) #print(f'ํ–‰์šด์˜ ์ˆซ์ž๋Š”{numbers}!!') for i in range(5): numbers = random.sample(range(1,46), 6) numbers.sort() print(numbers) # print(numbers)
import sys sys.stdin = open("binary_search_input.txt") def binary_search(start, end, page): count = 0 while start <= end: count += 1 test = int((start + end) / 2) if test == page: return count elif page < test: end = test else: start ...
import numpy as np def sigmoid(Z): """ Implements the sigmoid activation in numpy Arguments: Z -- numpy array of any shape Returns: A -- output of sigmoid(z), same shape as Z cache -- returns Z as well, useful during backpropagation """ A = 1 / (1 + np.exp(-Z)) cache = Z ...
import math sig = lambda x: 1 / (1 + math.pow(math.e, -x)) weights = [0.5, -0.3, -0.04, 0.2, 0.06, -0.15] i1 = 1 i2 = 0.5 actual = 1 def forward(w, i1, i2): """ :param w: list, the weights for the NN :param i1: float, the first input :param i2: float, the second input :return: float...
""" ID: ashayp21 LANG: PYTHON3 TASK: castle """ fin = open ('castle.in', 'r') fout = open ('castle.out', 'w') vals = fin.read().splitlines() #gets every line first_line = vals[0].split(" ") M = int(first_line[0]) N = int(first_line[1]) plan = [] #creates the plan for i in range(N): row_string = ...
a = int(input('์ˆซ์ž๋ฅผ ์—ฌ๊ธฐ ์ž…๋ ฅํ•˜์„ธ์š”: ')) for i in range(a): for j in range(a - 1): if j < i: print(' ', end='') else: print('*', end='') for f in range(a - i): print("*",end="") print()
from datetime import datetime odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59] now_now = datetime.today().second if now_now in odds: print("This is an odd second :-| ") else: print("So even")
class Garrage: def __init__(self): self.name=[] def __len__(self): return len(self.name) def __getitem__(self,i): return self.name[i] about=Garrage() about.name.append("i10") about.name.append("i20") about.name.append("Verna") about.name.append("Creta") about.name.append("i30") pri...
from file_handle import get_data_from_file from sample_data import sample_data ALL_LAB_BLOCKS = ["S","T","U","X","Y","Z","V","AA","BB","W","CC"] # eg. {'A': [4, 3, 4, 3], 'B': [7, 0, 7, 0]} # first element in list -> num of lecture time block # second element in list -> num of lab time block # third element in list -...
import time #Allows you to use the time.sleep(seconds) function to pause the terminal from doing any operation for a number of seconds print("ASCII TITLESCREEN GOES HERE") time.sleep(2) #terminal sleeps for 2 seconds print("\nYou awake in your plane seat") #Plus any more intro text you may want def main()...
space1 = "X" space2 = "X" space3 = "0" space4 = "" space5 = "" space6 = "0" space7 = "0" space8 = "0" space9 = "0" print("\n \033[1;32;40m | | ") print(" {} | {} | {} ".format(space1, space2, space3)) print(" | | ") print("-----------") print(" | | ") print(" {} | {} | {} ".format(s...
breakfast = "frosties" lunch = "smoked salmon sandwiches" dinner = "mushroom blintzes" #print ("This morning i had " + breakfast + " for my breakfast followed by some deliciouse " + lunch + " and " + dinner + " for dinner.") #print( "This morning i had {}".format(breakfast) + " for my breakfast followed by some d...
def gcd(x,y): return gcd(y,x % y) if y > 0 else x def lcm(a, b): return ((a*b) // gcd(a,b)) while(1): try: x,y = (int(x) for x in input().split()) print(gcd(x,y),lcm(x,y)) except: break
print(input().replace("apple","_").replace("peach","apple").replace("_","peach"))
# reverse def print_board(board): print(' 1 2 3 4 5 6 7 8' ) br = 1 for i in board: print(br, end=' ') br+=1 for j in i: print(j, end=' ') print('') def applay_to_board_bottom(board,player,i,j): br = 0 i+=1 k = i while ...
# ### Problem 1: # Create two variables. One should equal โ€œMy name is: โ€œ and the other should equal your actual name. # Print the two variables in one print message. # temp1= ("My name is: ") myName = ("Rachel") print(temp1 + myName) # ### Problem 2: # Ask the user to enter the extra credit they earned. If they en...
#!/usr/bin/python3 if __name__ == "__main__": from sys import argv numarg = len(argv) num = 0 for i in range(1, numarg): num += int(argv[i]) print("{}".format(num))
###Bikeshare python project to be uploaded into GitHub import time import pandas as pd import numpy as np 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 ...
# -*- coding: utf-8 -*- import sys if __name__ == "__main__": param = sys.argv obj = open("test.txt", "w") for value in range(100): print >> obj, value if value == 20: print >> obj, u"for roop is 20 over!!!!" sys.exit()
import numpy as np from math import log def calculate_variance(X): """ Return the variance of the features in dataset X """ return np.var(X,axis=0) def calculate_entropy(y, base=2): """ Calculate the entropy of label array y Parameters: ------------------------ y: np.array ...
from __future__ import division import numpy as np from scipy.special import expit from .activation_functions import Sigmoid import math import copy class Loss(object): def loss(self,y_true,y_pred): pass def gradient(self,y_true,y_pred): pass class SquaredLoss(Loss): def __init__(self): ...
def M(): for row in range(6): for col in range(5): if (col==0 or col==4) or (row<3 and (row-col==0 or row+col==4)): print("*",end=" ") else: print(end=" ") print()
def X(): for row in range(7): for col in range(7): if (row-col==0 or row+col==6): print("*",end=" ") else: print(end=" ") print()
__author__ = "Geoffrey Bachelot" def is_palindrome(string): return string == string[::-1] if __name__ == "__main__": user_input = input("Input your string: ") if is_palindrome(user_input): print(f'{user_input} is a palindrome.') else: print('Nope!')
# Tugas 1.3 Pelatihan Basic Python AI Indonesia standart = 70 #standart nilai kelulusan teori = int (input("Nilai Teori = ")) #tipe data untuk nilai integer praktek = int (input("Nilai Praktek = ")) #tipe data untuk nilai integer if ((teori >=...
# Tugas 1.1 Pelatihan Basic Python AI Indonesia nama = input("Nama = ") #input data masih bertipe string umur = input("Umur = ") #input data masih bertipe string tinggi = input("Tinggi = ") #input data masih bertipe string print ("Nama saya " + nama + ", umur saya " + umur + ", tinggi saya "+ ting...
""" Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. """ start = 2000 end = 3200 def filter_numbers(): result = filter(lambda x: x%7 =...
#!/usr/bin/python3 """ Module content base.py - Create a Base class for other classes to inherit from """ import json import csv class Base: """ Base class to inherit from """ __nb_objects = 0 def __init__(self, id=None): """ Initialization constructor method """ if (id is not None): ...
#๋‹ค์Œ ์†Œ์Šค ์ฝ”๋“œ์—์„œ Date ํด๋ž˜์Šค๋ฅผ ์™„์„ฑํ•˜์„ธ์š”. is_date_valid๋Š” ๋ฌธ์ž์—ด์ด ์˜ฌ๋ฐ”๋ฅธ ๋‚ ์งœ์ธ์ง€ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฉ”์„œ๋“œ์ž…๋‹ˆ๋‹ค. #๋‚ ์งœ์—์„œ ์›”์€ 12์›”๊นŒ์ง€ ์ผ์€ 31์ผ๊นŒ์ง€ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. class Date: @staticmethod def is_date_valid(date_string): year, month, day = map(int, date_string.split('-')) return month <= 12 and day <= 31 if Date.is_date_valid('2000-10-31'): print('...
# ์ฃผ์‚ฌ์œ„ ๊ตด๋ฆฌ๋Š” ํ”„๋กœ๊ทธ๋žจ import random #์ž„์˜์˜ ๊ฐ’์„ ์–ป๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•˜๋Š” random ๋ชจ๋“ˆ์„ ๊ฐ€์ ธ์˜จ๋‹ค. #์ฒ˜์Œ ์‹œ์ž‘ n = random.randint(1,6) #1์—์„œ 6๊นŒ์ง€์˜ ์ •์ˆ˜ ์ค‘์— ํ•˜๋‚˜๋ฅผ ๋ฝ‘๋Š”๋‹ค. print("๊ฒฐ๊ณผ : ", n) n = random.randint(1,6) print("๊ฒฐ๊ณผ : ", n) n = random.randint(1,6) print("๊ฒฐ๊ณผ : ", n) # ๋งค๊ฐœ ๋ณ€์ˆ˜๊ฐ€ ์—†๋Š” ํ•จ์ˆ˜ ์ •์˜ํ•˜๊ธฐ import random # ํ•จ์ˆ˜ ์‚ฌ์šฉ --์˜๋ฏธ ํŒŒ์•…์ด ์‰ฌ์›Œ์ง€๊ณ  ์ˆ˜์ •์ด ์‰ฝ๋‹ค. def rolling_dice(): n =...
# ์ •์  ๋ฉ”์„œ๋“œ๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜์— self๋ฅผ ์ง€์ •ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. # @staticmethod์ฒ˜๋Ÿผ ์•ž์— @์ด ๋ถ™์€ ๊ฒƒ์„ ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋ผ๊ณ  ํ•˜๋ฉฐ ๋ฉ”์„œ๋“œ(ํ•จ์ˆ˜)์— ์ถ”๊ฐ€ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. # ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋Š” 'Unit 42 ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ ์‚ฌ์šฉํ•˜๊ธฐ'์—์„œ ์ž์„ธํžˆ ์„ค๋ช…ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. # ๋ง์…ˆ๊ณผ ๊ณฑ์…ˆ์„ ํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. class Calc: @staticmethod def add(a, b): print(a + b) @staticmethod def mul(a, b): print(a * b) Calc.add(10, ...
def sum(*numbers): sum_value = 0 for number in numbers: sum_value = sum_value + number return sum_value result = sum(1,3) print("1 + 3 = ", result) print("1 + 3 + 5 + 7 = ", sum(1,3,5,7))
# ๊ธฐ๋ณธ์ ์ธ for๋ฌธ # range() ํ•จ์ˆ˜์˜ ๊ฐ ๊ฒฐ๊ณผ๊ฐ€ ๋ณ€์ˆ˜๋กœ ๋Œ€์ž…๋˜์–ด ๋ฐ˜๋ณตํ•œ๋‹ค. for x in range(3, 9, 2): print(x) # ๋ฌธ์ž์—ด์˜ ๊ฐ ๋ฌธ์ž๊ฐ€ ํ•˜๋‚˜์”ฉ ๋ณ€์ˆ˜๋กœ ๋Œ€์ž…๋˜์–ด ๋ฐ˜๋ณตํ•œ๋‹ค. for ch in "LOVE": print(ch) # ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ ์š”์†Œ๊ฐ€ ํ•˜๋‚˜์”ฉ ๋ณ€์ˆ˜๋กœ ๋Œ€์ž…๋˜์–ด ๋ฐ˜๋ณตํ•œ๋‹ค. for item in ["ํž™ํ•ฉ", "๋ฐœ๋ผ๋“œ"]: print(item + "์ฆ๊ฒจ๋“ฃ๋Š”๋‹ค.") # ํŠœํ”Œ์˜ ๊ฐ ์š”์†Œ๊ฐ€ ํ•˜๋‚˜์”ฉ ๋ณ€์ˆ˜๋กœ ๋Œ€์ž…๋˜์–ด ๋ฐ˜๋ณตํ•œ๋‹ค. for item in (2560, 1440): print(item) # ๋”•์…”๋„ˆ๋ฆฌ์˜ ...
# 1๋ถ€ํ„ฐ 100๊นŒ์ง€ ์ˆซ์ž ์ถœ๋ ฅ for i in range(1, 101): # 1๋ถ€ํ„ฐ 100๊นŒ์ง€ 100๋ฒˆ ๋ฐ˜๋ณต print(i) # 3์˜ ๋ฐฐ์ˆ˜์™€ 5์˜ ๋ฐฐ์ˆ˜์ผ ๋•Œ ์ˆซ์ž ๋Œ€์‹  'Fizz', 'Buzz'๋ฅผ ์ถœ๋ ฅ for i in range(1, 101): # 1๋ถ€ํ„ฐ 100๊นŒ์ง€ 100๋ฒˆ ๋ฐ˜๋ณต if i % 3 == 0: # 3์˜ ๋ฐฐ์ˆ˜์ผ ๋•Œ print('Fizz') # Fizz ์ถœ๋ ฅ elif i % 5 == 0: # 5์˜ ๋ฐฐ์ˆ˜์ผ ๋•Œ print('Buzz') # Buzz ์ถœ๋ ฅ ...
stack=[] num=int(input()) for i in range(0,num): str=input() if str=="pop": if len(stack)==0: print("-1") else: print(stack[0]) del stack[0] elif str=="size": print(len(stack)) elif str=="empty": if len(stack)==0: print(...
# ํšจ์œจ์„ฑ 0 ์ ...ใ… .ใ…  .. ๋‹ค ๊ตฌํ•ด์„œ ๊ทธ๋Ÿด๊นŒ? ############## for๋ฌธ ############## # def solution(n): # global tmp_list # tmp_list = [0 for _ in range(0, n)] # tmp_list[0:2] = [0, 1, 1] # # for i in range(0, n+1): # if i < 3: # #print('i<3', i, tmp_list[i] ) # pass # # else : # ...
from sys import stdin for line in stdin: print(line, end='') # ์ด๊ฑฐ๋Š” ์•ˆ๋˜๋„น..!! # from sys import stdin # while True: # try: # print(stdin.readline(), end='') # except EOFError: # break # ์ด๊ฑฐ๋Š” ๋˜๊ณ !! # while True: # try: print(input()) # except EOFError: # break
## ๊ธฐ์ˆ˜ ์ •๋ ฌ : ์ž๋ฆฟ์ˆ˜๋กœ ์ •๋ ฌ / queue ์ด์šฉ ## digit_number = (num / position) % 10 ## 100์˜ ์ž๋ฆฌ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด : 2341 -( 100์œผ๋กœ ๋‚˜๋ˆˆ ๋ชซ )-> 23 -( 10์œผ๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€ )-> 3 # map? # nums = list( map(lambda x :( int(x) / position ) % 10, li )) #[5, 0, 0, 6, 0, 9, 3, 7] def radix(li): is_sorted = False position = 1 while not is_...
class Node : def __init__(self, data, next=None): self.data = data self.next = next def init(): global node1 node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node1.next = node2 node2.next = node3 node3.next = node4 def delete(del_data): global ...
# # Write a program that prints out the first 25 Fibonacci numbers. (The Fibonacci sequence starts as with 0,1 and next number is the sum of the two previous numbers) # Extend the program to also print the ratio of successive numbers of the sequence. # # prev_2 - One before previous number # prev_1 - Previous number...
# # Write a program that prints out the square of the first # 20 integers a block such that the block has a dimension of 4x5. # # range(i,j) produces a list of numbers from i -> j-1 for i in range(1,21): print str(i*i).center(3), # center is a function for strings that centers the contesnt to the given widt...
# Write a program that creates a dictionary and initializes it with 5 names/ID pairs. ## Create a function that prints out the dictionary in a nicely formatted table; ## Update the dictionary with another 5 name/values and reprint the table, ## making sure you understand the ordering within the map. def format...
class A: aa = 1 def __init__(self, x, y): self.x = x self.y = y a = A(2,3) A.aa = 11 a.aa = 100 print(a.x, a.y, a.aa) print(A.aa) b = A(3,5) print(b.aa)
''' ็บฟ็จ‹็š„ไธ€ไธชๅ…ณ้”ฎ็‰นๆ€งๆ˜ฏๆฏไธช็บฟ็จ‹้ƒฝๆ˜ฏ็‹ฌ็ซ‹่ฟ่กŒไธ”็Šถๆ€ไธๅฏ้ข„ๆต‹ใ€‚ๅฆ‚ๆžœ็จ‹ๅบไธญ็š„ๅ…ถไป–็บฟ็จ‹้œ€่ฆ้€š่ฟ‡ๅˆคๆ–ญๆŸไธช็บฟ็จ‹็š„็Šถๆ€ๆฅ็กฎๅฎš่‡ชๅทฑไธ‹ไธ€ๆญฅ็š„ๆ“ไฝœ๏ผŒ่ฟ™ ๆ—ถ็บฟ็จ‹ๅŒๆญฅ้—ฎ้ข˜ๅฐฑไผšๅ˜ๅพ—้žๅธธๆฃ˜ๆ‰‹ใ€‚ไธบไบ†่งฃๅ†ณ่ฟ™ไบ›้—ฎ้ข˜๏ผŒๆˆ‘ไปฌ้œ€่ฆไฝฟ็”จ threading ๅบ“ไธญ็š„ Event ๅฏน่ฑกใ€‚ Event ๅฏน่ฑกๅŒ…ๅซไธ€ไธชๅฏ็”ฑ็บฟ็จ‹่ฎพ็ฝฎ็š„ไฟก ๅทๆ ‡ๅฟ—๏ผŒๅฎƒๅ…่ฎธ็บฟ็จ‹็ญ‰ๅพ…ๆŸไบ›ไบ‹ไปถ็š„ๅ‘็”Ÿใ€‚ๅœจๅˆๅง‹ๆƒ…ๅ†ตไธ‹๏ผŒevent ๅฏน่ฑกไธญ็š„ไฟกๅทๆ ‡ๅฟ—่ขซ่ฎพ็ฝฎไธบๅ‡ใ€‚ๅฆ‚ๆžœๆœ‰็บฟ็จ‹็ญ‰ๅพ…ไธ€ไธช event ๅฏน่ฑก๏ผŒ่€Œ่ฟ™ไธช event ๅฏน่ฑก็š„ๆ ‡ๅฟ—ไธบๅ‡๏ผŒ้‚ฃไนˆ่ฟ™ไธช็บฟ็จ‹ๅฐ†ไผš่ขซไธ€็›ด้˜ปๅกž็›ด่‡ณ่ฏฅๆ ‡ๅฟ—ไธบ็œŸใ€‚ไธ€ไธช็บฟ็จ‹ๅฆ‚ๆžœๅฐ†ไธ€ไธช event ๅฏน่ฑก็š„ไฟกๅทๆ ‡ๅฟ—่ฎพ็ฝฎไธบ็œŸ๏ผŒๅฎƒๅฐ†ๅ”ค้†’ๆ‰€ๆœ‰็ญ‰ๅพ…่ฟ™ไธช event ๅฏน่ฑก็š„็บฟ็จ‹ใ€‚ๅฆ‚ๆžœไธ€ไธช็บฟ็จ‹็ญ‰ๅพ…ไธ€ไธชๅทฒ็ป่ขซ่ฎพ...
import math class Lead: def __init__(self , name , staff_size , estimated_revenue , effort_factor): self.name = name self.staff_size = staff_size self.estimated_revenue = estimated_revenue self.effort_factor = effort_factor def __get_digit(self , op): return len(str(math...
def add_four(func): def wrapper_func(*args, **kwargs): print("We're adding 4") result = func(*args, **kwargs) return result + 4 return wrapper_func def double(func): def wrapper_func(*args, **kwargs): print("We're doubling") result = func(*args, **kwargs) re...
import csv import codecs import sqlite3 class CSVTable(object): def __init__(self, csv_file, csv_encoding): self.csvreader = CSVReader(csv_file, csv_encoding) def create(self, filepath, tablename): self.con = sqlite3.connect(filepath) self.con.text_factory = str self.ta...