text stringlengths 37 1.41M |
|---|
n=int(input())
i=1
while i**2<n:
print (i**2)
i+=1
|
x = input('Введите х: ') # возвращается строка, не число
x=float(x) # преобразуем строку в вещественное число
y=x**5-2*x**3+1
y=str(y)
print('y = ' + y)
|
import DeepLearningModel
import glob
import numpy as np
FREQUENCY = 200 # Frequency the microcontroller collected data
TARGET_FREQUENCY = 50 # Frequency to scale collected data to / Frequency of the TensorFlow model
modelName = 'TensorFlowModel' # The name of the model used for saving / lo... |
from numpy import *
#from array import *
arr=array([1,2,3,4,5,6])
arr2=arr
print(id(arr))
print(id(arr2))
arr[1]=12
print(arr)
print(arr2)
arr3=arr.view()
#view() uses sghallow copy internally and any modification done on
#one array reflects the changes automatically in the other array
print(arr)
print(i... |
"""x=1
while x <= 4:
print("San")
x=x+1
print("Exit_loop")
"""
i = 1
while i<=4:
print("SAndeep " , end="")
j=1
while j<=2:
print("DHONI",end="")
j=j+1
i=i+1
print()
print("EXIT_LOOP") |
from numpy import *
arr=array([1,2,3])
arr2=array([10,20,30])
for i in range(len(arr)):
arr[i]=arr[i]+arr2[i]
print(arr) |
from dictionnaire import villes
from math import *
from time import *
def livraison(depart, arrivee):
vitesse_m = 0
distance_trajet = villes[depart][arrivee] * 1000
distance_parcourue = 0
temps_s = 0
t_avant_pause = 0
pause = False
nb_Pause = 0
distance_restante = 0
while (distance_... |
import heapq
i = 0
arr = []
while True:
i = int(input())
if i == 0:
print(-heapq.heappop(arr))
elif i == -1:
break
else:
heapq.heappush(arr, i)
print(arr)
# while True:
# i = int(input())
# if i == 0:
# arr.sort()
# print(arr.pop(0))
# elif i =... |
arr = input()
stack=[]
for x in arr:
if x.isdecimal():
stack.append(int(x))
elif x == '(' or x == ')':
continue
else:
n1 = stack.pop()
n2 = stack.pop()
if x == '+':
stack.append(n2 + n1)
elif x == '-':
stack.append(n2 - n1)
eli... |
import pickle
file = open('word_list.txt', 'rb')
# loading the words in a list
dictionary = pickle.load(file)
# code for bi-gram
bi_gram_list = []
word_no = 0 # to position a word in dictionary
for word in dictionary:
word_length = len(word)
if word_length < 2:
bi_gram_list.append... |
#第一题两种方式不换横
'''
a = 1
while a<5001:
if a%5 == 0 and a%7 == 0:
print(a,end =" ")
a+=1
for a in range (1,5001,1):
if a%5 == 0 and a%7 == 0:
print(a,end=" ")
'''
'''
import random
s = random.randint(1,100)
a = 1
while a<11:
c = int(input("请输入数字"))
if c > s:
print("比%d小小小"%c)
elif c < s:
print("比%d大大大"%c)
e... |
# 选区类
print("❤"*78)
class Xuanqu(object):
# 类 属性 通过它可以满足条件(不满足条件为假)
is_login = False
def denglu(self):
print("欢迎进入CS游戏选区界面\t 请您选区:\t电信A区 \t网通B区")
print("❤"*78)
A = input("请输入区域(A)或(B)进入游戏:")
if A == A or A == B:
print("欢迎进入登录界面")
print("❤"*78)
def zhang(self):
count = 1
while count <= 3:
pri... |
def q():
list = []
for i in range(2,101):
a = True
for a in range(2,i):
if i%a == 0:
a = False
break
if a:
list.append(i)
print(list)
print(result)
|
#author=dipendra ale
def show_menu():
menu = "choose the option below " + "\n\t1: show_all_employees"\
"\n\t2: show_employee" \
"\n\t3: change salary "\
"\n\t4: add_employee"\
... |
with open("input_02.txt", "r") as f:
list = f.read().splitlines()
count = 0
for line in list:
beforeColon = line.split(":")[0]
password = line.split(":")[1].strip()
numbers = beforeColon.split()[0]
lowerBound = numbers.split("-")[0].strip()
upperBound = numbers.spli... |
__author__ = 'yan'
# rock-paper-scissors-lizard-Spock
# encode roles with numbers
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
import random
def number2Name(num):
if num == 0 :
return "rock"
elif num == 1 :
return "Spock"
elif num == 2 :
retu... |
import threading
import time
def deletrea_palabra(palabra, periodo):
for caracter in palabra:
time.sleep(periodo)
print(caracter.upper())
thread1 = threading.Thread(name='Palabra 1', target=deletrea_palabra, args=('be í', 3))
thread2 = threading.Thread(name='Palabra 2', target=deletrea_palabra, ... |
def histogram(items):
for n in items:
output =" "
times = n
while(times>0):
output +='*'
times = times-1
print(output)
histogram ([4,9,7])
|
# 리스트 복사
a = [1, 2, 3]
b = a
# print(id(a)) # id: 변수가 가리키고 있는 객제의 주소 값 리턴
# print(id(b))
# print(a is b) # is: 동일한 객체를 가리키고 있는지 판단
a[1] = 4
# print(a)
# print(b)
# a 변수의 값을 가져오면서 다른 주소를 가리키도록 하는 방법
# 1. [:]이용
a = [1, 2, 3]
b = a[:]
# print(id(a))
# print(id(b))
# 2. copy 모듈 이용
from copy import copy
a = [1, 2,... |
s1 = set([1, 2, 3]) # 리스트
print(s1)
s2 = set('Hello')
print(s2)
# 교집합, 합집합, 차집합 구하기
s1 = set([1, 2, 3, 4, 5, 6])
s2 = set([4, 5, 6, 7, 8, 9])
print(s1 & s2) # 교집합
print(s1.intersection(s2))
print(s1 | s2) # 합집합
print(s1.union(s2))
print(s1 - s2) # 차집합
print(s1.difference(s2))
print(s2 - s1)
print(s2.difference(s1)) |
class Cola:
'''Tipo de dato abstracto donde se representa un manejo tipo FiFO (primero en llegar, primero en salir).
Se implementarán distintos métodos para manejar este TAD a través de listas'''
def __init__(self):
#Constructor de la clase Cola
self.items = []
def estaVacia(self):
... |
#!usr/bin/python3.6
import pygame
import random
from colors import Colors
from paddle import Paddle
from ball import Ball
# Initialising the game engine
pygame.init()
# Open a new window
window_width = 1250
window_height = 800
window_size = (window_width,window_height)
window = pygame.display.set_mode(window_size)
p... |
# -*- coding: utf-8 -*-
import numpy as np
inputs = np.array(input().split(), dtype = 'float')
diff = inputs.max() * 3 - inputs.sum()
if diff % 2 == 0:
print(int(diff / 2.0))
else:
print(int(np.floor(diff / 2.0)) + 2)
|
def update(x):
x=8
print(x) # 10 update to 8
update(10)
def update(x):
x=8
print("x",x)
a=10
update(a) # here pass by value 10 not by reference a
print("a",a)
def update(x):
print(id(x)) # referce to same address because pass by value
x=8
... |
class Student:
def __init__(self,name,rollno):
self.name = name
self.rollno = rollno
self.lap = self.Laptop()
def show(self):
print(self.name ,self.rollno)
self.lap.show()
class Laptop: #inner class
def __init__(self):
... |
x=int(input("enter how many times you want to print your name"))
name = input("enter your name")
i=1
j=3
while i<=x:
print(name)
i+=1
while j>=1:
print("thank you")
j-=1 |
class A:
def __init__(self):
print("in init of A")
def feature1(self):
print("feature 1 is working")
def feature2(self):
print("feature 2 is working")
class B: # B is subclass which access all features from superclass but not vise versa
... |
#def greet():
# print("Hello")
# greet() #recursion means again greet calling greet() and it is infinite
# greet() #give error
# how to increase limit
import sys
sys.setrecursionlimit(200)
print(sys.getrecursionlimit())
i=0
def greet():
global ... |
class Computer():
def __init__(self):
self.name = "vinay"
self.age = 20
def update(self):
self.age=20
def compair(self,other):
if self.age == other.age:
return True
else:
return False
c1 = Computer() # constructor is alloc... |
# a light weight process when you breakdown a beg task into small part that each task called thred
# simple code
class Hello:
def run(self):
for i in range(0,5):
print("hello")
class Hi:
def run(self):
for i in range(5):
print("hi")
t1 = Hello()
t2= Hi()
t1.run()
t2.... |
def fabonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fabonacci(n-1)+fabonacci(n-2)
number=int(input())
print(fabonacci(number))
|
#!/usr/bin/python3
""" checking is an object is an istance of"""
def is_kind_of_class(obj, a_class):
"""Checks if object is an instance of or an instance of a class that
inherited from a specified class"""
if isinstance(obj, a_class):
return True
else:
return False
|
#!/usr/bin/python3
"""
Create empty class BaseGeometry
"""
class BaseGeometry():
"""
Class BaseGeometry with Exception
"""
def area(self):
"""Is the area function"""
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
"""This verify value... |
# =====================================
# METHODS AND THE PYTHON DOCUMENTATION
# =====================================
# mylist = [1,2,3]
# mylist.append(4)
# mylist.pop()
# mylist.insert
# =====================================
# FUNCTIONS IN PYTHON
# =====================================
# def name_function():
... |
import pygame
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((1000,500))
red = 255,0,0
white = 255,255,255
black = 0,0,0
color_1 = 100,150,201
screen.fill(white)
while True:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
... |
#All Rights Reserved to Ahmed Ezzat -> https://fb.com/ezzat001
import random
print('All Rights Reserved to Ahmed Ezzat -> https://fb.com/ezzat001')
print("[1] Gmail Mail List")
print("[2] Yahoo Mail List")
print("[3] Hotmail List")
type = int(input("Enter The Number : "))
nums = int(input("Do You want it example@email.... |
# remove()
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
#pop()
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
# pop() index
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
# delete index del
thislist = ["apple", "banana", "cherr... |
# uper and lower
a = "Hello, World"
print(a.upper())
print(a.lower())
# strip white space remove
b = " Hello, Bangladesh "
print(b.strip())
print(b.lstrip())
print(b.rstrip())
# replace string
a = "Hello, Bangladesh"
print(a.replace("Bangladesh", "Dhaka"))
# split separator function
a = "Hello, Bangladesh"
pr... |
# Many Values to Multiple Variables
x, y, z = "Bangladesh", "India", "Pakistan"
print(x)
print(y)
print(z)
# One Value of Multiple Variable
x = y = z = "Hello Bangladesh"
print(x)
print(y)
print(z)
# Unpack a Collection
city = ["Dhaka", "Feni", "Bogura"]
x, y, z = city
print(x)
print(y)
print(z)
a, b, c = ["Dhaka... |
from abc import ABC, abstractmethod
class Robot(ABC): # Abstract class
@abstractmethod
def show_name(self): # Abstract method
pass
class Human(Robot):
def __init__(self, name, age):
self.name = name
self.age = age
def show_name(self):
return self.name
def show_a... |
"""Implementation of insertion sort algorithm in python
Starting at the beginning of the list find the appropriate position for each
element and reposition it
Space complexity:
n is the size of the list
O(n^3) - creates a new list of size n, n^2 times; not implicit in the algorithm
just this implementation
Time Compl... |
"""Colas: FIFO"""
#Cola de clientes en un banco
print("Clientes en el banco")
cola = ["Juan","María"]
#Llega nuevo cliente
cola.append("Luis")
#Imprimimos turnos
print("Turnos")
print(cola.index("Juan"),cola.index("María"),cola.index("Luis"))
print (cola)
for nombres in cola:
print(nombres)
#se atiend... |
class Conta:
"""
Classe do tipo conta, seus atributos e métodos foram elaborados para simular umaconta bancária qualquer
"""
def __init__(self, ID, saldo):
"""
Metodo Construtor da classe Conta
"""
self.ID = ID
self.saldo = saldo
def __str__(self):
... |
""" """
contato = {'Nome': 'Gabriel Ulisses', 'Celular' '9976-6160': '', 'Email' : 'ga@email.com'}
contato['Nome']
contato['Oficio'] = 'Estudante - Analista estagiário'
'Nome' in contato
'Endereco' in contato
contato_list = {}
contato_list[1] = contato
dic = {'f-acrescimo': lambda x: x+1, 'f-descrescimo': lam... |
string = """
interessante,
como o python trabalha com strings
de uma maneira versátil ."""
print(string, end = ' ')
print('Basquete')
lista = ['P','e','d','r','o']
for char in lista:
print(char,end = '')
print('\n')
for char in 'Pedro':
print(char)
"""
Strings e Bytes
"""
string = 'b... |
import cv2
import numpy as np
def clean_img(img, kernel_size=5, iterations=5):
'''
clean_img :
uses morphological operations to clean the image, in this case uses erosion to remove
extremly small items, and dilation to go back to original shape and closess some holes,
different combi... |
import cv2
def contours_extraction(img):
'''
Basic contour extraction from threshold image
img: img
returns
ctr: list of all extracted contours,
h: containes hierarchical information about every contour,
for every contour [nextCtr_id, prevCtr_id, FirstChildCtr_id, parent... |
file1 = "test2DSamcra"
file2 = "2Dres-sorted"
def in_dict(filename):
dict = {}
with open(filename,'r') as f:
for l in f.readlines():
l = l.strip()
if len(l.split(" ")) == 3:
node, delay, cost = l.split(" ")
else:
node, delay, cost, _ = l.split(" ")
cost = int(cost)
if node not in d... |
import pandas as pd
import sqlite3
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/00476/buddymove_holidayiq.csv')
df = df.rename(columns={'User Id': 'UserId'})
# CREATING DATA BASE
conn = sqlite3.connect('Reviews.db')
c = conn.cursor()
# Create TABLE
c.execute('CREATE TABLE REVIEWS (UserI... |
#This function computes the factorial
#of a number entered by the user
def factor():
n = int(input("Please enter a whole number: "))
fact = 1
for factor in range(1, n+1):
fact = fact * factor
print("The factorial of ",n," is",fact)
factor()
|
# This is opening and reading the .txt file
log_file = open("um-server-01.txt")
# Creating a function
def sales_reports(log_file):
# looping over the txt file
for line in log_file:
# removing any trailing character
line = line.rstrip()
# creating variable to dispay the day
day... |
#!/usr/bin/python -tt
import sys
def repeat(s, exclaim):
"""
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
"""
result = s + s + s # can also use "s * 3" which is faster (Why?)
if exclaim:
result = result + '!!!'
return result
"""
Pyt... |
import tkinter as tk
class LeftFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.l_text = tk.Text(self.parent, width = 40, height = 10)
self.l_text.grid(row=0, column=0)
self.l_text.bind("<Key>", self.return_data)
d... |
"""**1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column are set to 0.
* Approach:
* Have two boolean arrays to keep track of row and column that has zero
* Nullify those rows and columns
* Time Complexity O(n^2)(row*column); Space Complexity O(n)
*/
"""
class Ze... |
"""*Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the
intersecting node. Note that the intersection is defined based on reference, not value. That is, if the
kth node of the first linked list is the exact same node (by reference) as the jth node of the second
linked list, t... |
"""
Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks.
"""
class QueueviaStacks(object):
def __init__(self):
self.newest = []
self.oldest = []
def enqueue(self, item):
self.newest.append(item) # push item into new stack
def dequeue(self):
... |
"""* 4.2 Minimal Tree:
* Given a sorted (increasing order) array with unique integer elements,
* write an algorithm to create a binary search tree with minimal height.
* """
from TreeNode import TreeNode
class MinimalTree(object):
def createBSTT(self, sortedlist):
return self.createBST(sortedlist, 0, len(... |
"""One Away: There are three types of edits that can be performed on strings: insert a character,
* remove a character, or replace a character. Given two strings, write a function to check if they are
* one edit (or zero edits) away.
* EXAMPLE
* pale, ple -> true
* pales, pale -> true
* pale, bale -> true
* pale, bae -... |
"""Up your Python console game with formatted text!
Requirements:
* Python 3.7+
Works great in JetBrains PyCharm console.
No idea about other consoles!
Try: ``>>> p = FancyPrinter().demo()``
"""
__author__ = "Christopher Couch"
__license__ = "MIT"
__version__ = "2020-06"
class FancyPrinter(object):
d... |
'''
Created on Jan 25, 2018
@author: James
===========================================================
Thanks to http://naelshiab.com/tutorial-send-email-python/
for the short and easy explanation of making an E-mail bot!
===========================================================
'''
import smtplib
# Multipurpose ... |
from calculator import Calculator
calc= Calculator()
print(calc.addition(1,2))
print(calc.subtraction(1,2))
print(calc.multiplication(1,2))
print(calc.division(2,1))
print(calc.exponent(1,3))
print(calc.square_root(4))
|
import requests
import random
import re
api_url = 'https://reddit.com'
last_url = ''
class APIError(Exception):
pass
def get(url, no_cache=False):
headers = {
'User-Agent': 'cybits a cute IRC bot',
}
if no_cache:
headers['Cache-Control'] = 'private,max-age=0'
return requests.get(a... |
from random import randint as base_randint
def randint(maximum=100, minimum=0):
"""
Generate a random integer between `minimum` and `maximum`.
Args:
- `maximum` - The maximum integer that can be generated (defaults to 100)
- `minimum` - The minimum integer that can be generated (defaults to... |
# creat function: equal to strip
# the following code not work, how to do that...??
print('请输入您想要从首尾去除的字符或其它参数:')
text = input()
import re
myfun = re.compile(r'text')
print('请输入一行字符串:')
selfString = str(input())
mo = myfun.sub('',selfString)
print(mo)
|
x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s. " % (binary, do_not)
print (x)
print (y)
print ("I said : %r." %x )
print ("I also said : '%s'. " %y)
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print (joke_evaluation %hilar... |
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print "The animal at 1 is %s." %animals[1]
print "The third animal is at 2 and is a %s." %animals[2]
print "The first animal is at 0 and is a %s." %animals[0]
print "The animal at 3 is %s." %animals[3]
print "The fifth animal is at 4 and is a %s."... |
def get_fused_sequence_complement(sequence_a, sequence_b):
"""
This function receives two sequences of DNA and combines them, iterating over
the two sequences and alternating between characters from each one. If one
sequence is longer than the other, it will only add characters from both until
the s... |
def string_bits(str):
res = ""
n = len(str)
for x in range(n):
if x % 2 == 0:
res = res + str[x]
return res |
sum = 0
for num in range(1, 101):
a = int(input())
sum += a
print(sum)
|
a = int(input())
b = int(input())
if a > b:
print (a)
else:
print (b)
|
a = int(input())
for num in range(1, a + 1):
if a % num == 0:
print(num)
|
def extra_end(str):
n = len(str)
last = str[n - 2:]
return last + last + last |
N = int(input())
sum = 0
for num in range(N):
a = int(input())
if a == 0:
sum += 1
print(sum)
|
def string_times(str, n):
word = ""
for x in range(n):
word += str
return word
|
# 1. Escribe un programa Python que imprima "Hola Mundo", si a es mayor que b.
a = int(input('Ingrese un valor entero "a": '))
b = int(input('Ingrese un valor entero "b": '))
if a > b:
print('Se imprimirá el saludo: ')
print('Hola Mundo')
else:
print('No se imprimirá el saludo.') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Script to find sentences
which contain both a and b markers.
'''
import sys
reload(sys)
sys.setdefaultencoding('utf8')
final_sents = []
sents_parts = []
i = -1
sents = []
def init(filename):
global sents, i, final_sents, sents_parts
fp = open(filename, 'r')
sents = ... |
v=int(input('Introduceti varsta:'))
print("Greutatea ideala este de", 2*v+8, "kg, Inaltimea ideala este de", 5*v+80, "cm") |
n=int(input('Introduceti numarul:'))
print("Tabla inmultirii cu", n, ':')
print(n, '*1=', n*1)
print(n, '*2=', n*2)
print(n, '*3=', n*3)
print(n, '*4=', n*4)
print(n, '*5=', n*5)
print(n, '*6=', n*6)
print(n, '*7=', n*7)
print(n, '*8=', n*8)
print(n, '*10=', n*10) |
#immutability example
l1= [10,20,'abcdef',30,40]
l2= l1
print(type(l1))
print(l1)
print(l2)
l1[0]= 7777
print(l1)
print(l2)
# slicing operation in list
print(l1[1:3])
# append and remove in list
l1.append(50)
l1.append(60)
print(l1)
l1.remove(50)
print(l1) |
a= int(input('enter first number'))
b= int(input('enter second number'))
c= int(input('enter third number'))
if a<b and a<c:
print('smallest number is ',a)
elif b<c:
print('smallest number is',b)
else:
print('smallest number is', c) |
def alphabet_position(letter):
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if letter in lower:
return lower.index(letter)
else:
return upper.index(letter)
def rotate_character(char, rot):
lower = "abcdefghijklmnopqrstuvwxyz"
upper... |
# lambda 변수: 변수를 이용한 표현식
L = [lambda x: x**2, lambda x: x**3, lambda x: x**4]
for f in L: #f는 리스트의 원소인 람다식(무명함수이자, 콜백함수)이 넘어옴
print(f(3)) #3의 제곱, 세제곱, 네제곱을 출력할 것임
min = (lambda x, y: x if x < y else y) #최소값을 반환
# 참일때, 거짓일 때
print(min(100, 200)) |
from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
image = PhotoImage(file="hello.png")
canvas.create_image(20, 20, anchor=NW, image=image)
# anchor는 이미지의 NW(왼쪽 상단)을 기준점으로 사용하라는 의미
window.mainloop() |
import time
now = time.localtime()
print("현재 시간은", time.asctime())
if now.tm_mon >= 3 and now.tm_mon <= 5:
print("따뜻한 봄이네요~")
elif now.tm_mon >= 6 and now.tm_mon <= 8:
print("더운 여름이네요~")
elif now.tm_mon >= 9 and now.tm_mon <= 11:
print("청명한 가을이네요~")
else:
print("추운 겨울이네요~")
if now.tm_hour < 11 :
... |
from tkinter import * # TKinter
import random # 난수 발생
answer = random.randint(1, 100) # [1, 100] 난수 발생
def guessing():
guess = int(guessField.get()) # Entry 위젯에서 숫자를 가져옴
# 결과 판단
if guess > answer:
msg = "높음"
elif guess < answer:
msg = "낮음"
else:
msg = "정답"
resultLabel... |
def myGederator():
yield 'first'
yield 'second'
yield 'third'
# generator은 yield 문장 사용
for word in myGederator():
print(word)
# chap10_iterator.py와 유사 코드
# Generator는 함수를 이용해 Iterator 객체를 생성하는 것임!
def MyCounterGen(low, high):
while low <= high:
yield low
low += 1
for i in MyC... |
def postfix_to_infix(expression):
stack = []
postfix = ""
for i in expression:
print(i, "||", len(stack), ">>", stack, "||", postfix)
if i == '(': # 열린 괄호는 스택에 들어감
stack.append(i)
elif i == ')': # 닫힌 괄호는 열린 괄호까지 스택에서 빼냄
while len(stack) > 0 and stack[len(sta... |
import turtle
polygon = turtle.Turtle()
num_sides = 6 # 육각형의 변의 개수
side_length = 70 # 한 변의 길이
angle = 360.0 / num_sides # 육각형의 내각
for i in range(num_sides):
polygon.forward(side_length) # 한 변의 길이만큼 전진!
polygon.right(angle) # 각도 변경!
turtle.mainloop() |
from tkinter import *
def show():
print("name = %s\n age = %s" % (entryName.get(), entryAge.get()))
# Entry에서 get 함수를 쓰면 입력한 값을 가져옴
window = Tk()
Label(window, text="name").grid(row=0)
# Grid 배치 관리자를 사용함 -> 행 0번째 붙임
Label(window, text="age").grid(row=1)
entryName = Entry(window)
entryName.grid(row=0, column... |
from tkinter import *
window = Tk()
canvas = Canvas(window, width=300, height=200)
canvas.pack()
line = canvas.create_line(0, 0, 300, 200, fill="red")
canvas.coords(line, 0, 0, 300, 100) # line의 좌표를 변경함
canvas.itemconfig(line, fill="blue") # line의 색깔을 변경함
# canvas.delete(line) # line을 삭제함
# canvas.delete(ALL) # 모든 ... |
from tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=200)
canvas.pack()
canvas.create_text(250, 10, text="Hello World!", fill="blue", font="Courier 20")
# font는 ("Courier", 20)으로 해도 됨
canvas.create_text(250, 100, text="Hello World!", fill="red", font="Helvetica 30")
window.mainloop() |
#이진수 변환기
input_number = input("수를 입력하세요 >> ")
#정수부와 소수부를 나누기
pos = input_number.find('.')
if pos != -1 : #소수점을 찾으면
Z_number, point_number = int(input_number[:pos]), int(input_number[pos+1:])
#print(real_number, point_number)
#정수부는 2로 나눈 나머지에 대한 것
ans_Z = ""
if Z_number > 0 : # 양수이면
while Z_number != 0 ... |
def eratosthenes(n):
multiples = set() # 공백의 set을 정의
for i in range(2, n + 1): # 2부터 n까지의 정수에 대해서
if i not in multiples: # set에 없으면
yield i # 함수의 return 값을 i로 출력 (generator) -> 이것이 소수
multiples.update(range(i * 1, n + 1, i)) # i의 배수를 전부 추가함
print(list(eratos... |
print('Введите три числа')
a=int(input())
b=int(input())
c=int(input())
if a%b==c :
print('Условие 3 верно, a даёт остаток c при делении на b')
else:
print ('Условие 3 неверно')
if c==-b/a :
print ('Условие 4 верно, c является решением линейного уравнения ax + b = 0')
else:
print ('Услови... |
import numpy as np
import matplotlib.pyplot as plt
from danpy.sb import *
from matplotlib.patches import Ellipse
import matplotlib.animation as animation
import matplotlib.patches as patches
from scipy import signal
import argparse
"""
Notes:
X1: angle of pendulum
X2: angular velocity of pendulum
"""
def dx1_dt(X,U)... |
t = int(input())
for i in range(t):
notas = [int(x) for x in input().split()]
nota_min = int(min(notas))
nota_max = int(max(notas))
print(nota_min, nota_max)
if nota_min == nota_max:
print("S", end="" if i == t-1 else "\n")
else:
print("N", end="" if i == t-1 else "\n") |
'''
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Intervals can "touch", such as [0, 1] and [1, 2], but they won't be considered overlapping.
For example, given the intervals (7, 9), (2, 4), (5, 8), return 1 as the last inte... |
'''
You are given a starting state start, a list of transition probabilities for a Markov chain,
and a number of steps num_steps. Run the Markov chain starting from start for num_steps and
compute the number of times we visited each state.
For example, given the starting state a, number of steps 5000, and the follow... |
'''
You have n fair coins and you flip them all at the same time. Any that come up tails you set aside. The ones that come up heads you flip again. How many rounds do you expect to play before only one coin remains?
Write a function that, given n, returns the number of rounds you'd expect to play until one coin remain... |
'''
Write an algorithm that computes the reversal of a directed graph. For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
'''
import unittest
def reverse_graph(graph):
reversed_graph = {}
for k, v in graph.items():
reversed_graph[k] = []
for node, connections in graph... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.