text stringlengths 37 1.41M |
|---|
#**********Class Decorator**************
print("\n***************Class Decorator***************")
class square:
def __init__(self,side):
self._side=side
@property
def side(self):
return self._side
@side.setter
def side(self, value):
if value>=0:
self._side=value
... |
#Nested loop
print("Welcome to glacticspace Bank ATM")
restart=('y')
chance=3
balance=67000.50
while chance>=0:
pin= int(input('Please Enter your 4 didgit pin:'))
if pin==(1234):
print('You have entered the correct PIN\n')
while restart not in ("n","NO","N","no"):
prin... |
import time
import datetime
def daysUntil(xDay):
today = datetime.date.today()
diff = xDay-today
return diff.days
def main():
print("{} days until freedom, SON!".format(daysUntil(datetime.date(2019,5,1))))
time.sleep(60)
exit(0)
if __name__ == "__main__":
main()
|
'''
链式结构
1、内存不连续
2、不能通过下标访问
3、追加元素很方便
4、遍历操作和查找操作比较复杂
单链表
1、通过指针的方式首尾相连
2、根节点,入口,用来遍历,首节点,尾节点
3、node:包括value,和指针next,指向下一个元素
4、可以定义一个class来体现node对象
5、实现单链表结构
单链表类的属性和方法
1、数据data:root、lenth、
2、method:
init、append、append_left、append_right、
iter_node、remove、find、pop_left(right)、
clear
'''
# 定义实现节点类
# 定义实现单链表类
# 初始化:最... |
string = list(input())
palavra = list(input())
hasEqual = False
tamanhoVetor = len(string) - len(palavra)
for i in range(0, tamanhoVetor + 1):
trecho = []
for j in range(0, len(palavra)):
trecho.append(string[i+j])
if trecho == palavra:
hasEqual = True
print(i)
if hasEqual == False:
print("NO... |
def lerValores():
x = []
for i in range(0, 10):
x.append(int(input()))
return x
def subValores():
y = lerValores()
for i in range(0, len(y)):
if y[i] <= 0:
y[i] = 1
for i in range(0, len(y)):
print(f"X[{i}] = {y[i]}")
subValores() |
binario = int(input())
decimal = 0
exp = 0
while binario != 0:
divisao = binario // 10
resto = binario % 10
decimal = decimal + resto * (2 ** exp)
exp = exp + 1
binario = divisao
print(decimal) |
"""TCP Client"""
import socket
def Main():
"""127.0.0.1 is the loopback address. Any packets sent to this address will
essentially loop right back to your machine and look for any process
listening in on the port specified."""
host = '127.0.0.1'
port = 5000
#Create a socket and connect to ou... |
# using inheritance importing product
import product
# and checkoutregister classes
import checkoutregister
# adding some products into the supermarket
product.product("123", "Milk", "2 Litres", "2.0")
product.product("789", "Fruits", "2 kgs", "4.0")
product.product("456", "Bread", "", "3.5")
# greeting message gener... |
# print the type of an object - escrevendo o tipo de um objeto
print(type(1))
print(type(1.0))
print(type('a'))
print(type(True))
# use brackets to declare a list - use colchetes para declarar uma lista
print(type([1, 2, 3]))
print(len('Gabriela'))
print(len([10, 11, 12])) |
#!/usr/bin/python3
my_word = "Holberton"
print("{0} is the first letter of the word {1}".format(my_word[0],my_word))
|
import curses
import math
from curses_printable import CursesPrintable
from rectangle import Rectangle
# Vertical scroll list.
class ScrollableList(object):
def __init__(self, aWindowObject, aRectangle, aScrollKeysOrd=(curses.KEY_UP, curses.KEY_DOWN), aTitle=''):
self.title = aTitle
self.scrollKeys = a... |
class Rectangle(object):
def __init__(self, aX, aY, aWidth, aHeight):
self.x = aX
self.y = aY
self.width = aWidth
self.height = aHeight
|
def toplama(sayı1,sayı2):
return sayı1+sayı2
def çıkarma(sayı1,sayı2):
return sayı1-sayı2
def çarpma(sayı1,sayı2):
return sayı1*sayı2
def bölme(sayı1,sayı2):
return sayı1/sayı2
işlem=input("yapmak istediğiniz işlem: ")
if(işlem=="+"):
sayı1=int(input("toplamak istediğiniz sayıları ... |
for i in range(0,11):
if i==0 or i==10:
for j in range(0,11):
print("-",end="")
if i==1 or i==9:
for j in range(0,11):
if j!=5:
print("-",end="")
else:
print("+",end="")
if i==2 or i==8:
for j in range(0,1... |
from turtle import*
for i in range(72):
for j in range(6):
forward(70)
right(60)
right(5)
right(30)
forward(150)
for h in range(360):
right(1)
forward(1)
fillcolor("red")
shape("turtle")
stamp()
left(50)
forward(100)
shape("classic")
stamp()
right(90)
forward(170)
... |
name=None
print("hello world!")
name=input("what's your name?")
#this is a greeting.
print("hello, " +name+ " !")
print("My name is Python.")
pythonFavorites=['read','code','and sleep']
print('I like to ' +str(pythonFavorites[0:4]))
print(' 5 + 3 = 8 ')
#ha ha ha
print( 'OK bye!')
print('I need to code!')
... |
print("게임을 시작합니다")
print("테트리스 시작")
print("1.오른쪽 2.왼쪽 3.블록 바꾸기")
number = input("숫자를 입력하세요: ")
print("당신이 입력한 숫자는?", number)
#만약에 1번을 누르면 오른쪽으로 이동
if int(number) == 1:
print("오른쪽으로 이동")
#만약에 2번을 누르면 왼쪽으로 이동
elif int(number) == 2:
print("왼쪽으로 이동")
#만약에 3번을 누르면 바꾸기 가능
else:
print("바꾸기")
|
import unittest
'''
unittest.skip(reason) 无条件地跳过装饰的测试,说明跳过测试的原因。
unittest.skipIf(condition, reason) 跳过装饰的测试,如果条件为真时。
unittest.skipUnless(condition, reason) 跳过装饰的测试,除非条件为真。
unittest.expectedFailure 测试标记为失败。不管执行结果是否失败,统一标记为失败
'''
class MyTest(unittest.TestCase):
@unittest.skip("直接跳过测试")
def test_skip(self):
... |
def print_menu():
print("="*30)
print("xxx--system---")
print("1.xxx")
print("2.xxx")
def print_string():
print("string")
print_menu()
print_string()
def sum_2_nums(a,b):
result = a + b
print("%d+%d=%d"%(a,b,result))
num1 = int(input("请输入第1数字"))
num2 = int(input("请输入第2个数字"))
#调用函数
su... |
L = [x*2 for x in range(5)]
def creatNum():
a,b =0,1
for i in range(5):
yield b
a,b = b,a+b
a = creatNum()
for num in a:
print(num)
|
def create_room_number_dict():
room_numbers = {'CS101': '3004', 'CS102': '4501', 'CS103': "6755", 'NT110': '1244', 'CM241': '1441'}
return room_numbers
def create_instructor_dict():
instructors = {'CS101': 'Haynes', 'CS102': 'Alvarado', 'CS103': 'Rich', 'NT110': 'Burke', 'CM241': 'Lee'}
return instruc... |
"""
Although you have to be careful using recursion it is one of those concepts you want to at least understand. It's also commonly used in coding interviews :)
In this beginner Bite we let you rewrite a simple countdown for loop using recursion. See countdown_for below, it produces the following output:
"""
def co... |
def sum_numbers(numbers=None):
# Check and fix input
if numbers == None:
numbers = range(1,101)
return sum(num for num in numbers) |
"""
Write a simple Promo class. Its constructor receives two variables: name (which must be a string) and expires (which must be a datetime object).
Add a property called expired which returns a boolean value indicating whether the promo has expired or not.
Checkout the tests and datetime module for more info. Have f... |
#Number guessing game
from tkinter import *
import random
rNumber=random.randint(1,100)
print(rNumber)
window=Tk()
window.title("Number guessing game")
lbl=Label(window,text="Enter your guessing number: ", font=("Arial Bold", 25))
lbl.grid(column=0, row=0)
window.geometry("1000x1000")
textField=Entry(window... |
"""
Classes são utilizadas para criar estruturas definidas.
Estas, definem funções chamadas de métodos.
Os métodos identificam os comportamentos e ações que um
objeto criado a partir da classe pode executar com
seus dados.
Uma classe é uma base de como algo deve ser definido.
Enquanto a classe é uma base, u... |
class Tabular(object):
def __init__(self, *cols):
self.cols = cols
def show(self, data):
cols = self.cols
titles = [c[0] for c in cols]
vals = [ [str(c[1](d)) if d else "*" for c in cols] for d in data ]
lengths = [ reduce(lambda m, v: max(m, len(v[i])), vals + [ titles], 0) for i,c in enumerat... |
#Jeremiah Hsieh AI Pac Man Final Project
#basic display and movement of pacman
import math
import pygame as pg
import random
#class for pellet objects using pg sprites to draw
class Pellet(pg.sprite.Sprite):
#initialize default to 255,255,255 which is white,
def __init__(self, x, y, r = 10, rgb = (255, 255... |
#!/usr/bin/env python3
# Сумма трёх чисел
print(int(input('num1 '))+int(input('num2 '))+int(input('num3 '))) |
from .settings import DEBUG, debug_logs, debug_read1_file, NOT_UTF_8
# -------------------------------
# ----- character functions -----
# -------------------------------
def ischar(c:str) -> bool:
return len(c) == 1
def isalpha(c:str) -> bool:
if not ischar(c):
return False
elif ord('A') <= ord... |
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from time import sleep
import datetime
today = datetime.date.today()
#Aks the user for how many days to scout ahead
while True:
try:
start_scout = int(input("How many days until you can leave? (0 to leave today)"))
da... |
import numpy as np
import itertools
import time
# easy sudoku board
grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2,... |
"""
9. 점수 구간에 해당하는 학점이 아래와 같이 정의되어 있다.
점수를 입력했을 때 해당 학점이 출력되도록 하시오.
81~100 : A
61~80 : B
41~60 : C
21~40 : D
0~20 : F
예시
<입력>
score : 88
<출력>
A
"""
print('<입력>')
scr = input('score : ')
print('<출력>')
if int(scr) < 21:
grade = 'F'
elif int(scr) < 41:
grade = 'D'
elif int(scr) < 6... |
#Polymorphism in inheritance lets us define methods in the child class that have the same name as the methods in the parent class
#Polymorphism means having many forms.
#Same function name(different parameters)being used for different implementations
class Bird:
def intro(self):
print("There are many type... |
"""Program to generate preprocessed N-gram vocabulary for contextual embeddings
To do this, we need to collect all of the N-gram vocab from a corpus, and then
run each N-gram chunk through the embedder. The vocabulary for the embedder is
going to be 1-grams and it will process an array. For example, if we have a sam... |
"""
Search and recognize the name, category and
brand of a product from its description.
"""
from typing import Optional, List, Union, Dict
from itertools import combinations
import pandas as pd # type: ignore
from pymystem3 import Mystem # type: ignore
try:
from cat_model import PredictCategory # type: ignore
... |
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind o... |
import hashmap
# create a mapping of state to abbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')
# create a basic set of states and some cities ... |
from Deck import Deck
from Card import Card
from Player import Player
def display_cards(cards):
for card in cards:
print(card)
def cards_sum(cards):
total = 0
for card in cards:
total += card.card_value()
return total
def contains_ace(cards, person):
for card ... |
def letterCasePermutation(self, S: str) -> List[str]:
ls = [] # list store stirng
def UpperCaseInCharacter(S: str, index: int) -> str:
s = list(S)
s[index] = s[index].upper()
return "".join(s)
def LowerCaseInCharacter(S: str, index: int) -> str:
s = list(S)
s[index... |
def oddEvenList(self, head: ListNode) -> ListNode:
odds = ListNode(0)
evens = ListNode(0)
index = 1
oddsHead = head
evensHead = evens
while head: # using while head to avoid NoneType error
if (index % 2 != 0):
odds.next = head
odds = odds.next
# use n... |
def subsets(self, nums: List[int]) -> List[List[int]]:
ls, leng = [], len(nums)
def subsets(origin_set: List[int], subset: List[int], index: int, n: int):
if index >= n:
new_set = []
new_set.extend(subset)
ls.append(new_set)
else:
new_set = []
... |
def cipher(word):
s=""
for w in word:
if(w.islower()):
s=s+chr(219-ord(w))
else:
s=s+w
return s
def main():
cip=cipher("Sample Sentence だよ")
print(cip)
rev_chip=cipher(cip)
print(rev_chip)
if __name__ == "__main__":
main()
|
b={1:'Entry',2:'Details',3:'Exit'}
for i in b:
print(b[i])
b1=int(input('Enter Command:'))
if b1==1:
import entry
elif b1==2:
import details
elif b1==3:
print('Exit')
else:
print('Please Enter Right One:')
|
# GUI 연습
import tkinter as tk # 창 생성
Window = tk.Tk()
# window 창 설정
Window.title( "제목" )
Window.geometry( "500x500+200+100" ) # ("너비 x 높이 + x좌표 + y좌표")
# 배치 (위젯)
label = tk.Label( Window, text= "입력하세요" )
label.pack()
display = tk.Entry( Window, width=30 )
display.pack()
# Window.resizeable(False, False) # 윈도우 창 크... |
import pygame
import random
pygame.init()
#Creating window for game
screen_width = 900
screen_height = 500
gamewindow = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("My Game")
pygame.display.update()
clock = pygame.time.Clock()
#colors
white = (255,255,255)
red = (255, 0, 0)
black = ... |
import re
count = int(input("input data:"))
results = ''
for i in range(count):
val = input()
# Use regular expression to remove all non-alphanumerical characters
val = re.sub('[^A-Za-z0-9]', '', val)
# Replace all letters with lowercase to avoid case sensitive
val = val.lower()
if (val == val... |
# -*- coding: utf-8 -*-
# Exercício 1
# valor1= float(input("digite o valor 1: "))
# valor2= float(input ("digite o valor 2: "))
# soma = valor1 + valor2
# subtracao = valor1 - valor2
# multiplicacao= valor1*valor2
# divisao = valor1/valor2
# resto = valor1%valor2
# media = (valor1+valor2)/2
# print (soma)
# print (... |
# Step 1. 필요한 모듈과 라이브러리를 로딩하고 검색어를 입력 받습니다
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import datetime
import sys
import numpy
import pandas as pd
import xlwt
import random
import urllib.request
import urllib
import re
import m... |
__author__ = 'skye2017-11-18'
# coding=utf-8
# 在Python中没有switch – case语句。
a = 100
if a:
print('1 - if 表达式条件为 true')
print(a)
b = 0
if b: # 布尔值除了 0 都是 true
print('2 - if 表达式条件为 true')
print(b)
print('再见')
age = int(input('请输入你家狗狗的年龄: '))
print('回答:', end='')
if age < 0:
print('你是在逗我吧!')
elif age =... |
p1 = input("Player 1, choose rock, paper, or scissors: ")
p2 = input("Player 2, choose rock, paper, or scissors: ")
def play(player1, player2):
if player1 == player2:
print("play again")
elif player1 == 'rock':
if player2 == 'scissors':
print("Rock hits scissors. Player 1 win!")
... |
moves = [1,5,3,5,1,2,1,4]
board = [[0,0,0,0,0], # 0
[0,0,1,0,3], # 1
[0,2,5,0,1], # 2
[4,2,4,4,2], # 3
[3,5,1,3,1]] # 4
result = [] # 4 3 1 1 3 2 0 4
total = 0
second_num = 0
# len(board) = 5
for i in moves:
print(i-1) # 0 4 2 4 0 1 0 3
second_num = i-1
... |
from pyfirmata import Arduino
from tkinter import *
#Especifique a Porta do Arduino
PORTA = "COM3"
arduino = Arduino(PORTA)
led = arduino.get_pin('d:13:o')
# d= Digital
#Pinno 13
#o = OUTPUT
def acender():
led.write(1)
def apagar():
led.write(2)
janela = Tk()
janela.title("Acender e Apagar LED com botão")... |
from typing import List
def checkio(game_result):
rPattern = createPattern(game_result)
for i in rPattern:
for s in "XO":
if i.count(s) == 3 :
return s
return "D"
def createPattern(game_result):
list =[]
#horizontal pattern
list.extend(game_resu... |
def sort_positive(arr):
pos = []
for i in range(0, len(arr)):
if arr[i] > 0:
pos.append(arr[i])
pos.sort()
j=0
for i in range(0, len(arr)):
if arr[i]>=0:
arr[i] = pos[j]
j +=1
return arr
def main():
arr = [28, -6, -3, 8, 4, 1, -5, -8, 23, 2]
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 19:51:53 2020
@author: Chennakesava Reddy
"""
#5)write a python program to create alist and access the elements in the list
my_list = ['u', 'l', 't', 'i', 'm','a','t','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list = ["H... |
class Movies:
'''
initializing tht class and objects
'''
def __init__(self):
'''
stroing the movies for view.movies and find.movies
'''
self.movies = [{'name': 'sherlock', 'year': '2009', 'genre': 'thriller'},
{'name': 'titanic', 'year': ... |
# CRYPTOGRAPHIC TOOL BASED ON AES-256 (OFB MODE) - A Symmetric Cryptographic Encryption and Decryption in Python
# Submitted by - Abhay Chaudhary
# Submitted to - Dr. Garima Singh
# CSE1007 Introduction to Cryptography (SLOT-A+TA)
# Python v3.9.0
# imports
import os
import sys
from tqdm import tqdm
from termcolor imp... |
"""Example file containing the main executable for an app."""
from logging import DEBUG
from Logger import logging_config
# Create a Logger for main_app
MAIN_LOG = logging_config.get_simple_logger("main_logger", DEBUG)
# Main program
def __main__():
MAIN_LOG.info("Running Main Program inside main_app.py")
MA... |
from tkinter import *
import sys
class Main(Frame):
def __init__(self, root):
super(Main, self).__init__(root)
self.build()
def build(self):
self.formula = "0"
self.lbl = Label(text=self.formula, bg="#000", foreground="#FFF", font=("Times New Roman", 21, "bold"))
s... |
class user():
def __init__(self,first,last,age):
self.first=first
self.last=last
self.age=age
harry=user("harry","rajput",22)
raju=user("raju","rajput","23")
print(harry.first,harry.last,harry.age)
|
i=int(input("enter the no.:"))
n=6
while i<=10:
print(i,"*",n,"=",i*n)
i=i+1 |
def banka(p,t,tax):
amount1=p+(p*t)/100+(tax*p)/100
return amount1
print("total amount","=",amount1)
p=int(input("principle:"))
t=int(input("tenur:"))
tax=int(input("tax:"))
banka(p,t,tax)
def bankb(p1,t2,tax2):
amount=p1+(p1*t2)/100+(tax2*p1)/100
return amount
print("total amount","=",amount)
... |
from collections import OrderedDict
my_order = OrderedDict()
for i in range(int(input())):
name,space,price = input().rpartition(' ')
if name not in my_order:
my_order[name] = int(price)
else:
my_order[name] += int(price)
for item_name, net_price in my_order.items():
print (item_name,net... |
#setting the global constant for the RETAIL_PRICE
RETAIL_PRICE = 99.00
MIN_QUANTITY = 10
#othe variables delclared for the function
quantity = 0
fullPrice = 0
discountRate = 0
discountAmount = 0
totalAmount = 0
def main():
#getting quanity from user
quantity= int(input('Enter quantity: '))
if quantity >= M... |
#!/usr/bin/env python3
#
# DESCRIPTION
#
# Prints terminal colours.
#
def print_color_table():
for style in range(8):
for fg in range(30, 38):
s = ''
for bg in range(40, 48):
cc = ';'.join([str(style), str(fg), str(bg)])
s += '\x1b[{}m {} \x1b[0m'... |
class PlayerCharacter:
# Class Object Attribute. does not change
membership = True
# __init__ constructor
# self is class PlayerCharacter same as "this" in Java
def __init__(self, name, age):
if self.membership: # same as PlayerCharacter.membership
self.name = name # attribute... |
from CustomError import NotNumberException
age = ""
while True:
try:
age = input("What is your age? ")
if age == "0":
raise ZeroDivisionError("Numerator cannot be zero-based")
10/int(age)
except ValueError:
print(f"inputted data: '{age}' is not a valid number")
... |
def my_function(*students):
print("The tallest student is " + students[2])
my_function("James", "Ella", "Jackson")
print("\n**********\n")
def my_function(*argv):
print(argv)
my_function('Hello', 'World!')
def multi_func(num1, num2):
return num1 * num2
print(multi_func(5, num2=67))
print("\n********... |
# list, set, dictionary
# var = [param for param in iterable]
# var = [expression for param in iterable conditional]
print("\n****** LIST COMPREHENSION *******\n")
my_list = [*'hello']
my_list2 = [char for char in 'hello']
print(my_list)
print(my_list2)
my_list3 = [num for num in range(0, 100)]
print(my_list3)
# dou... |
# generator is a subset of an iterable
from time import time
def generator_fn(num):
for i in range(num):
yield i # yield only keeps only value in memeory per time
g = generator_fn(10)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#
#
#
print("\n******** GENERATOR PERFORMANCE ********\n"... |
counter = 0
while counter < 4:
print("yoga")
counter += 1
print("**********************\n\n", 0o7)
i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2
print("**********************\n\n", 0o7)
i = 5
while True:
if i % 0o11 == 0:
break
print(i)
i += 1
print("*********... |
def find_root(parent, n):
if parent[n] != n:
parent[n] = find_root(parent, parent[n])
return parent[n]
def check_connection(network, first, second):
parent = dict()
for conn in network:
a, b = conn.split('-')
parent.setdefault(a, a)
parent.setdefault(b, b)
ra = f... |
def clock_angle(time):
h, m = map(int, time.split(':'))
h %= 12
h = (h + m / 60.) * 30
m *= 6
angle = abs(h - m)
if angle > 180:
angle = 360 - angle
return round(angle, 1)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing... |
VOWELS = "aeiouy"
def translate(phrase):
ans = []
it = iter(phrase)
while True:
try:
c = it.next()
ans.append(c)
if c in VOWELS:
it.next()
it.next()
elif c.isalpha():
it.next()
except StopIterati... |
import heapq
class Node(object):
def __init__(self, idx, dis):
self.idx = idx
self.dis = dis
def __lt__(self, other):
return self.dis < other.dis
def checkio(land_map):
w, h = len(land_map[0]), len(land_map)
dijkstra = [Node((0, i), land_map[0][i]) for i in xrange(w)]
he... |
def on_edge(point, edge):
p0, p1 = edge
if (p0[0] - point[0]) * (p1[1] - point[1]) == (p1[0] - point[0]) * (p0[1] - point[1]):
# same slope
if p0[0] <= point[0] <= p1[0] or p1[0] <= point[0] <= p0[0]:
if p0[1] <= point[1] <= p1[1] or p1[1] <= point[0] <= p0[1]:
return... |
import math
print('-'*30)
print(' TINTA EM CORES')
print('-'*30)
metros = float(input('area a ser pintada:'))
litros = metros/6
galao = math.ceil(litros/18)
latas = math.ceil(litros/3.6)
vgalao = galao*80
vlatas = latas*25
#MISTURANDO LATAS E GALOES
pgalao = math.trunc(litros/18)
platas = (litros%18)/3.6
vpgala... |
c = float(input('informe a temperatura em Celsius que deseja converter:'))
f = (((9*c)/5)+32)
print('a temperatura informada em Farenheit é',f)
input('.') |
def segs(h,m,s):
total=h*3600+m*60+s
return total
horas=int(input('informe a quantidade de horas: '))
minutos=int(input('informe a quantidade de minutos: '))
segundos=int(input('informe a quantidade de segundos: '))
print('o tempo total é de {} segundos'.format(segs(horas,minutos,segundos)))
|
def hipotenusa (b,c):
a=(b**2+c**2)**0.5
return a
b=int(input('informe o valor de um dos catetos: '))
c=int(input('informe o valor do outro cateto: '))
print('o valor da hipotenusa é {:.2f}'.format(hipotenusa(b,c)))
|
def inversos(n):
s=0
divisor=1
while divisor<=n:
s+=1/divisor
divisor+=1
return s
print('o valor da soma dos inversos de 1 a n é : ',
inversos(int(input('informe um numero: ')))) |
from tkinter import *
def bt_tipo_click():
a=float(et_lado01.get())
b=float(et_lado02.get())
c=float(et_lado03.get())
if a<b+c and b<a+c and c<b+a:
if a==b==c:
tipo.configure(text='Triângulo Equilátero')
else:
if a==b or a==c or b==c:
t... |
def media(n):
if n<5:
return 'D'
if n<7:
return 'C'
if n<9:
return 'B'
if n<10:
return 'A'
n= int(input('informe a media do aluno: '))
print('a nota informada tem conceito',media(n)) |
from tkinter import *
font=('Arial','10')
def bt_calc():
global v
terra=float(et_peso.get())
if v.get()==1:
planeta = (terra / 10) * 0.37
nome='Mercúrio'
if v.get()==2:
planeta = (terra / 10) * 0.88
nome = 'Vênus'
if v.get()==3:
planeta = (terra ... |
#Funções definidas pela linguagem
'''
print(parametro)
input(parametro)
int(parametro)
float(parametro)
list(parametro)
len(parametro)
range(parametro)
min,sum,max
'''
#funções que só podem ser usados com LISTA
'''
lista.append(parametro)
lista.index(parametro)
'''
#funçoes que só podem ser usadas c... |
def e_primo(num):
divisores = 0
i = 1
while i <= num:
if num % i == 0 :
divisores = divisores + 1
i = i + 1
if divisores == 2:
return True
else:
return False
n=int(input('informe o numero: '))
if e_primo(n)==False:
print('{} não é prim... |
prods=[]
quants=[]
dic={}
while True:
prod=str(input('informe o nome do produto: '))
prod=prod.upper()
if prod=='FIM':
break
else:
quant = int(input('informe a quantidade de {} a comprar: '.format(prod)))
prods.append(prod)
quants.append(quant)
dic=dict(zip(... |
lista = [] #lista vazia
print('tamanho:',len(lista))#tamanho da lista
lista.append(10) #adicionar um elemento a lista
print('tamanho:',len(lista))#tamanho da lista
print(lista)
lista.append(20)
lista.append(30)
lista.append(20)
print('tamanho:',len(lista))
print(lista)
del lista[0] #apagar item da posição i... |
def divisivel (x,y):
if x%y==0:
return 'é divisível'
else:
return 'não é divisível'
x=int(input('informe o valor: '))
y=int(input('informe o divisor: '))
print('{} {} por {}'.format(x,divisivel(x,y),y)) |
raio = float(input('informeo raio do circulo desejado:'))
area = 3.14*raio**2
print('a area do circulo é ',area)
input('.') |
import math
print('-----------------')
print('TINTAS EM CORES')
print('-----------------')
metros = float(input('informe quantos metros quadrados deseja pintar:'))
litros = metros/3
galao = math.ceil(litros/18)
print('você vai precisar de',galao,'galão(ões) de tinta')
print('cada galão custa R$ 80,00 reais')
print('o ... |
# heap sort
# Utility Function to get parent node by index
# i is the index of array member
def getParent(i):
idx = (i-1)//2
if idx >= 0:
return idx
else:
return None
# Utility Function to get left child node by index
def getLeftChild(i, arr):
idx = 2*i + 1
if idx < len(arr):
... |
import math
import typing
import kinematics2d as k2d
__all__ = ["Pose"]
class Pose:
"""A 2-dimensional pose.
Attributes:
- position: k2d.Vector
- orientation: float (in radians)
"""
def __init__(self, position: k2d.Vector, orientation: float) -> None:
self._position: k2d.Ve... |
'''
Sample input : hello
sample output: {h: 1, e: 1, l: 2, 0: 1}
'''
# first solve
inp = input()
spis = {}
new_spis = []
for i in range(len(inp)):
count=1
if inp[i] not in new_spis:
new_spis.append(inp[i])
spis.update({inp[i]: count})
count = 1
else:
count += 1
spis.update({inp[i]: count})
print(spis)
... |
def swap(i, j):
sqc[i], sqc[j] = sqc[j], sqc[i]
def heapify(end,i):
l=2 * i + 1
r=2 * (i + 1)
max=i
if l < end and sqc[i] < sqc[l]:
max = l
if r < end and sqc[max] < sqc[r]:
max = r
if max != i:
swap(i, max)
h... |
from Stack import Stack
def check_line(input_line):
st = Stack([])
key_dict = {
')': '(',
'}': '{',
']': '['
}
inx = 0
for elem in input_line:
inx += 1
if elem not in key_dict.keys():
st.push(elem)
elif st.is_empty():
return ... |
"""exdictionary = {"hi":2, "hola":4}
print(exdictionary["ahi"])
if "hi" in exdictionary:
print("hola")"""
""".clear() - deletes all contents of a dictionary
.items() - returns all key, value pairs
.get(key) - returns the value for the passed key
.keys() - returns a list of all keys
.values() - returns a list of al... |
# Rosette.py
import turtle
t = turtle.Pen()
colors = ["red", "pink", "blue", "purple", "yellow", "green"]
for x in range (6):
t.pencolor(colors[x%6])
t.circle(100)
t.left(60)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.