text
stringlengths
37
1.41M
def len(iterable): return sum(1 for x in iterable) def count(iterable, element): return sum(1 for x in iterable if x == element) def count_if(iterable, predicate): return sum(1 for x in iterable if predicate(x))
import os,sys a = 5 b = 3 st = "a > b" if a > b else "a < b" print(st) print("a > b") if a > b else print("a < b") c = 6 d = 6 print("c > d") if c > d else (print("c < d") if c < d else print("c == d")) #st = print("crazyit"); x = 20 if a > b else "" st = x = 20; print("crazyit") if a > b else "" print(st) print(x) s...
import numpy as np import matplotlib.pyplot as plt mean_values = [1, 2, 3] variance = [0.1, 0.25, 0.5] bar_label = ["bar1","bar2","bar3"] x_pos = list(range(len(bar_label))) #将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。 """ >>>a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) ...
#!/usr/bin/env python import random from main import Sudoku class Multiplayer_Sudoku(Sudoku): def __init__(self, players, revealed=0): super(Multiplayer_Sudoku, self).__init__() self.players = players self.mistakes = dict((x,0) for x in players) self.cur_player = 0 self.known_data = list(False ...
# -*- coding: utf-8 -*- print("Podaj wzrost w cm:") wzrost = input() print("Podaj wagę w kg:") waga = input() BMI = int(waga) / int(wzrost) ** 2 print ("Twoje BMI wynosi:", BMI)
#Zadanie 7.4 # -*- coding: utf8 -*- numer = int(input("Podaj liczbę:\n")) for n in range(1, 2): if numer % 3 == 0: print("Podana liczba jest wielokrotnością liczby 3") elif numer % 4 == 0: print("Liczba jest wielokrotnością liczby 4") elif numer % 3 == 0 and numer % 4 == 0: print("...
#Zadanie 2.3 - KalkulatorZapotrzebowaniaKalorycznegoKOBIETA # -*- coding: utf8 -*- weight = float(input("Podaj proszę swoją wagę kg: ")) height = float(input("Podaj proszę swój wzrost w cm: ")) age = int(input("Podaj proszę swój wiek: ")) S = -161 PPM = 10 * weight + 6.25 * height + 5 * age + S print("Twoje dzienne ...
#Zadanie 6.2 # -*- coding: utf8 -*- print("Podaj wagę w kg: ") weight = float(input()) print("Podaj wzrost w cm: ") height = float(input())/100 BMI = weight / (height ** 2) print("Twoje bmi wynosi:", round(BMI, 2)) if (BMI < 18.5): print("Niedowaga") elif (18.5 <= BMI < 24): print("Waga prawi...
""" pyfsm - Python Finite State Machine =================================== A simple Python finite state machine implementation. pyfsm is based on various states contained within a task. The task can be retrieved using L{pyfsm.task_registry.get_task}. Use the L{pyfsm.Registry} object as the central L{pyfsm.task_regis...
""" Alocação de memória em Python -> este é um laboratório apenas conceitual -> Lembre-se => tupo em Python é objeto OBS.: 1- Python inteligentemente reutiliza valores já alocados para novos valres, economizando espaço em memória 2- Não se esqueça que a RAM de seu computador está dividida em partes, ...
""" Filter =>> sua funçao é filtrar dados de uma determinada coleção - Assim como a função map(), a função filter() recebe dois parâmetros, sendo um uma função e o outro um iterável - Cada valor do iterável será passado para a função que deverá retornar algum valor - DICA: Como função trabalhe com lambdas ...
""" Tipos em Python na Prática -> deixando um pouco mais complexo # Trabalhando com Type Hinting em tipos mais complexos -> olhando para as variáveis não para seu conteúdo nomes: list = ['Ciencia', 'Dados'] versoes: tuple = (3, 5, 7) opcoes: dict = {'ar': True, 'banco_couro': True} valores: set = {3, 4, 5, 6} pri...
""" Módulos Customizados => como módulos Python nada mais são do que arquivos Python, então todos os arquivos criados neste curso e os que venham a criar são também módulos Python prontos para serem utilizados Como exemplo vamos chamar o lab27_funcoes_com_parametros para teste =>> OBSERVE from lab27_funcoes_com_param...
""" Dictionary Comprehension ->> Se quisermos criar um dicionário fazemos => dicionario={'a': 1, 'b': 2, 'c': 3, 'd': 4} Se quisermos criar uma lista fazemos => lista=[1, 2, 3, 4] Se quisermos criar uma tupla fazemos => tupla=(1, 2, 3, 4) ou tupla = 1, 2, 3, 4 Se quisermos criar um set (conjunto) fazemos => conjunto={...
""" Criando Loops =>> criando sua própria versão de loop """ # O que sabemos e praticamos ->> sabemos isso ... for num in [1, 2, 3, 4, 5]: # iter([1, 2, 3, 4, 5]) print(f'Iterando na lista -> {num}') # next(num) for letra in 'Python Ciência de Dados': # iter('Python Ciência de Dados') print(f'Iterando na...
""" Listas Aninhadas (Nested Lists) ->> em Python não existem arrays =>> Python possui Listas - Algumas linguagends de programação possuem uma estrutura de dados chamadas de arrays: - Unidimensionais ->> (Arrays/Vetores) - Multidimensionais ->> (matrizes) """ # Exemplos -> veja uma Matriz 3 x 3 a...
""" Tipo float, decimal => casas decimais Obs.: o separador de casas decimais na programação é o ponto (.) e não a vírgula (,) Todas as operações realizadas com inteiros são possíveis com float """ # Errado do ponto de vista do float mas gera uma tupla valor = 1, 44 print(valor) print(type(valor)) # Será do tipo tup...
""" Manipulando data e hora => eventualmente precisamos trabalhar com Data e Hora. NOTA: Python nos ajuda, pois possui um método built-in (integrado) para se trabalhar com data e hora chamado datetime # Conhecendo o datetime - Primeiro, precisamos importá-lo import datetime print(f'Para conhecê-lo...
""" Módulos Externos => são módulos que não são instalados previamente com a linguagem Python Para instalar um módulo: pip install <nome_modulo> Utilizamos o gerenciador de pacotes Python chamado Pip ->> Python Installer Package Você pode conhecer todos os pacotes oficiais no site =>> https...
""" Módulos Builtin => são módulos integrados que já vem instalados no Python Ao instalar Python os módulos builtin são instalados também, a única coisa é que eles não são carregados sem que você demande explicitamente esse desejo. Para conhecer um pouco sobre os módulos builtins digite dir(__builtins). Pa...
""" POO -> Classes ->> nada mais são do que modelos dos objetos do mundo real sendo representados computacionalmente NOTAS: 1- Imagine que você queira fazer um sistema para automatizar o controle das lâmpadas da casa/empresa. Existe o tipo lâmpada em Python??? 2- Não existe, ma...
""" Daniel Daugherty Word Frequency Analysis Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string def get_word_list(file_name): """ Reads the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list ...
import math as m #bisection function, calculate any math system def bisection(function, beginValue, endValue, errorRate, maxIteration): index = 0 beginFunctionValue = function(beginValue) while index < maxIteration: middleValue = beginValue + (endValue - beginValue) / 2 middleFunctionValue ...
""" 9-5 상속 https://youtu.be/kWiCuklohdY?t=14368 """ # 일반 유닛 class Unit: def __init__(self, name, hp): self.name = name self.hp = hp # 공격 유닛 class AtttackUnit(Unit): def __init__(self, name, hp, damage): Unit.__init__(self, name, hp) self.damage = damage def atta...
from sys import maxsize def solution(arr): """ Args: arr (list): List of integers Returns: int: absolute value of the difference between the sum of first and the second parts of n """ max_sum = 0 for i in arr: max_sum += i min_difference = maxsize sub_sum = 0 ...
def caesar(stringer): string = stringer.split() out_str = '' for i in string: for j in i: if j.isalpha(): out_str += sdvig(j, count_char(i)) else: out_str += j out_str += ' ' return out_str[:-1] def sdvig(symb, num): abc = 'ab...
""" @author : CK =>ckrajadurai7@gmail.com @github : https://github.com/ck2605 @date : 13/03/2019 ==============================STAIRCASE(#) PATTERN===================================================================== IF ROW = 5 ANSWER(O/P): # # # # # # # # # # # # # # # """ n = int(input("enter th...
# Escrever um programa que leia duas matrizes A e B de uma dimensão com dez elementos. A matriz A deve aceitar apenas a entrada de valores divisíveis por 2 e 3, enquanto a matriz B deve aceitar apenas a entrada de valores múltiplos de 5. A entrada das matrizes deve ser validada pelo programa e não pelo usuário. Constru...
# Ler dois valores para as variáveis A e B e efetuar a troca dos valores de forma que a variável A passe a possuir o valor da variável B e a variável B passe a possuir o valor da variável A. Apresentar os valores após a efetivação do processamento da troca. A = input('valor de A: ') B = input('Valor de B: ') Aux = ...
# Elaborar um programa que leia uma matriz A de uma dimensão com dez elementos inteiros. Construir uma matriz C de duas dimensões com três colunas, sendo a primeira coluna da matriz C formada pelos elementos da matriz A somados com 5, a segunda coluna seja formada pelo valor do cálculo da fatorial de cada elemento cor...
# Realizar a leitura dos valores de quatro notas escolares bimestrais de um aluno representadas pelas variáveis N1, N2, N3 e N4. Calcular a média aritmética (variável MD) desse aluno e apresentar a mensagem "Aprovado" se a média obtida for maior ou igual a 5; caso contrário, apresentar a mensagem "Reprovado". Informar ...
# Elaborar um programa que leia duas matrizes A e B de duas dimensões com quatro linhas e cinco colunas.A matriz A deve ser formada por valores divisíveis por 3 e 4, enquanto a matriz B deve ser formada por valores divisíveis por 5 ou 6. As entradas dos valores nas matrizes devem ser validadas pelo programa e não pelo...
# Elaborar um programa que leia uma matriz A do tipo vetor com 20 elementos inteiros. Construir uma matriz B do mesmo tipo e dimensão da matriz A, sendo cada elemento da matriz B o somatório de 1 até o valor do elemento correspondente armazenado na matriz A. Se o valor do elemento da matriz A[1] for 5, o elemento corr...
# Elaborar um programa que leia duas matrizes A e B de uma dimensão do tipo vetor com dez elementos inteiros cada. Construir uma matriz C de mesmo tipo e dimensão que seja formada pelo quadrado da soma dos elementos correspondentes nas matrizes A e B. Apresentar os elementos da matriz C. A = [] B = [] C = [] for ...
# Elaborar um programa que leia uma matriz A do tipo vetor com 15 elementos inteiros. Construir uma matriz B de mesmo tipo, e cada elemento da matriz B deve ser o resultado da fatorial correspondente de cada elemento da matriz A. Apresentar as matrizes A e B. A = [] B = [] for i in range(0, 15): A.append(int(in...
# Elaborar um programa que calcule uma raiz de base qualquer com índice qualquer. base = float(input('informe o valor da base: ')) RaizQ = base **(1/2) print('A Raiz Quadrada de {} é igual a {}'.format(base, RaizQ))
# Construir um programa que leia uma matriz A de uma dimensão do tipo vetor com 30 elementos do tipo inteiro.Ao final do programa, apresentar a quantidade de valores pares e ímpares existentes na referida matriz. A = [] Par = 0 Impar = 0 for i in range(0, 30): A.append(int(input('Informe o {}° valor do vetor ...
# Elaborar um programa que calcule e apresente o valor do volume de uma caixa retangular, utilizando a fórmula VOLUME <- COMPRIMENTO* LARGURA* ALTURA. comp = int(input('Informe o comprimento: ')) larg = int(input('Informe a largura: ')) alt = int(input('Informe a altura: ')) vol = comp * larg * alt print('O volum...
# Efetuar a leitura de três valores inteiros desconhecidos representados pelas variáveis A, B e C. Somar os valores fornecidos e apresentar o resultado somente se for maior ou igual a 100. A = int(input('Informe valor de A: ')) B = int(input('Informe valor de B: ')) C = int(input('Informe valor de C: ')) Soma = A ...
# Elaborar um programa que leia uma matriz A do tipo real de duas dimensões com cinco linhas e cinco colunas. Apresentar o somatório dos elementos situados na diagonal principal (posições A[1, 1 ], A[2,2], A[3,3], A[4,4] e A[5,5]) da referida matriz. A = [[], [], [], [], []] for i in range(len(A)): for j in rang...
from util import isint class Relocatable(): data = 1 main = 2 wk = 3 def __init__(self, tag, imm): self.tag = tag self.imm = imm def __add__(self, x): if not isint(x): raise RuntimeError("cannot __add__ a {}".format(x)) return Relocatable(self.tag, se...
#import math class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ #return(int(math.sqrt(x))) i=0 if(i==0 and x==0): return(0) while(i<x): i+=1 if(i*i==x): retu...
class cargos: secuenc=0 def __init__(self,des="Sin cargo"): cargos.secuenc=cargos.secuenc+1 self.codigo=cargos.secuenc self.descripcion=des if __name__ == "__main__": cargo1=cargos() # cargo1.codigo=1 # cargo1.descrip="docente" print(cargo1.codigo,cargo1.desc...
import sqlite3 import dateutil.parser import datetime import sys def ValidateArgs(): if len(sys.argv) is not 3: print("Usage: Python query.py start_date end_date") startDate = '' endDate = '' try: startDate = dateutil.parser.parse(sys.argv[1]) endDate = dateutil.parser.parse(s...
class Auto: def __init__(self, model): self.model = model def stay(self): return 'Stay' def move(self): return 'Move' class Car(Auto): def __init__(self, model, passengers_max): super().__init__(model) self.passengers_max = passengers_max class Truck(Auto): ...
# Создать свою структуру данных Список, которая поддерживает # индексацию. Методы pop, append, insert, remove, clear. Перегрузить # операцию сложения для списков, которая возвращает новый расширенный # объект. class CustomList: def __init__(self, *args): self.my_custom_list = [*args] def __str__(self...
import time import concurrent.futures from collections import deque commonList = set() q = deque() def task(item): """ タスク """ global commonList commonList.add((item.ID,sum(item.values))) def main(): global q global commonList num_workers = None # os.cpu_count() test_data_num ...
# Implement atoi which converts a string to an integer. # The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and inte...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: LARATWINS # # Created: 24/02/2018 # Copyright: (c) LARATWINS 2018 # Licence: <your licence> #----------------------------------------------------------------------------...
#------------------------------------------------------------------------------- # Name: module2 # Purpose: # # Author: student # # Created: 04/02/2018 # Copyright: (c) student 2018 # Licence: <your licence> #------------------------------------------------------------------------------- ...
# /usr/bin/env python3 # -*- coding:utf-8 -*- import math print('理解呢大 %2d-%02d' %(3,1)) print('chygkkbiu %.2f' %3.1415926535) def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny print(move(10,12,5,math.pi/6)) def fact(n): if n==1: return 1 retu...
import tkinter as tk from tkinter import * import os def main_acc(): global main_screen main_screen = Tk() main_screen.geometry("300x260") main_screen.title("Main") Label(text="Login or Register", bg="#b1abf1", fg="white", width="300", height="2", font=("Calibri", 13)).pack(padx=20, pady=...
romanInventions = { "Aquaducts": "Bridges carrying water", "Sanitation": "Clean water and adequate sewage disposal", "Roads": "Wide ways leading from anywhere to Rome" } menu = [ "List inventions", "Look up an invention", "Add an invention", "Edit an invention", "Delete an invention...
if __name__ == '__main__': fichier = open('input.txt', 'r') #open() pour ouvrir un fichier, r pour lire, w pour ecrire content = fichier.read() #lecture du fichier texte monTableau = [int(i) for i in content.split('\n')] #discomprehension pour traduire les string en int for monIterateur in monTa...
import re from functools import reduce from itertools import chain from collections import Counter import typing def get_words(word_len: int, filename: str = "words.txt") -> typing.Set[str]: """ Get all words that have the desired length from the given text file. :param filename: The name of the file to ...
#print("請輸入:", end="") #r=input("") # r=input("輸入:") # #print("你輸入了",r) # if r.find("a")!=-1: # print("你好") # elif r.find("b")=1: # print("哈囉") # else: # print("哈哈哈") # x="1,2,3,4,5,6,7" # z=x.split(",")#切割 split("做為切割的字串") # print(z) # for i in z: # print(i) # x=input("請輸入生日:")#切割範例 # z=x.split("-") # print(...
# Snake and Snake App # Author: Yuanjie Yuanjie # Date: 11/20/19 import pygame import random import time import config class Snake: # pos = (x, y), where x is the col offset, and y is the row offset. def __init__(self, pos, rows, cols): self.rows, self.cols = rows, cols self.body = [pos] ...
from tkinter import * from login_details import auto_login_details def auto_login(): """Build an auto login page using GUI""" screen = Tk() screen.title("User Login Page") screen.geometry("300x250") Label(screen, text="Please enter login details").pack() Label(screen, text="").pack() #Declaring type of va...
def minion_game(s): def is_vowel(c): return c == 'A' or c == 'E' or c == 'I' or c == 'U' or c == 'O' stuart_pts = 0 kevin_pts = 0 for i in range(len(s)): add = len(s) - i if is_vowel(s[i]): kevin_pts += add else: stuart_pts += add if stuart_p...
import random from typing import List RANDOM_LENGTH = 3 BASE_62_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # This function is just for testing. def _base62_string_to_decimal(base62_string: str) -> int: number_list = list(map(BASE_62_DIGITS.index, base62_string)) result = 0 ...
n = int(input().strip()) N = n i = 2 while i * i <= n: if n % i: i += 1 else: n //= i if n == N: print(True) else: print(False)
class TrieNode: def __init__(self): self.children = dict() self.val = 0 class Trie: def __init__(self, n): self.root = TrieNode() self.n = n def add_num(self, num): self._add(num) def _add(self, num): node = self.root for bit in...
# Importando os datasets disponíveis da biblioteca sklearn from sklearn import datasets # Importação da classe KNeighborsClassifier do pacote neighbors do sklearn from sklearn.neighbors import KNeighborsClassifier # Carregamento da base de dados Iris que classifica tipos de plantas de acordo com suas características ...
""" Pattern Matching with Ladder """ """ # # Function 1. is_match (difficulty 1) # Lets implement a function called `is_match`. `is_match(pattern, input)` "pattern" is a string where each character is a token. "input" is a string where each word is a token (space delimited). return value: boolean which represents w...
""" n Queens """ from collections import deque from copy import deepcopy class Queen(object): def __init__(self, row): self.row = row self.col = None self.possibles = deque() def __repr__(self): return '<Queen ({}, {}) >'.format(self.row, self.col) def get_possibles(se...
# Suppose we have a file with manager and reportee pairs (manager, reportee) # and we would like to convert this into a tree structure. # # Write a function create_mangement_tree which given a list of # (manager, reportee) pairs creates a tree and returns the root. # # Tree Node Data Structure: # # class Node(objec...
def main(): print("This program illustrates a chaotic function") n = input("Amount of times to loop?") x = input("Enter a number between 0 and 1: ") for i in range(n): x = 3.9 * x * (1-x) print(x) main() # this doesn't seem to work, the eval doesn't work., page 13
import math from .print_ import print_simplex_table def table_simplex(table, B, S, W): print('Starting table simplex:') print() print_simplex_table(table, B, S, W) print() if any(i!=0 for i in table[-1][:-1]): print("Cleaning the function from basis variables") for b in B: ...
from collections import defaultdict import os.path from os import path import numpy as np # Prints a bar def print_split(): print("\n--------------------------------------------------\n") def input_problem(): print("---- NOTE ----\nThe file must be in the following format:\nn MAX\t\t\tWhere n - number of it...
import os.path from os import path import sys import numpy as np from .print_ import print_split def input_vars(): sol_set = 'N' option = 2 while option != 1 or option != 2: if option == 1: print("---- NOTE ----\nThe input must be in the following format:\nN M\t\t\t\tWhere N - numb...
import os.path from os import path # Prints a bar def print_split(): print("\n--------------------------------------------------\n") def input_graph(): print("---- NOTE ----\nThe file must be in the following format:\nX\t\t\tX - Number of nodes\nN0 N1\nN1 N3\nN0 N3\n....\n....") print_split() file_na...
#!/usr/bin/env python3 def my_factorial(n): assert n >= 0 result = 1 if (n==0): return 1 for i in range(2, n+1): result = result * i return result
with open("Day1Input.txt","r") as file: lines = file.readlines() freq = 0 for line in lines: sign = line[0] value = int(line[1:]) if sign == "-": value = value * -1 freq = freq + value print(freq)
def player_1(): global numbs1,score1,lis1,continuety while continuety: print("Welcome: {} ".format(numbs1)) index1 = int(input("Player#1 – score {}:".format(score1))) index2 = int(input("Player#1 – score {}:".format(score1))) if lis1[index1] == "*" and lis1[index2] == "...
numlist = [9, 41, 32, 2, 121, 5, 73] max = numlist[0] for i in numlist: if i > max: max = i print(max)
# Primality test - Check if a number is prime or not from math import sqrt, ceil marked = [] try: num = int(input("Enter the number to check if it is prime : ")) except(ValueError): print("Please Enter a real number greater than 1 or less than -1") quit() num_sq = ceil(sqrt(abs(num))) flag = False for i in rang...
# insertion sort # Holding onto each element (and moving others) and then trying # to find it's position in the list according to those positions # iterating over each element till it is completely sorted is called insertion sort unsorted = [3,2,5,4,1,6,7,8,22,32,43,12,54,65,87,98,78,79,90,12] for i in range(len(uns...
import math def get_prime(n): if n <= 1: return [] prime = [2] limit = int(math.sqrt(n)) print(limit) # 奇数のリスト作成 data = [i for i in range(3, n + 1, 2)] while limit > data[0]: print('prime') print(prime) print('data') print(data) prime.append...
def tower_builder(n_floors): floors = [] stars = 1 space = n_floors - 1 for floor in range(n_floors): floors.append(' ' * space + '*' * stars + space * ' ') #print(floors) stars += 2 space -= 1 print(floors) return floors #test.assert_equals(tower_buil...
#https://www.hackerrank.com/challenges/countingsort4 N = input() countmap = {} for i in range(0, N): line = raw_input().strip().split() num = int(line[0]) countmap.setdefault(num, []) if i < N/2 : countmap[num].append('-') else : countmap[num].append(line[1]) out = [] for key, value in countmap.items(): ...
#https://www.hackerrank.com/challenges/find-digits T = input() for i in range(0, T): N = input() out = [n for n in list(str(N)) if int(n) and int(N) % int(n) == 0] print len(out)
print("Input -1 for wanted & -2 for unwanted") vo = input("Initial velocity : ") * 1.0 v = input("Velocity : ") * 1.0 a = input("Acceleration : ") * 1.0 t = input("Time : ") * 1.0 d = input("Distance : ") * 1.0 print " " if vo == -2: print "Impossible" if v == -1: if a == -2: print ("Velocity = " + str(((d * 2) / t...
""" This class will filter the information inside a Document and return a filtered (SAME) Document. """ from document import * from sentence import * class TextFilter: """ Applies a list of filter to a document and returns same filtered Document """ def __init__(self, filterList=None, doc=None): ...
#함수형모델을 2개를 만들어라 #1. 데이터 import numpy as np #모델1. x1 = np.array([range(1,101), range(711,811), range(100)]) y1 = np.array([range(101,201), range(311, 411), range(100)]) x1 = np.transpose(x1) y1 = np.transpose(y1) print(x1.shape) #(100, 3) output 3 #모델2. x2 = np.array([range(4,104), range(761,861),...
# RNN 기법에는 LSTM 말고도 SimpleRNN과 GRU가 있다. 두개 다 구축해보고 LSTM과 성능을 비교해보기. #1. 데이터 import numpy as np x=np.array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]]) #(4,3) y=np.array([4,5,6,7]) #(4,) print("x.shape : ", x.shape) print("y.shape : ", y.shape) x=x.reshape(x.shape[0], x.shape[1], 1) print("x.shape : ", x.shap...
# import import os import csv # csv file pulling and reading csvfile = os.path.join("..", "PyBank", "budget_data.csv") with open(csvfile, 'r') as bankfile: bank_reader = csv.reader(bankfile, delimiter=',') bank_header = next(bank_reader) months = [] monthlyprofitloss = [] totalprofitloss = 0 ...
import os import csv import traceback class BaseCar: """This is a base vehicle class""" def __init__(self, car_type=None, photo_file_name=None, brand=None, carrying=0.0): self._car_type = car_type self._photo_file_name = photo_file_name self._brand = brand ...
#Inclass exercise 3 import numpy as np from matplotlib import pyplot as plt def plot(): x = np.linspace(0, 2*np.pi, 100) y, z = np.sin(x), np.cos(x) fig = plt.figure() ax1 = fig.add_subplot(211) ax1.plot(y, "r") ax1.plot(z, "b") plt.xlabel("% of Period") plt.ylabel("Y-Value") plt.title("Plotting sin and ...
import requests from bs4 import BeautifulSoup from tkinter import * from tkinter import ttk r = requests.get("https://www.worldometers.info/coronavirus/") c = r.text soup = BeautifulSoup(c, "html.parser") data = soup.find("table", {"id":"main_table_countries_today"}) rows = data.find_all("a", {"class":"...
import wolframalpha as wa import datetime as dt import getpass as gp import wikipedia as wp user = gp.getuser() def getMessage(): time = dt.datetime.now().hour message = "Good Morning, " if (time < 12) else ("Good Afternoon, " if (time < 18) else "Good Evening, ") message += user.capitalize() return m...
import os # For using os.linesep instead of using a line separator: '\n' class Book(object): # Initialize the book title, author(s) name and price def __init__(self, title, author): # Assign the value to class variables self.title = title self.author = author class MyBook(Book): ...
###################################################################### # PWM_LED.py # # This program produce a pwm and control light exposure of an LED # with changing it's duty cycle ###################################################################### import RPi.GPIO as GPIO ledPin = 18 GPIO.setmode(GPIO.BC...
class Queue: def __init__(self): self.list = [] def enqueue(self, item): """ Inserts an element in a queue. """ self.list.append(item) def dequeue(self): """ Removes an element from a queue. """ return self.list.pop(0) def isEmpty(self): """ Checks if the queue is empty. """ if len...
''' Task The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers. ''' if __name__=="__main...
''' Kevin and Stuart want to play the 'The Minion Game'. Game Rules Both players are given the same string, S. Both players have to make substrings using the letters of the string S. Stuart has to make words starting with consonants. Kevin has to make words starting with vowels. The game ends when both players have m...
import collections n = int(input()) fields = input().split() Students = collections.namedtuple('Students', fields) total = 0 for _ in range(n): student=Students(*input().split()) total +=int(student.MARKS) print(total/n)
import calendar mm,dd,yyyy=map(int,input().split()) #print(list(calendar.day_name)) ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] #print(calendar.weekday(yyyy,mm,dd)) Returns the index position for the day from the calender.day_name print(calendar.day_name[calendar.weekday(y...
import random def random_pair_int(begin, end): assert end > begin first, second=random.randint(begin, end), random.randint(begin, end-1) if second >= first: second += 1 return first, second
import sys, pygame, random from pygame.math import Vector2 right = Vector2(1, 0) left = Vector2(-1, 0) up = Vector2(0, -1) down = Vector2(0, 1) cellSize = 36 cellNumber = 20 buffer = 5 class Snake(): def __init__(self): self.body = [Vector2(5, 10), Vector2(4, 10), Vector2(3, 10)] self.direction = ...
# The tutorial to learn how to write on a video on it. # the first lesson is to capture the video and show it in gray scale import numpy as np import cv2 as cv import datetime cap = cv.VideoCapture(0) # (task 1) # cap = cv.VideoCapture('vtest.avi') # video capture from device (task 2) # (task 4) adjusting and en...