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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.