text stringlengths 37 1.41M |
|---|
import sys
def is_palindrome(num):
return str(num) == str(num)[::-1]
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if test == "":
continue
iterations = 0
while is_palindrome(test) is False:
test = int(test) + int(str(test)[::-1])
iterations += 1
print("{} {}".format(iteration... |
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if test == '':
continue
digits = [int(digit) for digit in test.strip() if digit != ' '][::-1]
odd_digits = digits[::2]
even_digits = [2 * digit for digit in digits[1::2]]
sum_even_digits = 0
for even_digit in even_digits:
... |
# 4.- Escribir un programa que lea el salario de un empleado y
# mediante un algoritmo efectué un incremento salarial
# en base a la siguiente escala:
# Si el salario es menor < 1000 Bs. incremente en un 20%
# Si el salario es mayor o igual a 1000 pero es menor a 3000 Bs. Incremente en un 15%
# Si el salario es mayor o... |
print("--------Fabrica el cometa--------")
materia_prima = int(input("Materia prima: "))
clave = int(input("Clave del producto: "))
if clave == 3 or clave == 4:
mano_obra = materia_prima*0.75
else:
if clave == 1 or clave == 5:
mano_obra = materia_prima*0.85
else:
mano_obra = materia_prima*0.... |
horas = int(input("Horas de estacionamiento: "))
if horas <= 2:
costo = 5
total = costo*horas
elif horas <= 5:
costo = 4
total = (horas-2)*costo + 10
elif horas <= 10:
costo = 3
total = (horas-5)*costo + 22
elif horas > 10:
costo = 2
total = (horas-10)*costo + 31
print("-----------------... |
#1.- Una empresa tiene dos turnos (mañana y tarde) en los
# que trabajan n empleados (la mitad de ellos por la mañana
# y la otra mitad por la tarde). Elabore un programa que
# permita almacenar los sueldos de los empleados agrupados
# en dos listas. Imprimir las dos listas de sueldos y además
# mostrar el s... |
# 14.- Leer las temperaturas de n regiones y determine:
# el porcentaje de temperaturas por encima de 30º C,
# también el porcentaje de temperaturas por debajo de 0º C
def temperatura(cantidad):
maximo = 0
minimo = 0
fuera = 0
for region in range(1, cantidad+1):
temperatura = int(input(f"Digite... |
a = int(input("Digite lado A: "))
b = int(input("Digite lado B: "))
c = int(input("Digite lado C: "))
if a == b == c:
print("El triangulo es equilatero")
elif a != b and a != c and b != c:
print("Es triangulo es escaleno")
else:
print("Es triangulo isosceles")
|
n = int(input("Digite cantidad de numeros(n): "))
m = n
for i in range(1, n+1):
# print(i, end=' ')
for j in range(1, m+1):
print(j, end=' ')
m -= 1
print("\n")
|
numero = int(input("Introduzca numero: "))
valor = numero%2
if valor == 0:
if numero > 0:
print("El numero {} es par positivo".format(numero))
elif numero == 0:
print("El numero es cero")
else:
print("El numero {} es par negativo".format(numero))
else:
if numero > 0:
prin... |
class Solution:
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
a=""
if t == None:
return a
a= str(t.val)
if( t.left != None or t.right != None ):
a+= "(" + self.tree2str(t.left) + ")"
if t.right... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumOfLeftLeaves(self, root, left= False):
"""
:type root: TreeNode
:rtype: int
"""
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, r):
"""
:type root: TreeNode
:rtype: List[str]
"""
if r is... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
a= []
h= head
while ... |
class Mhs(object):
def __init__(self, nama, nim, kota, uangsaku):
self.nama = nama
self.nim = nim
self.kotaTinggal = kota
self.uangSaku = uangsaku
h0 = Mhs("Aini", 107, "Sukoharjo", 240000)
h1 = Mhs("Salsa", 113, "Sragen", 230000)
h2 = Mhs("Anggi", 145, "Surakarta", 250000)... |
import os
class ReadFile:
_filename = None
_workspace = None
def __init__(self, workspace):
self._workspace = workspace
pass
def read_file(self, extension):
workspace = self._workspace
for file in os.listdir(self._workspace):
if file.endswith("." + extens... |
class Trapezoid:
def __init__(self,h,b1,b2):
self.h=h
self.b1=b1
self.b2=b2
def getArea(self):
return self.h*self.b1+self.b2/2
def getPerameter(self):
return self.h*self.b1+self.b2/2
i=int(input("ENTER THE HIGHT:"))
j=int(input("ENTER THE BASE NO. 1:"))
k... |
# Metodos para el manejo de listas Listas
# Variables
# int_Nombre_variable = tipo_dato ; Variables del tipo entero
# float_Nombre_variable = tipo_dato ; Variables con decimales
# str_Nombre_variable = tipo_dato ; variables con Cadenas o caracteres
# bool_Nombre_variable = tipo_dato ... |
if __name__ == '__main__':
n=int(input())
list=[]
list1=[]
for i in range(1,n):
if(i%2==0):
list.append(i)
else:
list1.append(i)
print("even num:",list);
print("odd num:",list1)
|
import numpy as np
import cv2
def basic_color_mask(image, color_range_hsv):
"""
Create contrast between white and what is not white in a picture.
"""
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_white = np.array(color_range_hsv[0], dtype=np.uint8)
upper_white = np.array(color_range_hsv... |
#Kitchen
import _Speech
import _Nouns
from _Verbs import *
import sys
def kitchen(sentence=[], item=[]):
noun = _Nouns.kitchen()
verb = verbs()
try:
if sentence[0] == "go":
return("You walk into the kitchen leaving the door to the dining "\
"room opene... |
#随机生成20个数字,并且筛选出其中最大的3个数
import random
numbers = []
for i in range(20):
numbers.append(random.randint(-100,100))
print(numbers)
lst = numbers
lst.sort(reverse=True)
print(lst[:3]) |
# 打印出N对合理的括号组合。
# 例如: 当N=3,输出:()()(),()(()),(())(),((()))
'''
例:N = 2
( if left
(( if left () if right
(() if right ()( if left ()) if right
(()) if right ()() if right
利用二叉树理解
'''
d... |
#给定一个整型列表,请实现从其中找出2个数的和为某一个指定的值?
# 如:lst =[1,5,2,7,4,9],指定的目标值为11,可以从中找出 2和9之和为11
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print (lst)
sum = int(input("请输入总和值:"))
def find_sum(sum, lst):
for one in range(len(lst)-1): #第一个值为lst[0]到lst[7]
for two in range(one + 1, len(lst)): ... |
#一个5位数,判断它是不是回文数
num = input("please enter a five-digit number: ")
def TellPa(num):
for i in range(2):
if num[i]!=num[-i-1]:
print("不是回文数")
break
else:
print("是回文数")
|
#给出任意一个列表,请查找出x元素是否在列表里面,如果存在返回1,不存在返回0
方法一:
lisa = [1,2,3,'a',[4,5,[6]],'b']
a = str(lisa)
flag = a.find(str(input('>>>')))
if flag != -1:
print ('此数存在:1')
else:
print ('此数不存在:-1')
方法二:
#交互式
a = None
lisa = []
while a != 'end':
a = input('>>>')
lisa.append(a)
a = str(lisa)
flag = a.find(str(input('>>>... |
#实现一个可迭代的类
class Iter:
def __init__(self):
self.item=[1,2]
def __iter__(self):
return iter(self.item)
for i in Iter():
print(i) |
list = input('请输入一个列表=')
code = input('请输入元素=')
for i in list:
if code in i:
print(1)
break
else:
print(0) |
import random
goods = {"袜子": 10, "鞋子": 20, "拖鞋": 30, "项链": 40}
def outer(func):
def inner(goods_deal):
func(goods_deal)
count = {}
goods_lst = []
for k in goods_deal:
count[k] = 0
goods_lst.append(k)
times = int(input("返回的次数:"))
lst = []
... |
def fibonacci_1(num: int):
if num == 0:
return 0
elif num == 1:
return 1
a = 0
b = 1
for i in range(num):
a, b = b, a + b
print(a, b)
def fibonacci_2(num: int):
if num <= 1:
return num
return fibonacci_2(num - 1) + fibonacci_2(num - 2)
# 2、使用 Python 实... |
#要求: 给出任意一个列表,请查找出x元素是否在列表里面,如果存在返回1,不存在返回0
def elementJudgement(lst,x=None):
while type(lst)==list:
return 1 if x in lst else 0
break
else:
print('TypeError:the arguement lst must be list')
return None
lst = [11,2,5,8,5,4]
print(elementJudgement(lst,5))
|
import requests
import threading
# 1、并发抓取10 个url,并且打印出它们的状态码、和文本内容
def fetch(urls: list):
def req(url):
ret = requests.get(url)
print(ret.status_code, ret.text)
for l in urls:
threading.Thread(target=req, args=(l,))
# 2、上下文管理是什么?请实现一个python 类,具有上下文管理功能
class A:
def __init__(se... |
#打乱一个排好序的list对象alist,alist=[1,2,3,4,5]
import random
alist = [1,2,3,4,5]
random.shuffle(alist)
print(alist) |
#打乱一个排好序的list对象alist,alist=[1,2,3,4,5]
import random
alist=[1,2,3,4,5,6,7,8,9,10]
random.shuffle(alist)
print(alist) |
a = 1
b = 1
print(a)
print(b)
while True:
c = a + b
a = b
b = c
if c >= 100:#设置最大数
break
print(c) |
# 实现数据结构stack(栈),并实现它的append,pop方法[手动查询相关资料理解stack特点以及与queue区别]
# 栈(stack):是限定仅在表尾进行插入或删除操作的线性表。表尾为栈顶,表头为栈底,空表为空栈。
# 是后进先出(last in first out)的线性表(LIFO结构)
# 队列(queue):是只允许在表头进行删除,表尾进行插入的线性表,表头为队头,表尾为队尾,空表为空队。
# 是先进先出(first in first out)的线性表(FIFO结构)
class Stack:
def __init__(self):
... |
# functions
def countNumbers(num):
for i in range(0, num +1):
print(i)
# return the result
return i
countNumbers(10)
def sales(item, price, day):
return(f'I bought {item} and it cost me {price}, it was great a week {day}')
sales('uvas',23, 'saturday') |
import unittest
import modifyUser
#ModifyUser 2 test cases
#1. Test case for correct username and password. Allows user to modify her password.
#2. Test case for correct username and wrong password does not allow the user to modify.
class ModifyUserTestCase(unittest.TestCase):
def setUp(self):
# pass
self.userna... |
import requests
import pandas
import numpy as np
from bs4 import BeautifulSoup
def getShopLinks(url):
#This is a list which will hold all the wiki links
list = []
#Grabs the Wiki page for all the shops
html = requests.get(url)
#Puts it into a beautiful soup object so we can pars... |
import functools as ft
class TopSortException(Exception):
pass
def read_deps():
n, m = [int(x) for x in input().split()]
deps = [set() for _ in range(n)]
for _ in range(m):
x, y = [int(x) for x in input().split()]
deps[y-1].add(x-1)
return deps
def _top_sort_dfs(curr, deps, state, top_sorted):
if state[cur... |
data = [7, 3, 2, 99, 4, 9, 9, 1, 1]
print(data)
def swap(index1, index2, data):
temp = data[index1]
data[index1] = data[index2]
data[index2] = temp
def selection_sort(data):
for i in range(len(data)):
min_index = i
for j in range(i, len(data), 1):
if data[j] < data[min_ind... |
#Creating a text file
file = open(r'C:\\Users\\thessceniza\\Desktop\\CRUD Exercise\\quiz.txt', 'w')
quiz_list1 ='Sampaguita is the National flower of the Philippines.\nThere are 15 regions in the Philippines.\nPhilippines has a total of 7,107 islands.\nBacolod City is known for its Masskara Festival.\nMayon volcano ca... |
import time
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# compare the value to the root's value to determine which direction
# we're gonna go in
... |
import Tkinter as tk
class ExampleApp(tk.Frame):
''' An example application for TkInter. Instantiate
and call the run method to run. '''
def __init__(self, master):
# Initialize window using the parent's constructor
tk.Frame.__init__(self,
master,
... |
#!/usr/bin/python3
import sys
datos = input().split()
L = int(datos[0]) # Longitud de la linea de luces a fabricar
N = int(datos[1]) # número de colores diferentes
C = int(datos[2]) # consumo maximo de la tira
datos = input().split()
consumo = [] # consumo de cada bombilla
for i in range(N):
consumo.appe... |
print("welcome to Hana and Mashael's game")
print("lets guess Mashael's favorite genre")
for x in range (3):
guess = input("what is your guess?")
#print(x)
#print(guess)
if guess == "horror" or guess== " horror":
print("correct")
print("\U0001f600","\U0001f600")
break
... |
import sys
def protected(password):
"""Requests the user to input the password before running decorated function."""
def decorator(f):
def wrapper(*args, **kwargs):
attempts = 3
while attempts > 0:
user_password = input("Password: ")
if user_pass... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import numpy as np
from pandapower.control.basic_controller import Controller
class CharacteristicControl(Controller):
"""
... |
'''
CodeWars kata from codewars.com
Count the number of Duplicates
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) an... |
from commons.commons import read_puzzle_input
import os
def solve():
"""
Advent Of Code 2019 - Day02 Solution.
:return: tuple(partOneResult[int], partTwoResult[int])
"""
# Store parsed puzzle input "globally" to avoid re-reading input file in part-two of the puzzle. We copy parsed program instead... |
# replace "your team name" with the name you want
# for your turtle. Make sure the text is enclosed
# by quotation marks
# for example:
# team_name = "The Cool Team"
team_name = "team AJ"
# replace "your team color" with the name of the color
# you want your turtle to be. Make sure the text is
# enclosed by quotat... |
'''
Created on Aug 29, 2019
@author: Carrie
'''
from _ctypes import Array
class Player: #defining the basic characteristics of a player
health=0
name=""
def __init__ (self,name,health):
self.name=name
self.health=health
return
def health (self):
if ... |
# mi_edad.py
# calcula tu edad en días, horas, minutos y segundos
# convertimos a <edad> (string) en un integer
# para poder operar aritméticamente
edad = int(input('Ingresá tu edad: '))
dias = edad * 365
horas = dias * 24
minutos = horas * 60
segundos = minutos * 60
print('\nTu edad es ' + str(edad) + ' años.')
... |
# excepto_tres.py
# imprime <num> hasta que sea igual a 3
num = 0
while num < 6: # mientras <num> sea menor que 6
num += 1
if num == 3:
break # corta cuando <num> sea 3
print(num)
|
# b_args_con_clave.py
# muestra ejemplos de funciones con argumentos con clave (keyword arguments)
# en la función <operaciones> de a_args_posicionales.py vemos que se aceptan
# dos argumentos: <a> y <b>
# estos argumentos tienen nombre (clave), aunque aceptan ser tratados posicionales
# en la medida en la que no se l... |
# indices.py
# muesta métodos que hacen uso de índices
lista = ['python', 'academy', 'fundamentals', 'listas', 'índices', 'segmentos']
print(f'\nLista original: {lista}')
# podemos usar range(len(coleccion)) para obtener un iterador de tantos índices
# como ítems contenga nuestra colección
print('\nUsando range():... |
# algunos_metodos.py
# ejemplos de métodos propios de todas los objetos de clase list
lista = ['python', 'academy', 'python', 'fundamentals']
print(f'\nLista original: {lista}')
# list.count() cuenta los ítems en una lista
n_python = lista.count('python')
n_academy = lista.count('academy')
print('\nUsando list.co... |
# alumnos.py
# programa que permite crear diccionarios representando alumnos, asignar notas,
# imprimir información de interés, y guardar en o leer desde un archivo de texto
# en formato JSON
import json
class Alumno:
'''
Una simple clase que representa a un alumno.
'''
def __init__(self, nombre, ap... |
# solo_pares.py
# imprime sólo números pares en <enteros>
enteros = list(range(10))
for n in enteros:
if n != 0: # si <n> no es 0
pass
else: # si <n> es 0, continúa con la siguiente iteración
continue
if n % 2 == 0:
print(n)
|
# Most Factors
# U5W2
# Solution
# input
num = int(input('Enter an upper limit: '))
# processing & output
''' Solution Process
We will be storing each number's list of factors in a List.
Therefore,
-- loop through from 1 to Num inclusively
-- Determine each number's factor List
-- Then re loop through the database t... |
# List of Primes under N
# U5W2
# Solution
# IPO
upper = int(input('Enter the value of N: '))
''' Solution Thoughts:
We will be iterating throught 2 to upper,
If any of those numbers are a prime then we add it to a list.
'''
primes = [2,3] # initialization w/ first 2 Primes
# this is to make our life a little easier... |
class Graph:
def __init__(self,size):
self.size=size
self.vertices={}
self.adjList=[[]for i in range(self.size)]
self.vertexIndex=0
def add_Edge(self,v1,v2):
if v1 not in self.vertices:
self.vertices[v1]=self.vertexIndex
self.vertexIndex+=1
... |
x=5
y=8
print(x==y)
print(x+y)
print(x<<y)
|
def listDivide(numbers, divide=2):
"""Returns total number of elements in a given list (`numbers`) that are divisibe by `divide`.
Parameters
-----------
numbers: List[]
Lit containing integer elements.
divide: int, defaultvalue = 2
Divisor. Each element in the list will... |
#List
def divlist(n):
ans=[]
for each in range(1, n+1):
if n%each==0:
ans=ans+[each]
return ans
def hailstone(n):
ans=[n]
while n != 1:
if n%2==1:
n=3*n+1
else:
n=n/2
ans=ans+[n]
return ans
def fib(n):
ans=[0, 1, 1]
w... |
import math
def f(x):
return x + 2.
def g(x):
return 2. * x
def h(x):
return f( g(x) )
def myabs(x):
if x >= 0:
return x
else:
return -x
def mymax(x, y):
# x=input("First Number: ")
# y=input("Second Number: ")
if x>y:
return x
elif x<y:
return y
e... |
def read_starting_numbers(filename):
with open(filename) as f:
return [int(y) for y in [x.split(',') for x in f][0]]
def play(numbers, n):
count = len(numbers)
spoken_nums = {}
last_spoken = numbers[len(numbers) - 1]
last_spoken_turn = len(numbers)
for idx, num in enumerate... |
'''
Instructions
Convert heights and positions, which are regular lists, to numpy arrays. Call them np_heights and np_positions.
Extract all the heights of the goalkeepers. You can use a little trick here: use np_positions == 'GK' as an index for np_heights. Assign the result to gk_heights.
Extract all the heights ... |
import sys
def devcon(arr,i, x):
print('\n\n Rekursion Nr. '+str(x))
print('L = '+str(arr))
print('Wähle p als letztes Element von L')
p = arr[len(arr)-1]
print('p = '+str(p))
L1 = ([])
L2 = ([])
print('L1 enthält alle Elemente aus L die kleiner als ')
print('L2 enthätl alle Elemente... |
"""
Mya Gwinn
Purpose: To pose questionable trivia to the user. Depending on the
user's answers, the program will determine the most appropriate response
using a point system (that's for later tho, like end-of-route).
Points: If the user gets more wrong than right, the program will display
more egotistical te... |
from prac06.Guitar import Guitar
def main():
guitars = []
print("My Guitars!")
name = input("Name: ")
while name != "":
year = get_float("Year: ")
cost = get_float("Cost: ")
guitar_add = Guitar(name, year, cost)
guitars.append(guitar_add)
print(f"{guitar_add} ad... |
import math
def primeSieve(sieveSize):
# Returns a list of prime numbers calculated using
# the Sieve of Eratosthenes algorithm.
sieve = [True] * sieveSize
sieve[0] = False # zero and one are not prime numbers
sieve[1] = False
# create the sieve
for i in range(2, int(math.sqrt(sieveSize)) + 1):
pointer = i * 2
... |
trigger=True
gravedadL=0
gravedadM=0
gravedadG=0
menorInfracc=None
motivoMenorInfracc=None
clausurarFabrica=False
cont=0
total=0
contInfracc=0
print("SISTEMA DE INFRACCIONES")
print("FABRICA DE PINTURAS\n")
while trigger:
tInfr=int(input("Ingrese el tipo de infraccion (1,2,3 o 4): "))
if tInfr == 0:
trigger=Fals... |
null= False
maxnegativo=0
minpositivo=0
prom=0
cont=1
while null == False:
while True:
try:
numero=int(input("Ingrese un valor numerico, se cancelara el ingreso con (null): "))
except ValueError:
null=True
continue
if cont == 0:
"""if numero < 0:
maxnegativo=numero
elif numero>0:
minpositiv... |
def hallar_fibonacci(numero):
listaF=[]
cont=0
while cont < numero:
if cont==0:
listaF.insert(cont,1)
elif cont==1:
listaF.insert(cont,1)
else:
listaF.insert(cont,listaF[cont-2]+listaF[cont-1])
cont= cont+1
return listaF
numero=int(input("Ingrese el numero de posicion: "))
listaF=hallar_fibonacci(... |
fin=False
nombres_y_fechas={}
cont=0
import datetime
while fin == False:
nombre=input("Ingrese nombre: ")
if nombre == "fin":
fin=True
else:
nombres_y_fechas[nombre]=0
f= input("Ingrese fecha de nacimiento formato (ddmmaaaa: ")
fecha= datetime.datetime.strptime(f, '%d%m%Y')
nombres_y_fechas[nombre]= fecha
... |
fechahoy=[29,3,1994]
print(fechahoy[:])
primerfecha=[]
print("Ingrese una primera fecha:")
primerfecha.append(int(input("Ingrese primer dia: ")))
primerfecha.append(int(input("Ingrese mes: ")))
primerfecha.append(int(input("Ingrese anio: ")))
print(primerfecha)
segundafecha=[]
print("Ingrese segundo dia: ")
segundafe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date, timedelta
from random import randrange
def random_date(min_date, max_date):
d = max_date - min_date
delta = randrange(d.days)
return min_date + timedelta(days=delta)
|
#!python3
#############################################################
# FILE : math_print.py
# WRITER : Raz Karl , razkarl , 311143127
# EXERCISE : intro2cs ex1 2016-2017
# DESCRIPTION: A set of functions which print mathematical
#############################################################
import math
def sin_30()... |
#!python3
import turtle
def intro_test():
"""This is only a test method for printing hello"""
print("hello")
def draw_petal(petal_thickness=0.5, petal_length=30):
"""Draws a single rectangular petal with the given length and thickness.
Pen state (up/down) should be set before calling this method.
... |
#!/usr/bin/env python3
#############################################################
# FILE : articles.py
# WRITER : Raz Karl , razkarl , 311143127
# EXERCISE : intro2cs ex10 2016-2017
# DESCRIPTION: Defines the Article class.
#############################################################
class Article:... |
############################################################
# Helper class
############################################################
import ship_helper
class Direction:
"""
Class representing a direction in 2D world.
You may not change the name of any of the constants (UP, DOWN, LEFT, RIGHT,
NOT_M... |
import os
#BOLETA DE VENTA
#DECLARAR VARIABLES
producto,costo,rebaja="",0.0,0.0
#INPUT
producto=os.sys.argv[1]
costo=float(os.sys.argv[2])
rebaja=float(os.sys.argv[3])
#PROCESSING
precio_total=round(costo-rebaja)
#VEREFICADOR
producto_calidad=(precio_total>=250)
#OUTPUT
print("#####################... |
import os
#BOLETA DE VENTA
#DECLARAR VARIABLES
consumidor,precio_moto,precio_auto="",0.0,0.0
#INPUT
consumidor=os.sys.argv[1]
precio_moto=float(os.sys.argv[2])
precio_auto=float(os.sys.argv[3])
#PROCESSING
total=round(precio_moto+precio_auto)
#OUTPUT
print("################################")
print("# ... |
import os
#BOLETA DE VENTA
#DECLARAR VARIABLES
cliente,precio_polo,precio_pantalon="",0.0,0.0
#INPUT
cliente=os.sys.argv[1]
precio_polo=float(os.sys.argv[2])
precio_pantalon=float(os.sys.argv[3])
#PROCESSING
total=round(precio_polo+precio_pantalon)
#VERIFICADOR
cliente_favorable=(total>400)
#OUTPUT
... |
import os
#BOLETA DE VENTA
#DECLARAR VARIABLES
nombre,producto1,precio_p1,producto2,precio_p2="","",0.0,"",0.0
#INPUT
nombre=os.sys.argv[1]
producto1=os.sys.argv[2]
precio_p1=float(os.sys.argv[3])
producto2=os.sys.argv[4]
precio_p2=float(os.sys.argv[5])
#PROCESSING
total=round(precio_p1+precio_p2)
#VE... |
import twitter
import os
def main():
"""Sets up API and searches for Tweets as specified"""
twitter_api = setup_api() # Initialises API
search_twitter(twitter_api,"'roger federer' OR tennis (suisse OR swiss) (url:news OR url:nouvelles) -lang:de") #Tweet search
def setup_api():
"""Gets user API credent... |
# Esse codigo foi feito em janeiro de 2020 qdo comecei a estudar programacao!
# -- coding: utf-8 --
# '''
# 1. Considere um input do usuário como sendo o valor base para o cálculo,
# sobre esse valor aplique um desconto de 10%, e como saída deverá apresentar o
# valor final com desconto em duas diferentes formata... |
"""
Exemplo de uso de funções para cadastro
Uso de Dicionários como banco de dados
Estrutura:
products_db {
id : {
name: ,
city: ,
age:
}
}
"""
import Utilities as util
CONST_FIELD_NAME = "name"
CONST_FIELD_CITY = "city"
CONST_FIELD_AGE = "age"
def register_client(id, clients):
... |
'''When the wind blows in cold weather, the air feels even colder than it actually is because the movement of the air increases the rate of cooling for warm
objects, like people. This effect is known as wind chill. In 2016, Jammu and Kashmir, the Delhi and the Himachal Pradesh adopted the following formula for computi... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,100)
# 1.
# plt.figure()
# plt.subplot(2,1,1)
# plt.plot(x,np.sin(x))
#
# plt.subplot(2,1,2)
# plt.plot(x,np.cos(x))
#
# plt.show()
# 2.
# fig,ax=plt.subplots(2)
# ax[0].plot(x,np.sin(x))
# ax[1]=plt.plot(x,np.cos(x))
# 3.
fig=... |
# Function defintion for sq()
def sq(x):
x = x*x
print x
return;
# Calling Function
for i in range(20):
sq(i)
print i
|
import sys
if(len(sys.argv) != 2):
print("give 1 arg")
sys.exit(1)
numOfSeats = int(sys.argv[1])
array = []
f=open("output.txt","r")
for i in f.read().split():
array.append(int(i))
f.close()
answer = []
for i in range(numOfSeats):
answer.append(i+1)
if(sorted(array) == answer):
print("ok")
|
#################
#
# Uso do print()
#
################
# A função print() mostra na tela uma mensagem ou o valor das variáveis.<br>
# Assim é só colocar uma variavel dentro do print() ou uma string (texto) desta forma:
# Com um uma string (texto)
print("Sejam bem vindos ao nosso sistema de cadastro de pessoas"... |
from sqlite3 import connect
class Database_Utils:
def __init__(self, database):
# Conectar ao SQLite3
self.bd = connect(database)
self.sql = self.bd.cursor()
def listar(self, tabela: str):
# Selecionar tabela
self.sql.execute(f'SELECT nome FROM {tabela}')
# Reco... |
# Exercicio 10
# Faça um programa que peça o nome de 2 produtos, a quantidade comprada de cada produto (inteiro) e o valor (float) de cada um.
#
# Mostre o nome a quantidade, preço por unidade e o total de cada produto.
produto1 = input("Digite o nome do primeiro produto:")
qtd_produto1 = int(input("Quantas undidade... |
"""Exercício 4
(use o conhecimento que foi passado no curso)
Crie um programa com um menu interativo:
-----
Cadastro de pessoas v1.0
A) Cadastrar Pessoa
B) Ver todos os nomes cadastrados:
C) Ver cadastro pelo nome:
D) Apagar um cadastro pelo nome:
S) Sair
-----
Para A: Cadastre os dados do cliente (Nome, idade... |
n1, n2, n3, n4 = map(float, input().split())
media = ((n1 * 2) + (n2 * 3) + (n3 * 4) + (n4*1))/10
if(media >= 7.0):
print(f"Media: {media:.1f}\nAluno aprovado.")
elif(media < 5.0):
print(f"Media: {media:.1f}\nAluno reprovado.")
elif(media >= 5.0) and (media <= 6.9):
print(f"Media: {media:.1f}\nAluno em ex... |
# Exercicio 9
# Faça um programa que peça 3 números inteiros e mostre o os tês em ordem crescente.
#
#
print("Digite 3 números diferentes")
num1 = int(input("Digite um número: "))
num2 = int(input("Digite outro número: "))
num3 = int(input("Digite mais um número: "))
if(num1<num2 and num2<num3):
print(num1, nu... |
# ---
#
#Laço condicional 2
#
# ---
# Laço condicional aninhado
# As vezes necesitamos mais condições para o mesmo problema.
#
# Para isso existe 1 solução o "elif"
#
# O elif fica aninhado (dentro) do if e é executado somente se a sua condição for verdadeira.
#
# if <condição1>:
# ....<ação>
# elif <condição2>:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.