text
stringlengths
37
1.41M
def sentenceReverser(s): words = s.split(' ') #Create a list of words i = len(words) - 1 #i is the index in the list sen = "" while i >= 0: sen += words[i] + " " #Start adding into the string from the last element in the list i ...
from math import * def basic(operation): if(operation == "1"): evaluation = 0 n = input("How many numbers would you like to add? ") elif(operation == "2"): n = input("How many numbers would you like to subtract? ") elif(operation == "3"): evaluation = 1 n = i...
import unittest from functools import wraps def score_with(score): def decorator(fn): def decorated(*args,**kwargs): ret = fn(*args,**kwargs) if ret: args[0].__class__._increase_score(score) return ret return decorated return dec...
# List minuman dengan 2 dimensi list_minuman = [ ["Kopi", "Susu", "Teh"], ["Jus Apel", "Jus Melon", "Jus Jeruk"], ["Es Kopi", "Es Campur", "Es Teler"] ] for menu in list_minuman: for minuman in menu: print minuman
def HelloWorld(): print("Hello World") HelloWorld() def Greeting(name): print("Hi " + name + "!") Greeting("Vedant") def Add(num1, num2): print(num1 + num2) Add(10, 15) def returnAdd(num1, num2): return (num1 + num2) print("Hello") sum = returnAdd(12, 34) print(sum)
#https://www.geeksforgeeks.org/maximum-product-subarray/ def MaximumProductSubArray(arr): n= len(arr) i=0 max=-float("inf") product=1 while i<n: product= product * abs(arr[i]) if(product >= max): max=product else: product=1 i=i+1 print(max...
def solution(x, y): res = str(solve(int(x), int(y))) return res if res != "inf" else 'impossible' def solve(x, y): if x == 1 and y == 1: return 0 if x < 1 or y < 1 or x == y: return float("inf") x, y = max(x, y), min(x, y) coeff = (x // y) - (1 if x % y == 0 else 0) return solve(x - coeff * y, y) + ...
user_str = input("Please enter a string.") charToFind = input("Please enter a character.") charCount = 0 for item in range(0, len(user_str)-1, 1): if charToFind == user_str[item]: charCount += 1 print(charCount)
def ddm_dd_convert(coord, direction): """Converts GPS reading from DDM to DD str coord - the ddm coordinate from $GPGGA str direction - the direction of the coord (N,S,W,E) returns - string representation of dd coordinate """ value = '' if (direction == 'S' or direction =...
import sys import os import csv #write listname content into file named filename def Writelistintofile(filename,listname): try: with open(filename,'a') as writefile: for item in listname: writefile.write(item) writefile.write(',') except: print("File "...
"""Some Code.""" def Some(): """Some.""" some = ["S", "o", "m", "e"] Some = "" for SOME in some: Some += SOME return Some def Code(): """Code.""" code = 1 CODE = -code if code * CODE == -code: Code = "Code" return Code def Some_Code(Some...
#Python Program 02 - Quadratic Solver #Written by Gabby and Kaylee import math print("Chicken Function Palace - Fine cuisine") print("Enter a number for how much you want") a = input("How many fries?") b = input("How many chicken tenders") c = input("How many pints of ice-cream?") disc = float disc = (int(b))**2-4*(i...
#Mathmatics/ Object oriented programming, and pscreen/pygame Notes #Thomas Gilman #Mr. Paul Yost #Etgg 1801-03 #16th November, 2015 #Up to now, we have been representing motion in a simple way: #X+=1, Y-=1, to move up and to the right, or X+=dX, Y-=dY #We want to Represent motion more naturally: # *direction of Motio...
#Functions and Game Loop, Assignment 6 Program 1 #by. Thomas Gilman ETGG 1801-02 #imports for code import pscreen import math import random import time #loading process pscreen.loadScreen() pscreen.fontSelect("Arial",24) #Global random colors for randomness in all colors #randR=Red randR = random.randint(5,250) #ran...
#Object Oriented example 1 import pscreen import random import time import math class Ball(object): def __init__ (self,x=400,y=300,speed=1,direction=0,radius=20,color=(255,255,255,0)): self.x=x self.y=y self.speed=speed self.direction=direction self.radius=radius s...
#Graphics list example import random import pscreen pscreen.loadScreen pscreen.fontSelect() bullet_list=[] while True: if pscreen.keyIsPressed("escape"): break pscreen.clearScreen((0,0,0)) #check to see if we want to create a bullet if pscreen.keyIsPressed("space"): #create a bullet...
#program 3 draws objects on screen if key is pressed #ETGG 1801-01 by. Thomas Gilman #imports import pscreen import random b=(0,0,255) black=(0,0,0) white=(255,255,255) def drawFace(x,y,randMood): #face pscreen.circle(x,y,20,c,0) #whites of eyes pscreen.circle(x-5,y-5,5,...
#02 - Utilizando estruturas de repetição com variável de controle, faça um programa que # -receba uma string com uma frase informada pelo usuário e conte quantas vezes aparece # -as vogais a,e,i,o,u e mostre na tela, depois mostre na tela essa mesma frase sem nenhuma # -vogal. aux = 0 frase = str(input("Digite u...
input1 = input("Enter the Range :") list1=[] #getting input from the user print "Enter the %d Numbers :"%input1 for i in range(input1): x=input() list1.insert(i,x) # finding biggest and Smallest nunber in the range list1.sort() print "The Biggest Number in the Range is :%d"%list1[len(list1)-1] print "The Smalle...
list1 = ['Gokul','Manish','Yogesh','Muthu','Siva'] str = raw_input("Enter a Name :") count=0 #using in operator if (str in list1): print "Using IN operator - The given Name is present in the list" else: print "Using IN operator - The given Name is not present in the list" #Without using in operator for i in lis...
# -*- coding: cp1252 -*- ''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' def isPalindrome(n): # we count the characters in n, push half of them on ...
def sum_higher(grades , start , end): if(start >= end): return find_num_higher(grades , grades[start] , start + 1 , end + 1) return sum_higher(grades , start + 1 , end) + find_num_higher(grades , grades[start] , start + 1 , end + 1) def find_num_higher(grades , current_grade , low , high): if(low >= high): retu...
''' Two English words are similar iff they only contain the same alphabetical letters. For example, ​food ​and g​ood​ are not similar, but ​dog ​and g​ood ​are similar. If A​ ​is similar to ​B​,then all letters in A ​​are contained in ​B,​ and vice versa. 10 < |​L|​ < 500.000 Solution: Use sets to get unique charac...
''' 1. A gardener consider aesthetically appealing gardens in which the tops of sequential physical trees (eg palm trees) are always sequentially going up and down, that is: [3, 1, 5, 2, 4] On the other hand, the following configurations would be invalid: * [4, 3, 1] reason: 3rd tree should be higher than the 2...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 30 11:23:25 2019 @author: renazhong """ #%% import random def poker(number_of_players): ranks = ['2','3','4','5','6','7','8','9','10','J', 'Q', 'K', 'A'] suits = ['clubs', 'spades', 'hearts', 'diamonds'] pdict = {} drawn = [] ...
# coding: iso-8859-1 -*- #tag usada para no dar conflitos com acentuao # Elabore um programa que gera e escreva os n mpares dos numeros entre 100 e 200. #Processamento for n in range (100, 201): if n % 2 != 0: print(n)
# coding: iso-8859-1 -*- #tag usada para no dar conflitos com acentuao # Tendo como dados de entrada a altura da pessoa, construa um algoritmo que calcule o # seu peso ideal, usando uma frmula definida. #Entrada height = float(input("Informe, em metros, sua altura: ")) #Processamento ideal_weight = (72.7 * height) -...
# coding: iso-8859-1 -*- #tag usada para no dar conflitos com acentuao # Faa um programa que leia os nomes de usurios e a sua senha e no aceite a senha # igual ao nome de usurio, mostrando uma mensagem de erro e voltando ao inicio. name = input("Informe o nome do usurio: ") password = input("Informe a senha do usurio...
# coding: iso-8859-1 -*- #tag usada para no dar conflitos com acentuao # Faa um programa que receba um cdigo numrico inteiro e um vetor de cinco posies de # nmeros reais. Se o cdigo for zero, termine o programa. Se o cdigo for 1, mostre o # vetor na ordem direta, se o cdigo for 2, mostre o vetor na ordem inversa. #...
# -*- coding: utf-8 -*- """ Created on Tue Sep 28 11:12:58 2021 @author: saurabh satapathy """ def string_test(s): d={"UPPER_CASE":0, "LOWER_CASE":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass if d[...
# -*- coding: utf-8 -*- """ Created on Mon Oct 11 12:11:07 2021 @author: saurabh satapathy """ import math def Log2(x): if x == 0: return False; return (math.log10(x) / math.log10(2)); def isPowerOfTwo(x): return (math.ceil(Log2(x)) == math.floor(Log2(x))); def hig...
# -*- coding: utf-8 -*- """ Created on Sat Oct 9 09:16:44 2021 @author: saurabh satapathy """ def slope(arr,n): #defining the function slope() s=0 k=max(arr) m=arr.index(k) for i in range(m): if not (arr[i]<k and arr[i]<arr[i+1]): s=s+1 for ...
print("Star Wars Reference Game") print("------------------------") print("1 - Hello there!") print("2 - No, Luke, I am your father!") print("3 - These are not the droids you are looking for!") print("4 - Move along") print("5 - Use the force, Luke.") i1 = input("Select your reference from the list: ") if int(i1) == 1:...
a=input("enter your choice :1.addition\n 2.subtraction\n 3.multiplication\n 4.division \n") b=input("enter 1st no.:") c=input("enter 2nd no.:") if a==1: result=b+c print result elif a==2: result=b-c print result elif a==3: result=b*c print result elif a==4: result=b/c print result else...
class Room(): def __init__(self, room_name): # __init__ initializes or CREATES the object self.name = room_name self.description = None #note, you can put "none" here to add parameters later self.linked_rooms = {} #dictionary for linking rooms, look below for link method self.charact...
import pandas as pd from AnalysisType import * from Output import * # Define count_entries() def count_entries(csv_file, c_size, delimit, *args): """Return a dictionary with counts of or totals of a second column occurrences as value for each key.""" # counts how many arguments in order to determine how m...
def polycandidates(corners): # initiating empty list of polygon candidates polygon_candidates = [] # for every corner for corner1 in corners: # take another corner point starting with the first one # if x-value of corner 2 is more than x-value of corner 1 for corner2 in co...
C = float(input('Enter Celsius temperature:')) F = float(C * 1.8 + 32) print(str(F) + '°F')
# implementation by @kaba_y, https://korogba.github.io from bisect import bisect_left from collections import deque from data_structures.huffman_node import HuffmanNode from utils.file_operations import convert_file_to_huffman_list def increment_count(node): if node.left_node is None and node.right_node is None:...
# implementation by @kaba_y, https://korogba.github.io # Simple implementation of Union-Find data structure used in Kruskal's algorithm and clustering class UnionFind: """ Union find data structure to optimize Kruskal's algorithm """ def __init__(self, kruskal_graph): self.partitions = {} ...
def alphabet_position(letter): alphas = 'abcdefghijklmnopqrstuvwxyz' for i in letter: o = ord(i) #ord value for letter determines if it is capital and lowercase letters if o > 96: position = alphas.index(i) # position gives the numerical location of letter in alphabet else: ...
from math import cos, sin, atan2, acos, pi def check_coord(b): if b == 1: while True: X = input("Insert X: ") Y = input("Insert Y: ") Z = input("Insert Z: ") try: X = float(X) Y = float(Y) Z = float(Z) ...
a = [1, 2, 3, 4, 5] def fun(x): i = 0 b = [[]] while i < len(a): j = i + 1 while j <= len(a): b.append(a[i:j]) j += 1 i += 1 print(b) fun(a)
def arithmetic_progression(a1, r, n): an = a1 + (n -1) * r Sn = ((a1 + an)*n) / 2 print("an =", an, "Sn =", Sn) if __name__ == "__main__": arithmetic_progression(0, 100, 10)
def shortest_path(M,start,goal): print("shortest path called") import copy # auxiliary function:compute_f(Map, Path , Goal) # "f_value" equals "path cost" plus "estimated distance to goal" import math def compute_f(Map, Path , Goal): if len(Path) == 0: f_value = 0 ...
''' Simple PD game model. ''' # Numpy imports import numpy.random class SimpleGame(object): ''' Simple game class. This class is analogous to our Tournament object in the Rock-Paper-Scissors tournament. ''' # Payoff matrix; payoff_matrix = [[(3, 3), (0, 5)], [(5, 0), ...
import os import sys # return bool = if there's a 3 in row or either X or O # called by CheckWinner() # pm a, b, c = strings, board position contents ('', 'X', or 'O') def Equals3(a, b, c): return (a == b and b == c and a != "") # returns if there's a winner or not # called by kivy.btnClicked() # pm board = 2d l...
# -*- coding: utf-8 -*- class Lamp: _LAMPS = [''' . . | , \ ' / ` ,-. ' --- ( ) --- \ / _|=|_ |_____| ''', ''' ,-. ( ) \ / _|=|_ |_____| '''] #__init__ Constructor de la...
# -*- coding: utf-8 -*- import csv class Contact: def __init__(self, name, phone, email): #Método constructor. Los métodos de las clases empiezan con "self" self.name = name self.phone = phone self.email = email class ContactBook: def __init__(self): self._contacts = [] def add(self, na...
def showNumbers(a): i=0 while i<a: if i%2==0: print("even") else: print("odd") i=i+1 showNumbers(12)
def check_numbers(a,b): if a%2==0 and b%2==0: print("even number") else: print("odd number") check_numbers([12,42,6,8],[12,6,8,4])
def pascal_triangle(maxRows): currentRow = 1 a = [1]; while(maxRows >= currentRow): spaces = maxRows - currentRow; currentString = '' for j in range(spaces): currentString += " " for j in range(len(a)): currentString += str(a[j]) + " " print(currentString) tmp = [1] ...
import turtle from math import cos, sin, pi def draw(x, y): turtle.goto(x, y) def move(x, y): turtle.up() turtle.setpos(x, y) turtle.down() def dot(x, y, size=5): move(x, y) turtle.dot(size) def dotP(a, size=5): return dot(a[0], a[1], size) def drawP(a): return draw(a[0], a[1...
import numpy as np class Vector: """ implementation of Eucledian vector""" def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __mul__(self, other): x = se...
s1 = input("請輸入考試次數與學生數:").split(" ") s2 = input("每次考試所佔的比率:").split(" ") t = int(s1[0]) s = int(s1[1]) for i in range(len(s2)): s2[i] = float(s2[i]) st = [[0]*t for i in range(s)] for i in range(s): w = input().split(" ") for k in range(t): st[i][k] = w[k] sc = 0 for i in range(s): ...
__author__ = 'lena' # Split method creates list from string song = "The rain in Spain" wds = song.split() print(wds) # Optional delimiter (default is " ") wds = song.split('ai') print(wds) # Join method creates str from lst wds = ["This", "is", "the", "song", "that", "doesn't", "end"] song = " " song = song.join(wds...
__author__ = 'lena' mylist = [1, 2, 4, 5] newlist = [item * 2 for item in mylist if item > 2] print(newlist) wordlist = ["apple", "banana", "grapes", "mango"] newlist = [fruit for fruit in wordlist if "e" in fruit] print(newlist) numlist = [5, 10, 12, 18, 28, 33] newlist = [num // 2 for num in numlist if num % 2 == ...
__author__ = 'lena' # Function return value can be a tuple import math def circle_info(r): # Return the area and circumference of a circle c = 2 * math.pi * r a = math.pi * r * r return c, a radius = 10 circum = circle_info(radius)[0] area = circle_info(radius)[1] print("The circumference of radius...
__author__ = 'lena' # use the built-in append method of list objects newlist = list([1, 3, 6]) newlist.append(10) vlus = (5, 15) newlist.append(vlus[0]) print(newlist) # Insert method newlist.insert(1, vlus[1]) print(newlist) # Count method print(newlist.count(5)) # Index method print(newlist.index(10)) # Reverse ...
__author__ = 'lena' # Create tuple julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia") print(julia[0:5]) print(id(julia)) # Modify tuple by slicing old tuple (creates new obj) julia = julia[0:3] + ("Eat, Pray, Love", 2010) + julia[5:] print(julia) print(len(julia)) print(id(julia)) #...
print ("EXERÍCIO 009 - ESTRUTURA DE DECISSÕES - 04") print ("Programa para uma loja de tintas") area = int(input("Valor em metros quadrados a ser pintado: ")) litros = area//6 if area % 6 > 0: litros = litros + 1 latas = litros//18 if litros % 18 > 0: latas = latas + 1 galões = litros//4 if galões % 4 > 0: ...
""" Exercício 3.10 Faça um programaque calcule o aumento de um salário. Ele deve solicitar o valor do salário e a porcentagem do aumento. Exiba o valor do aumento e do novo salário. """ salario = int(input("Digite o valor do seu salário: ")) aumento = int(input("Digite o valor porcentual do seu aumento: ")) x = ...
''' Código para rolagem de dados, para jogar rpg com os amigo durante a pandemia. ''' from random import randint while(True): numero = int(input('Qual a quantidade de faces do dado: ')) dado = randint(1, numero) if dado >= 1: print(dado) else: print('Informação incorreta! Tente n...
# Definition for a binary tree node. class Tree(object): def __init__(self, x, l = None, r = None): self.val = x self.left = l self.right = r class Solution(object): complement = {} def findTarget(self, root, k): return self.preOrder(root,k) def preOrder(self,root,k): ...
class Tree(object): def __init__(self, x, l = None, r = None): self.val = x self.left = l self.right = r class Solution(object): def binaryTreePaths(self, root): self.path = [] self.findpaths(root, '') return self.path def findpaths(self, root, curr): ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None odd = head ...
from itertools import groupby, tee students = [ {'name': 'Misa', 'note': 'A'}, {'name': 'Megumin', 'note': 'B'}, {'name': 'Yuuki', 'note': 'A'}, {'name': 'Mira', 'note': 'A'}, {'name': 'Aqua', 'note': 'C'}, {'name': 'Yui', 'note': 'B'}, {'name': 'Yukinoshita', 'note': 'A'}, {'name': 'Nami', 'note': 'A'}, {'na...
# pede uma temperatura em farenheit em seguida converte para celsius. graus = float(input('Informe a temperatura em °F: ')) convert = (5 * (graus-32) / 9) print(f'A temperatura de {graus:.2f}°F é correspondente a {convert:.2f}°C')
class People: def __init__(self, name, age): self.name = name self.age = age self.classname = self.__class__.__name__ def speak(self): print(f'{self.classname} talking...') class Customer(People): def buy(self): print(f'{self.classname} buying...') def speak(self): print('CUSTOMER') class Customer...
""" List comprehension """ # l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] # eg1 = [variable for variable in l1] # eg2 = [v * 2 for v in l1] # eg3 = [(v, v2) for v in l1 for v2 in range(3)] # l2 = ['misa', 'yui', 'asuna'] # eg4 = [v.replace('a', '@') for v in l2] # tuple_ = ( # ('key1', 'value1'), # ('key2', 'value2'), # )...
while True: try: n1 = int(input('Type a number: ')) n2 = int(input('Type a number: ')) print() except Exception as e: print('Type a valid number, please') print(f'error: {e}') print() continue operator = input('Type a operator: ') print() if...
# Os números primos possuem várias aplicações dentro da Computação, por exemplo na Criptografia. # Um número primo é aquele que é divisível apenas por um e por ele mesmo. Faça um programa que # peça um número inteiro e determine se ele é ou não um número primo. n = 0 num = int(input('Digite um número: ')) for x in ra...
vetor = [] consoantes = [] stop = tot = 0 while stop < 10: caracteres = str(input('Digite um caractere: ')) if caracteres not in 'AEIOUaeiou': tot += 1 consoantes.append(caracteres) vetor.append(caracteres) stop += 1 print(f'Vetor caracters: {vetor}') print(f'Consoantes: {tot}') print(...
vetor = [[],[]] stop = 0 while stop < 20: num = int(input('Digite um número: ')) vetor.append(num) stop += 1 for x in vetor: if isinstance(x, float) or isinstance(x, int): if x % 2 == 0: vetor[0].append(x) else: vetor[1].append(x) print(f'VETOR: {vetor}') print...
# A série de Fibonacci é formada pela seqüência 1,1,2,3,5,8,13,21,34,55,... # Faça um programa capaz de gerar a série até o n−ésimo termo. # def fibonacci(num): # if num <= 1: # return num # else: # return fibonacci(num - 1 ) + fibonacci(num - 2) # x = int(input('Digite um número: ')) # res =...
import csv with open("customers.csv", "r") as file: # data = csv.reader(file) data = [x for x in csv.DictReader(file)] with open("customers2.csv", "w") as file: wrt = csv.writer( file, delimiter=",", quotechar='"', quoting="csv.QUOTE_ALL", ) for d in data: ...
from time import time from time import sleep def speed(func): def inner(*args, **kwargs): start_time = time() result = func(*args, **kwargs) end_time = time() time_ = (end_time - start_time) * 1000 print(f'\nThe function {func.__name__} took {time_:.2f}ms to execute') ...
'''Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tin...
''' Até 5 Kg Acima de 5 Kg File Duplo R$ 4,90 por Kg R$ 5,80 por Kg Alcatra R$ 5,90 por Kg R$ 6,80 por Kg Picanha R$ 6,90 por Kg R$ 7,80 por Kg''' '''Para atender a todos os clientes, cada cliente poderá levar apenas um dos tipos de carn...
class Cart: def __init__(self): self.products = [] def insert_product(self, product): self.products.append(product) def show_products(self): for product in self.products: print(product.name, product.value) def sum_total(self): total = 0 for product ...
# le um nome de usuario e senha, se a senha for igual user printa error while True: user = input('User: ') password = input('Password: ') if password != user: break else: print('Error password and user is the same')
""" count - itertools """ from itertools import count my_count = count() names = ['misa', 'yui', 'asuna'] names = list(zip(my_count, names)) print(names) # my_count = count(start=5, step=0.1) # my_count = count(start=9, step=-1) # for value in my_count: # print(round(value, 2)) # if value >= 10 or value <=...
# pede dois números inteiros e um número real em seguida calcula # A - o produto do dobro do primeiro com metade do segundo . # B - a soma do triplo do primeiro com o terceiro. # c - o terceiro elevado ao cubo. n1 = int(input('Digite um número inteiro: ')) n2 = int(input('Digite outro número inteiro: ')) n3 = flo...
# pergunta o quanto ganha por hora e quantos horas trabalhadas durante o mês # A salário bruto. # B quanto pagou ao INSS. # C quanto pagou ao sindicato. # D o salário líquido. dinheiro_hora = float(input('Quanto ganha por hora? R$')) horas_mes = int(input('Quantas horas trabalha por mês? ')) salário_bruto = di...
# converte metros para centimetros n = float(input('Informe a medida: ')) km = n*0.001 hm = n*0.01 dm = n*10 cm = n*100 mm = n*1000 dam = n*0.1 print(f'''A medida de {n}m corresponde a {km}→KM {hm}→ HM {dam}→DAM {dm}→DM {cm}→CM {mm}→MM ''')
from database import * valid_commands = [ 'help', 'exit', 'reload', 'population', 'density', 'timezone', 'capital', 'city', 'state' ] # In order to properly handle city and state names that contain more than one word, # like "New York" and "Little Rock", we cannot simply divide th...
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split # 使用scikit-learn库的LinearRegression方法 def linear_aggression(): data = np.loadtxt("Advertising.csv", delimiter=',') x_data = data[:, 1:4] y_data = data[:, ...
import fileinput def checktree(preorder, inorder, postorder, length): # if the array lengths are 0, then all of them are obviously equal if length == 0: return 1 # if array lengths are 1, then check if all of them are equal if length == 1: return (preorder[0] == inorder[0] == postorder...
import fileinput from collections import defaultdict class Graph: def __init__(self, V): self.V = V self.graph = defaultdict(list) def addEdge(self, v, w): # Add w to v ist. self.graph[v].append(w) # Add v to w list. self.graph[w].append(v) # A recursive f...
# K-NEAREST NEIGHBORS(KNN) ON IRIS DATASET #IMPORTING THE LIBRARIES from sklearn import datasets import numpy as np #IMPORTING IRIS DATASET iris=datasets.load_iris() print(iris.data) print(iris.target) # SPLITTING DATA INTO TEST AND TRAIN from sklearn.model_selection import train_test_split x_train, x_t...
"""CPU functionality.""" import sys LDI = 0b10000010 PRN = 0b01000111 HLT = 0b00000001 class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.ram = [0] * 256 self.registers = [0] * 8 # R0-R7 self.pc = 0 # Program Counter, address of the currently...
# Item 3: Know the difference between bytes, str, and unicode import os # In Python 3, there are two types that represent sequences of characters: # bytes and str. Instances of bytes contain raw 8-bit values. Instances of # str contain Unicode characters. # In Python 2, there two types that represent sequences of cha...
def fibo(a0,a1,n): i = 2 x0 = a0 x1 = a1 x2 = None print(x1) while i <= n: x2 = x0 + x1 x0 = x1 x1 = x2 i = i + 1 print(x2) return x2 x2 = fibo(0,1,10)
#!/usr/bin/python3 """ print database with filters """ import MySQLdb from sys import argv if __name__ == '__main__': db = MySQLdb.connect(user=argv[1], passwd=argv[2], db=argv[3]) name = argv[4] cur = db.cursor() cur.execute("SELECT cities.name FROM cities\ INNER JOIN states\ ON cities.stat...
#!/usr/bin/python3 """ append write """ def append_write(filename="", text=""): '''append a string to new file''' with open(filename, mode="a", encoding="utf-8") as myFile: myFile.write(text) return len(text)
#!/usr/bin/python3 if __name__ == "__main__": import sys leng = len(sys.argv) strn = "argument" num = 0 if leng != 2: strn += "s" if leng > 0 and leng != 1: print("{} {}:".format(leng - 1, strn)) for i in sys.argv[1:]: print("{}: {}".format(num + 1, i)) ...
# Задание_1 # Задан массив из 10 чисел. Напишите программу, которая выводит их сумму. # 1) Входные данные: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Выходные данные: 45 # 2) Входные данные: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1. Выходные данные: 10 # 3) Входные данные: 8, 4, 5, 3, 9, 2, 3, 4, 5, 1. Выходные данные: 44 """ a = input().spli...
"""Distance Calculations""" from os import listdir def sizeDistance(file1, file2): """Distance calc based on document size""" return abs(len(file1) - len(file2)) def hammingDistance(file1, file2): """Hamming Distance""" count = 0 for i in range(min(len(file1), len(file2))): if file1[i] != f...
############## # Atividade Newton ############## #Valores e produto produto=['salgado','refri','suco','sorvete','cafe','capp','bolo','dad'] preco=[4.00,4.50,5.00,6.00,4.00,6.00,4.50,0.50] #exercicio um def cardapio(): print ("1- SALGADO") print ("2-refri") print ("3-suco") print ("4-sor...
#len() '''a=[1,2,3,4,5,67,8,9] print(len(a))''' #min() '''a=[2,34,5,6,7,8,0,2,3,4] print(min(a)) ''' #max() '''a=[2,34,5,6,7,8,0,2,3,4] print(max(a))''' #sorted() '''a=[2,34,5,6,7,8,0,2,3,4] print(sorted(a))''' #sum() '''a=[2,34,5,6,7,8,0,2,3,4] print(sum(a)) ''' #type() '''a={2,34,5,6,7,8,0,2...