text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Sun Jul 12 00:09:36 2020 @author: jayada1 """ def find_order(words): cols = max([len(w) for w in words]) rows = len(words) matrix = list() for word in words: word_col = list(word) word_col.extend([None]*(cols-len(word))) matr...
# -*- coding: utf-8 -*- """ Created on Sun Aug 18 13:06:57 2019 @author: jayada1 create heap from an unsorted array """ class BinaryHeap(): def __init__(self): self.heap = [] def insert(self, val): i = self.size() self.heap.append(val) while i != 0: ...
""" Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was pr...
from collections import Counter candidates = [2,3,6,7] target = 7 Counter def find_combination(nums, target, path, res): if target < 0: return if target == 0: res.append(path) return for i in range(len(nums)): find_combination(nums[i:], target-nums[i], path+[nums[i]], res)...
# -*- coding: utf-8 -*- """ Created on Sun Mar 3 11:34:10 2019 @author: jayada1 """ arr = [1,2,3,4,5,6,7] d = 2 n = 7 def rotate(arr, d, n): new_arr = arr[d:] new_arr.extend(arr[0:d]) return new_arr print(rotate(arr, d, n)) """ num = 123 output : 231, 312 num = 1445 output:...
# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ def remove_duplicates_str(s): stack = [] for c in s: if stack and stack[-1] == c: stack.pop() else: stack.append(c) return "".join(stack) # print(remove_duplicates_str("abbaca")) # print(rem...
# https://leetcode.com/discuss/interview-question/364618/ def count_min_steps_equalize(arr): arr.sort(reverse=True) # O(nlogn) steps = 0 n = len(arr) i = 0 while i in range(n-1): # O(n) if arr[i] > arr[i+1]: # for k in range(0,i+1): # O(n) # arr[k] = arr[i+1] ...
envelopes = [[5, 4], [6, 4], [6, 7], [2, 3]] def merge_sorted_arrays(left, right, m, n): sorted_array = [] i = 0 j = 0 while i < m and j < n: if left[i] <= right[j]: sorted_array.append(left[i]) i += 1 else: sorted_array.append(right[j]) ...
def sort_array_recursive(arr, sorted_array): if not arr: return sorted_array min_num = arr[0] min_idx = 0 for i, n in enumerate(arr): if n < min_num: min_num = n min_idx = i sorted_array.append(min_num) return sort_array_recursive(arr[:min_idx] + arr[min_i...
# original = [5, 2, 4, 3, 1, 6] #works # original = [1,2,3,4] #works # original = [3, 6, 4, 2, 1] #works original = [4,3,2,1] temp_stack = [] sorted_stack = [] while original: if not sorted_stack: sorted_stack.append(original.pop()) while sorted_stack: if original[-1] > sorted_stack[-1]: ...
def solve(arr, start, n, k): if n == 1: return arr[0] start = (start + k) % n if arr: arr.pop(start) print(arr) return solve(arr, start, n - 1, k) # n = 7 # k = 3 # n = 5 k = 2 def main(n, k): arr = [i for i in range(1, n + 1)] print(solve(arr, 0, n, k)) # main(n, k) ...
# n = 3 # # # def solve(n, output, stack): # if n == 0: # if not stack: # output = output + '()' # else: # while stack: # output = output + ')' # stack.pop() # print(output) # elif n >= 1: # solve(n - 1, output + ")", stack)...
# https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/ def is_palindrome(word): return word == word[::-1] def longest_palindrome(words): palindromes = [] for word in words: if is_palindrome(word): palindromes.append(word) elif word[::-1] in words...
import re def snack_checker(choice, options): for var_list in options: if choice in var_list: chosen = var_list[0].title() is_valid = "yes" break else: is_valid = "no" if is_valid == "yes": return chosen else: return "inva...
class myclass: #__a,__b=0,0; __var1 = 99; def __init__(self): self.a = 10; self.b = 20; print("instantiating"); #swaps a number without using a temporary variables... def swap_values(self): temp = 99; print ("temp is 20", 20); print("before swaping",self.a,self.b...
# bike OOP class Bike(object): def __init__(self, name, price, max_speed, miles=0): self.name = name self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print "\n{}".format(self.name) print "Price: {} dollars".format(self.price) print "Maximum Speed: {} mph".format(s...
# bike OOP class Bike(object): def __init__(self, name, price, max_speed, miles=0): self.name = name self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print "\n{}".format(self.name) print "Price: {} dollars".format(self.price) print "Maximum Speed: {} mph".format(s...
reais = float(input('quanto dinheiro tem na carteira: ')) dol = 3.27 cambio = reais/dol print(f'voce pode comprar {cambio:.2f} dólares')
import random, time print('=-'*50) print('Vou pensar em um numero entre 0 e 5. Tente adivinhar...') print('=-'*50) x = random.randrange(0, 5, 1) y = int(input('Em qual numero eu pensei? ')) print('PROCESSANDO...') time.sleep(1) if x == y: print('PARABENS!! Você conseguiu me vencer.') else: print(...
import datetime contmaior = 0 contmenor = 0 hoje = datetime.date.today().year for c in range(1, 8, 1): n = int(input(f'ano de nascimento da {c}ª pessoa: ')) idade = hoje - n if idade >= 18: contmaior += 1 else: contmenor += 1 print(f'{contmaior} pessoas maiores de 18\n' ...
print('GERADOR DE PA') print('=-'*20) termo = int(input('digite o primeiro termo ')) razao = int(input('digite a razao ')) cont = 1 while cont <= 10: print(f'{termo} - ', end='') termo += razao cont += 1 print('FIM')
n1 = int(input('digite um numero: ')) n2 = int(input('digite outro numero: ')) if n1 > n2: print(f'o primeiro nr é maior: {n1}') elif n2 > n1: print(f'o segundo nr é maior: {n2}') else: print(f'os dois são iguais {n1} e {n2}')
n = 0 cont = 0 soma = 0 while n != 999: soma += n n = int(input('digite um nr (999 para parar): ')) if n == 999: break cont += 1 print(f'a soma dos {cont} valores é {soma}')
celcius = float(input('digite a temperatura em celcius: ')) fahren = ((9*celcius)/5)+32 print (f'a temperatura de {celcius} celcius é de {fahren} FH')
# IMPORTAÇÕES # FUNÇÕES def multa(velocidade): if velocidade > 80: print(f'VOCE FOI MULTADO! o limite é de 80 km/h\n' f'Voce excedeu o limite em {(velocidade-80):.2f} km/h\n' f'Valor da multa R$ {((velocidade - 80)*7):.2f}') else: print('velocidade dentr...
frase = str(input('digite a frase ')).strip().upper() palavras = frase.split() junto = ''.join(palavras) inverso = '' for c in range(len(junto)-1, -1, -1): inverso += junto[c] if junto == inverso: print(f'{junto} é palindromo \n' f'{junto} = {inverso}') else: print(f'{junto} não é pali...
matriz = [[], [], []] num = 0 for l in range(0, 3): for c in range(0, 3): num = int(input(f'digite a posição {[l, c]}: ')) matriz[l].append(num) for l in range(0, 3): for c in range(0, 3): print(f'[{(matriz[l][c]):^3}]', end='') print()
with open("input.txt") as f: buses_str = [x for x in f.readline().strip().split(",")] buses = [] for (index, bus) in enumerate(buses_str): if bus != "x": bus = int(bus) buses.append((bus, (bus - index) % bus)) buses = sorted(buses, key=lambda x: -x[0]) def closest_divisable(number, divident)...
active = set() with open("input.txt") as f: for (row, line) in enumerate(f): line = line.strip() for (col, point) in enumerate(line): if point == "#": active.add((row, col, 0, 0)) def iterate_neighbors(pos): x, y, z, w = pos for x1 in range(-1, 2): for y...
from collections import defaultdict tile_commands = [] def iterate_commands(path): index = 0 while index < len(path): c = path[index] if c in ("n", "s"): yield path[index:index+2] index += 2 else: yield path[index:index+1] index += 1 w...
from abc import abstractmethod, ABC class Band(): members = [] bands = [] def __init__(self,name): self.name=name Band.bands.append(self) def add_members(self,mname): self.mname=mname Band.members.append(mname) def play_solos(self): result ='' ...
import random from hangman.lives import LIVES with open('hangman/words.txt') as f: lines = f.read().splitlines() action_list = [] first_time = True word = "" letters = [] hearts = 10 used_letters = [] def random_word(): return lines[random.randint(0, len(lines))].lower() def display_...
x=10 #int y=10.5 # float print(type(x)) print(type(y)) #Type Conversion print(x) #10 print(float(x)) #10.0 #convert int to float print(type(float(x))) y=10.0 print(y) print(type(y)) print(int(y)) #convert float to int large=max(10,2,3) small=min(11,41,6,7,3,4) print("max number : ",large) print("min number ...
#swapping x=10 y=5 print("Before swapping : ",x,y) x,y=y,x print("After swapping : ",x,y)
#Type Casting num1=int(input("Enter First Number:")) #10 num2=float(input("Enter Second Number:")) #10.5 print(num1+num2) #20.5 num1=input("Enter First Number:") #10 num2=input("Enter Second Number:") #10.5 print(int(num1)+float(num2)) #20.5 num1=input("Enter First Number:") #10.5 num2=input("Enter Second Number:"...
#Number - int , float x=100 #int type y=100.5 #float type s='welcome' #string/char type a=True # Boolean Type # to Know the type of variable print(type(x)) print(type(y)) print(type(s)) print(type(a))
# Python list '''list1=[10,11,12,13,14,15] list2=list1 print(list2) list1[0]='apple' print(list1)''' # Range function for x in range(1,11): print(x)
from datetime import datetime import pandas as pd import settings from receipt_roll import money, common import numpy as np import matplotlib.pyplot as plot import seaborn as sn def terms_for_index(): """ Basic structure for holding data with terms as the index. """ return {'Michaelmas': [], 'Hilary': [], 'E...
from typing import List, Tuple SeatingPlan = List[List[int]] def solve(): seating_plan = get_seating_plan('input.txt') settled_seating_plan = get_settled_seating_plan(seating_plan) occupied_seats = count_occupied_seats(settled_seating_plan) print(occupied_seats) def get_seating_plan(input_file: st...
from queue import deque def solve(): player_1, player_2 = parse_input('input.txt') while player_1 and player_2: run_round(player_1, player_2) winner = player_1 or player_2 score = calculate_score(winner) print(score) def parse_input(input_file): players = {} player...
import re def solve(): all_entries = {} valid_entries = 0 with open('input.txt') as f: for line in f.readlines(): if line.strip() == "": if len(all_entries) > 7 or len(all_entries) == 7 and "cid" not in all_entries: if all_keys_valid(all_entries): ...
import numpy as np def rot_n(string: str, n: int) -> str: ord_list = [ord(c) for c in string] translated_list = [] for c in ord_list: # ord('A') == 65, ord('Z') == 90 # ord('a') == 97, ord('z') == 122 if c >= 65 and c <= 90: c -= 65 c = (c - n + 26) % 26 ...
#Leer tres numeros entereos de un digito y almacenarlos en una sola variable #Que contenga a esos tres digitos por ejemplo si A=5 y B=6 y C=2 entomces X=562 print("Bienvedido al Programa".center(50,"-")) a = "" b = "" c = "" x = "" a = input("Ingrese primer numero: ") b = input("Ingrese segundo numero: ") c = input...
#Calcula el preio de unboleto de viaje, tomando en cuenta el numero de kilometros #que se van a ecorrer, siend el precio BS/.10,50 por km. print("bienvenidos al programa".center(50,"-")) Precio_km = 10.50 kms = 0 total = 0 kms = float(input("Ingrese kilometros a recorrer:.")) total = Precio_km * kms print("Precio ...
#Ejercicio4 #realizar el promedio de n notas utilizando el for print ("BIENVENIDO") suma = 0 valor = int(input("Ingresar su nota") for i in range (valor): nota = int(input("ingrese su nota")) suma = suma + int(nota) promedio = suma / nota print ("El promedio es :. {}".format (promedio))
""" Real-time stream of audio from your microphone ============================================== This is an example of using your own Microphone to continuously transcribe what is being uttered, **while it is being uttered**. Whenever the recognizer detects a silence in the audio stream from your microphone, the gene...
""" Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). Example : Given binary tree 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] """ class Solution: # @param A : root node of tree ...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import random import numpy as np from numpy.random import randint from matplotlib import pyplot as plt #Question 1 plt.figure(1) x_coord = [1,2,3,4] y_coord = [1,2,3,4] plt.plot(x_coord, y_coord, marker = '', linestyle...
import sqlite3 ''' This file contains necessary functions for modifying and querying the sqlite3 'professors' database. ''' ###################################################### ## FUNCTIONS FOR PROFS TABLE ## ###################################################### def insert(samID, firstName, la...
from Common.state import State, Game_Phase from Common.player import Player from copy import deepcopy """ Data representation for a game tree representing the tree of all possible states from a starting state. Each node in the game tree contains a State, a list indicating the order of the players, a reference to ...
import unittest import sys sys.path.insert(1, '../../') from Common.board import Board # from Common.utils import parse_json class TestBoard(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) """ Tests that make_board_from_tiles properly co...
import data import pickle class Nearest(object): """ ========================================================= It's a very important module that can determine performance and correctness of this algorithm. CURRENT STRATEGY : To find nearest user, we look at users set's intersection, and we only calculate e...
name = 'Ali' if name == 'Alice': print('Hi Alice.') else: print(name)
import numpy as np # Some vector calculus functions def unit_vector(a): """ Vector function: Given a vector a, return the unit vector """ return a / np.linalg.norm(a) def d_unit_vector(a, ndim=3): term1 = np.eye(ndim)/np.linalg.norm(a) term2 = np.outer(a, a)/(np.linalg.norm(a)**3) answe...
from Tkinter import * top=Tk() main_frame=Frame(top) main_frame.pack() top_frame=Frame(top) top_frame.pack(side=TOP) c=Canvas(main_frame, bg="blue",height=300,width=200) x=0 def printButton(): print("button\n") def drawCircle(x):#probably could get more desired behavior using actual classes c.create_polygon(x+10,x+10...
from tkinter import * def setUpCanvas(root): root.title("Wolfram's cellular automata: A Tk/Python Graphics Program") canvas = Canvas(root, width = 1270, height = 780, bg = 'black') canvas.pack(expand = YES, fill = BOTH) return canvas def printList(rule): #1. print title canvas.create_text(170, 20, text = "Ru...
# Send one player around the board for a specified number of turns. import matplotlib.pyplot as pyplot # For drawing bar chart. import numpy as np import sys # For parsing parms. import game # Convert the parm list of numbers to a list...
i=1 sum=0 n=int(input("enter the number")) while(i<=n): sum=sum+i i=i+1 print(sum)
mytuple=("ram",343,"regal",3,45,"jalal",7.9) print(mytuple) print(mytuple[2]) print(mytuple*2) print(mytuple[1:3]) second=("yui",9999,"ddd",99) print(mytuple+second)
def pallindrome(x): g=x rev=0 while(x!=0): s=x%10 rev=rev*10+s x=x//10 if (g==rev): return"pallindrome number" else: return"not a pallindrome nujmber" n=int(input("enter the number")) result=pallindrome(n) print(result)
from datetime import datetime from typing import Union class Parser: @staticmethod def parse_data(date: str, formats: list) -> Union[datetime, None]: """Parse string with given formats :param date: (str) - string with date :param formats: (list) - all possible formats, that date may l...
#Exercise 177: Roman Numerals '''(25 Lines) As the name implies, Roman numerals were developed in ancient Rome. Even after the Roman empire fell, its numerals continued to be widely used in Europe until the late middle ages, and its numerals are still used in limited circumstances today. Roman numerals are constructed ...
""" Q U E U E S I N P Y T H O N """ """ - Using the FIFO approach, three names will be added into a queue. - Then an element is removed using this approach. - Think of a queue outside a retail store, the first one to arrive is Marc. When able to enter, Marc leaves the queue first. """ from collections import dequ...
import itertools def get_data(): with open("data/data_09.txt") as data_file: data_string = data_file.read() data_array = data_string.split("\n") data_array = list(map(lambda x: int(x), data_array)) return data_array def fetch_preamble(start, length): with open("data/data_09.txt") as f: ...
class LL: def __init__(self, data): self.data = data self.next = None def insrt_or_append(self, data, pos = None): if pos != None: c = 1 while c != pos-1: c+=1 self = self.next r = self.next f = LL(data...
def primeNative(n): if n < 2: return False for x in range(2, n): if (n % x) == 0: return False return True print(primeNative(15))
from trie import * # Create the tree mytrie = Trie() # Get the input ready s = "The quick brown fox jumps over the lazy dog" toks = s.strip().split() for tok in toks: # Insert key:value {word: meaning} in to tree mytrie.addWord(mytrie.rootNode, tok, "blabla") # If search is successful, you will get meani...
"""# Exercise: GCDRecr # Write a Python function, gcdRecur(a, b), that takes in two numbers and returns the GCD(a,b) of given a and b. # This function takes in two numbers and returns one number.""" def gcd_recursion(a_val, b_val): '''a, b: positive integers returns: a positive integer, the greatest common ...
"""#Guess My Number Exercise""" LOW_NUM = 0 HIGH_NUM = 100 print("Please think of a number between 0 and 100!") print("Enter 'y' if guess done, or 'h' if that (number > your guess ) else 'l' ") USER_GUESS = 'LOW_NUM' while USER_GUESS != 'y': print("Is your secret number ", int((LOW_NUM+HIGH_NUM)//2), "?") USER_...
from numpy import exp, array, random, dot class neural_network: def __init__(self): random.seed(1) # We model a single neuron, with 3 inputs and 1 output and assign random weight. self.weights = 2 * random.random((3, 1)) - 1 def __sigmoid(self, x): return 1 / (1 + exp(-...
"""Constants related to visualization methods.""" from typing import Tuple, Union LEN_RGB = 3 # number of elements in an RGB color LEN_RGBA = 4 # number of elements in an RGBA color RGB = Tuple[(float,) * LEN_RGB] # typing of an RGB color RGBA = Tuple[(float,) * LEN_RGBA] # typing of an RGBA color RGB_RGBA = Unio...
from functools import reduce """ A small expressions language, with variables and assignment as a result we have 3 additions to the AST nodes menagerie * Expressions to build a program block * Assignment to store a result in a variable name * Variable to reference a variable (use latest stored value) """ # https://d...
# https: // leetcode.com/problems/reverse-words-in-a-string-iii/ # Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. def reverseWords(s): new_words = [] split = s.split() for word in split: new_word...
def addNum(seq, num): seq = list(seq) for i in range(len(seq)): seq[i] += num return seq origin = (3, 6, 2, 6) changed = addNum(origin, 3) print(origin) print(changed) l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)] print([t[:-1] + (100,) for t in l]) a = {0...
"""This file contains all the classes you must complete for this project. You can use the test cases in agent_test.py to help during development, and augment the test suite with your own test cases to further test your code. You must test your agent's strength against a set of agents with known relative strength usin...
""" * Sample input: * * 1 * / \ * 3 5 * / / \ * 2 4 7 * / \ \ * 9 6 8 * * Expected output: * 1 * 3 5 * 2 4 7 * 9 6 8 """ class TreeNode: def __init__(self,data): self.data = data self.left = None sel...
nomes = ('Ana','Bia','Gui','Ana') #Identificar tipo da classe e valor booleano print(type(nomes)) print('Bia' in nomes) #Formas de pesquisas nas listas print(nomes[2]) print(nomes[0:2]) print(nomes[1:-1]) print(nomes)
lista = ["abacate","bola","cachorro"] for i in range(len(lista)): # RENGE cria um vetor e LEN mede o tamanho da lista print(i, lista[i]) #Enumerate: lista = ["abacate","bola","cachorro"] for i, nome in enumerate(lista): # Melhor forma de se fazer print(i, nome)
a = "Brasil" b = "China" concatenar = a + " " + b + "\n" #"\n" pula uma linha, para remover tem que usar print(concatenar.STRIP()). print(concatenar) print(concatenar.lower()) #Método para deixar os caracteres em minúsculo sem alterar a variável print(concatenar.upper()) #Método para deixar os caracteres ...
import random # Sorteia um numero aleatorio de 0 a 10 numero = random.randint(0,10) print(numero) # Sorteia um numero pré definido random.seed(1) numero = random.randint(0,10) print(numero) # Sorteia um numero da lista aleatoriamente (esse comando só funciona sozinho) lista = [6,45,9,66] numero = random...
#### To group records based on a field #### #### The records are stored in a list of dictionaries #### #### Using itertools.groupy() #### from itertools import groupby from operator import itemgetter rows = [ {'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '5148 N CLARK', 'date': '07/04/2012'...
#### to perform useful calculations on dictionary contents, it is often useful to convert the keys and values of the dictionary using zip() #### #### zip() creates an iterator, which can only be consumed once #### numbers = { 'Bryrant': 24, 'Gasol': 16, 'Bynum': 17, 'Odom': 7, 'Fisher': 2 } # find...
#!/usr/bin/env python from __future__ import print_function, unicode_literals ''' 1. Create a directory called mytest. In ./mytest create three Python modules world.py, simple.py, whatever.py. a. These three files should each have a function that prints a statement when called (func1, func2, func3). ...
#Dado n, inteiro maior que zero imprimir tabela com os valores de x * y para x e y = 1, 2, ..., n. #Imprimir apenas o triângulo inferior def main (): # ler n inteiro >= 0 n = int(input("Entre com o valor de n inteiro > a zero: ")) #imprimir o cabeçalho print (" ", end = '') for i in range (1,...
# Calcular o valor da função x^3 + x^2+ x + 1 para x = 1, -1, 2, -2, 3, -3 def main (): for k in [1,-1,2,-2,3,-3]: print ("O valor de x quando vale %d é =" %k, k*k*k + k*k + k + 1) main ()
# Função maior(x,y) que calcula e devolve o maior entre dois valores. def maior(x, y): if x > y: return x return y print (maior (3,5))
# Dado N > 0 e uma sequência de N números, determinar o maior elemento da sequência. def main(): # ler a quantidade de números N N = int(input("Digite a quantidade de números da sequência: ")) # Consistência dos dados de entrada if N == 0: print("A sequência possui zero elementos") else: ...
# Dado N > 0, inteiro, calcular a soma N + N/2 + N/4 + ... + 1 # solução abaixo considera a divisão inteira. Por exemplo, para N = 15 (15 + 7 + 3 + 1), para N = 10 # (10 + 5 + 2 + 1). def main(): N = int(input("Entre com N > 0 e inteiro:")) soma = 0 while N > 0: soma = soma + N N = N // ...
#Dada uma sequência de números terminada por zero, determinar o menor elemento da sequência. def main(): #lê o primeiro elemento x = float(input("Digite o primeiro elemento da sequência: ")) #consistência dos dados if x == 0: print("Esta sequência possui apenas o número zero como elemento.") ...
# Função simetrica(a, n) que verifica se a matriz a de n linhas e n colunas é uma matriz simétrica, # isto é, se a[i][j] é igual a a[j][i], devolvendo True (sim) ou False (não). percorrendo apenas o triângulo inferior a = [[2,4,4], [4,6,6], [4,6,9]] def simetrica(a,n): for i in range(n): print("i = ", i)...
# Dados 2 números imprimi-los em ordem crescente. # Considere ordem crescente quando o primeiro é menor ou igual ao segundo. a = int(input("Digite o primeiro número: ")) b = int(input("Digite o segundo número: ")) if a>b: print(b,a) elif b>a: print(a,b) else: print("Os números são iguais")
#Função verifica_linhas(a, n) que verifica se a matriz a n x n, possui 2 linhas iguais, devolvendo True ou False. a = [[1,1,0,1], [1,2,0,1],[3,3,0,0], [3,3,0,0]] def verifica_linhas(a): for j in range (len(a)): if a[j] not in a[j+1:]: linhas_iguais = False else: linhas_igu...
#Dado N > 0 e uma sequência de N números, determinar o menor elemento da sequência. def main(): #ler o número de elementos da sequência N = int(input("Digite a quantidade de números da sequência: ")) #consistência dos dados de entrada de N if N == 0: print ("O número de elementos da sequência ...
#dado n > 1, inteiro, verificar se n é primo #não precisa testar para todos os possíveis divisores de 1 em 1. Basta testar para 2 e depois só os ímpares def main (): #leia n n = int(input("Type a number you'd like to check if is prime or not: ")) div = 2 cont = 3 if n % 2 == 0: print (n,...
# Dado um valor em reais V (com duas casas decimais, os centavos), determinar a quantidade máxima de # notas de 100, 50, 20, 10, 5 2 e 1, moedas de 0,50, 0,25, 0,10, 0,05 e 0,01 necessárias para compor V. def main (): V = float(input("Digite o total em R$ com até duas casas decimais: ")) x = int(V * 100) ...
#Escreva a função void LCZero(mat) que devolve uma dupla de listas. # A primeira com todas as linhas zeradas e a segunda com todas as colunas zeradas da matriz mat. # Exemplo – se mat for a matriz abaixo, devolve: ([2, 3, 5], [0, 4]) mat =[[0,2,0,6], [0,3,5,0], [0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]] def LCZero(...
''' Dados a e b float (a < b), n e k inteiros e maiores que 0, uma sequência de n valores float no intervalor [a, b), ou seja maiores ou iguais a a e menores que b. Dividir o intervalo [a, b) em k subintervalos iguais e determinar quantos estão em cada intervalo. Note que serão k contadores e o tamanho do intervalor é...
# Dado N, simule a jogada de um dado (faces 1 a 6) N vezes e calcule quantas vezes cada face ocorreu import random def main (): n = int(input("Digite o valor de n: ")) a = 1 soma_1 = 0 soma_2 = 0 soma_3 = 0 soma_4 = 0 soma_5 = 0 soma_6 = 0 while a <= n: k = random.randr...
'''Dado um valor inteiro em reais (R$), determinar quantas notas de R$100, R$50, R$20, R$10, R$5, R$2 e R$1 são necessárias para compor esse valor. A solução procurada é aquela com o máximo de notas de cada tipo.''' N = int(input("Digite o valor total em R$: ")) total_100 = N // 100 total_50 = N % 100 // 50 total_2...
#Função procura_elemento(a, x), que procura elemento igual a x na lista a, # devolvendo como o índice do primeiro elemento que é igual a x ou -1 caso não encontre. # É quase a mesma coisa que a função index(x) já usada anteriormente. Assim, suponha que não exista a index(x) a = [0,0,0,0,1,1,1,1,2,2,2] def procura_ele...