text
stringlengths
37
1.41M
s = input('Введите имя и фамилию') while len(s) < 1 or len(s) > 1000: print('Попробуйте еще раз!') s = input('Введите имя и фамилию') print (s.title())
from math import sqrt class Complex(object): def __init__(self, a): self.real = float(a[0]) self.imag = float(a[1]) def __str__(self): if self.imag >= 0: return "{:.2f}+{:.2f}i".format(self.real, self.imag) return "{:.2f}{:.2f}i".format(self.real, self.imag) ...
from random import randrange def sortalg(items): size = len(items) for i in range(0, size - 1): a = items[i] for j in range(i, size): b = items[j] if b > a: items[i], items[j] = b, a a, b = b, a def sortest(items): print 'Start:', items sortalg(items) print 'End:', items if __name__ == '__main...
black_list = ['Susan' , 'Robert' , 'Raj' ,'Shaheb' , 'Murtaza']; student_list = list(input() for _ in range(int(input()))); print(student_list); while '' in student_list: a = student_list.index(''); print(a); print(f'please fill in the empty name:' ,end =' '); student_list[a] = input(); print(student_list); ...
import pandas as pd import numpy as np res = map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]) print(list(range(1, 12))) df = pd.DataFrame(np.arange(1, 10)) df['a'] = 1 df['b'] = 3 # df.pop('a') print(df) for x in range(1,3): print(x)
def combi(n,r): if r == n: return 1 elif r == 1: return n else: return combi(n,r-1)*(n-r+1)//r if __name__ == "__main__": n = 1 while n <= 5: r = 1 while r <= n: print(" {0} C {1} = {2} ".format(n,r,combi(n,r)), end="") r = r + 1 ...
def solve(n): ans = 0 i = 1 while i <= n: if n % i == 0: ans = ans + i i = i + 1 return ans if __name__ == "__main__": n = int(input("입력 : ")) print("약수의합 : {0}".format(solve(n)))
#!/usr/bin/python if __name__ == '__main__': sum = 0 for i in range(101): sum += i print("1부터 100까지의 합 : {}".format(sum))
def solve(n): i = 1 while i <= n: if i % 3 == 0: print(" X ", end="") else: print(" {0} ".format(i), end="") i = i + 1 if __name__ == "__main__": solve(30)
import numpy as np def msd(x, y, z): """Calculate the mean-squared displacement of a particle. To improve statistics, this routine calculates multiple displacements from a single trajectory and averages the results. A trajectory with N time steps has N-1 single-step displacements, (N-1)/2 two-step dis...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 18 09:07:34 2019 @author: tanvirkaur """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Time complexity = O(n) # Space complexity =...
var2 = 5 var = 2 print(var + var2) # Defining functions def greeting(name, department): print("Welcome " + name) print("You are part of " + department) greeting("Ana", "Front-End Development") # Return values def area_triangle(base, height): return base * height / 2 area_a = area_triangle(5, 4) a...
class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.key = [] self.value = [] self.size = 0 self.max_size = capacity def get(self, key): """ :type key: int :rtype: int """ try: ...
SIGNS = ( ("Водолей", 20), ("Риби", 19), ("Овен", 21), ("Телец", 21), ("Близнаци", 21), ("Рак", 21), ("Лъв", 22), ("Дева", 23), ("Везни", 23), ("Скорпион", 23), ("Стрелец", 22), ("Козирог", 22) ) def what_is_my_sign(day, month): sign_index = month ...
#!/usr/bin/env python3 j_count_speaking = 0 j_count = 0 with open("romeo.txt") as play: lines = play.readlines() for name in lines: if "JULIET" == name.strip(): j_count_speaking += 1 # j_count_speaking = j_count_speaking + 1 if "juliet" in name.lower(): j_count += 1 p...
#!/usr/bin/env python print("Hello") p = input("prompt here") v = range(8) for num in v: print(num)
a_list = [] a_list.append(1) a_list.append('a string') a_list.append(True) print(a_list) for element in a_list: print(type(element)) a_list.insert(1, 'inserted') print(a_list) a_list.extend(['another', 'list']) print(a_list) a_list.reverse() print(a_list) a_list.remove('inserted') print(a_list) # sort by data ...
numbers = [1, 2, 3] multiply100 = [number * 100 for number in numbers] print(multiply100) result = [number * 100 for number in numbers] print(result)
my_list = [] my_list.append(1) my_list.append(3) my_list.append(5) my_list.append(("Ahmad", "Agus", "Hasan")) colors = {} colors["Merah"] = "Red" my_list.append(colors) print(my_list)
my_list = [] my_list.append(1) my_list.append(2) my_list.append(3) my_list.append(("victor", "ronaldo")) plants = {} plants["pisang"] = 23 my_list.append(plants) print(my_list) print(len(my_list)) my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Output: e print(my_list[...
students = ["faisal"] students.append("roni") print(students) students.insert(1, "arief") print(students) women_students = ["wenty", "kekek", "suci", "rini", "melinia"] students.extend(women_students[0:2]) print(students) students.sort() print(students) students.reverse() print(students) students.remove("faisal") ...
friends = ["Hasan", "Fahri", "Kamil", "Ahmad", "Tomi"] for teman in friends: print(teman) print() print(friends[0]) print(friends[3]) print(friends[2]) print(friends[4]) print(friends[1]) print() print("Asli : ", friends) friends.reverse() print("Reverse : ", friends) friends.pop() print("Pop : ", friends) frien...
list2d = [] list2d.append([]) list2d.append([]) list2d[0].append(1) list2d[0].append(2) list2d[1].append("Darmawan") list2d[1].append("Abinugroho") for y in list2d: for x in y: print(x, end=" ") print()
# first create a list of questions and store it into the list # then create a dictionary that containes the correct answer for the given question # if the answer is correct then point will increase then it will not # question list questionsList = [ "How many Continent are there ? \n \n 1. Five 2. Size 3. Four ...
# -*- coding: utf-8 -*- #gruppe: Jørn Utheim-Olsen import random mydeck = [r+s for r in '23456789TJQKA' for s in 'SHDC'] def deal(numhands, n=5, numdecks=1, deck=mydeck): random.shuffle(deck) for s in range(numdecks - 1): deck = deck + mydeck return [deck[n*i:n*(i+1)] for i in range(numhands)] pranks = ["high ...
#!/usr/bin/env python3 N = 100 def main(): """ Sum of squares of numbers upto N - brute Sum of numbers squared = n.n+1/2 ** 2 """ sum_of_squares = sum(n * n for n in range(N + 1)) square_of_sum = sum(range(N+1)) ** 2 print(square_of_sum - sum_of_squares) if __name__ == '__main__': ma...
''' 列表生成式: [] ''' l = [x*x for x in range(1,11)] print(l) l2 = [m*m for m in range(1,11) if m%2 == 0] print(l2) l3 = [m+m for m in 'ABC' for n in 'XYZ' ] print(l3) d1 = {'a':1,'b':2,'c':3} l4 = [k+'='+str(v) for k,v in d1.items()] print(l4) #注意!! str1 = 'aa' str2 = 33 print(str1,str2,str1+str(str2)) #, 一个空格 +连接符 但是...
name = ['a','b','c'] for n in name: #不要忘记冒号 print(n) L = list(range(5)); print(L) sum = 0 ''' for x in range(101): sum += x print(sum); ''' n = 99 while n>0: sum += n n -= 2 print(sum)
a = 'abc' b = a a = 'xyz' print('a = ',a,'b = ',b) # 以下是练习 n = 123 f = 456.789 s1 = 'hello,world' s2 = 'hello.\'Ysw\'' s3 = r'hello,"ysw"' s4 = r'''hello ,YSW!''' print(n) print(f) print(s1) print(s2) print(s3) print(s4)
import socket def tcp_clt(): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = ('localhost', 10000) print('connecting to {} port {}'.format(*server_address)) sock.connect(server_addr...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(arr): arr1=[] for x in arr: for y in x: ...
# ALDS1_6_D: Minimum Cost Sort # https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_D import copy def min_sort_cost(W: list) -> int: num = len(W) min_w = min(W) c = 0 # sorting cost X = copy.deepcopy(W) X.sort() # result W sorted L = [None] * (max(W) + 1) for i in range(num): L...
# ALDS1_1_D: Maximum Profit # https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/1/ALDS1_1_D def maximum_profit(n, R): max_profit = -2 * pow(10, 9) # should be < 1 - pow(10, 9), minimum profit min_rate = R[0] for r in R[1:]: max_profit = max(max_profit, r - min_rate) min_rate = min(...
# ALDS1_8_A: Binary Search Tree I # https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_8_A class Node: def __init__(self, key: int, parent=None, left=None, right=None) -> None: self.key = key self.parent = parent self.left = left self.right = right class BinaryTree: nodes = [] ...
# ALDS1_4_B: Binary Search # https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_4_B import math def binary_search(A:list, n:int, key:int) -> bool: left = 0 right = n while left < right: mid = math.floor((left + right) / 2) if key == A[mid]: return True elif key > A...
#!/usr/bin/env python def binarize(num): division = num / 2 remainder = num % 2 if (division == 0): return str(remainder) else: return binarize(division) + str(remainder) if __name__ == '__main__': number = input('enter a number:\n') print binarize(number)
from random import randint as ri print("Lets Play Stone-Paper-Scissors....") print("***") print("***") print("***") print("***") print("***") Player= input("Hey 'Player' I am Mr. Computer!! \n ...Make your Move...") rand_num = ri(0,2) if rand_num==0: computer = "Stone" elif rand_num==1: computer= "Paper" else: ...
#!/usr/bin/env python3 f=open("input_3.txt", "r") hpos=0 cnt=0 for line in f.readlines(): line=line.strip() if line[hpos] == "#": cnt += 1 hpos += 3 if hpos >= len(line): hpos = hpos - len(line) print(cnt)
""" This module will be responsible for the Substitute objet It will handle saving substitution items with a better nutrition grade than selected products in the database """ class Substitute: """ This class is responsible for the addition of products to the database after an API GET Request to the Open Fo...
txt = input("Digite seu nome: ") def escada(x=0): global txt if x == len(txt)+1: exit() else: for i in range(x): print(txt[i], end="") print("") return escada(x + 1) print(escada())
lista = [] n= 0 cont = 0 while n != -1: n = int(input("Digite um número inteiro:")) lista.append(n) element = int(input("Escolha um elemento:")) print("O número %i apareceu %i vezes" %(element, lista.count(element) ))
txt = input("Digite algo: ") def alpha(txt): global letra letra = True for i in txt: if not("a"<= i <= "z" or "A" <= i <= "Z"): letra = False break return letra def mas(): global txt,mas mas = False if alpha(txt): mas = True for j in tx...
class Retângulo(object): def __init__(self,A,B): self.ladoA = A self.ladoB = B def Mudar_valor(self,A,B): self.ladoA = A self.ladoB = B def retornar(self): return f"O comprimento do retângulo é igual a {self.ladoA} e a largura é igual a {self.ladoB}",self.ladoA,self.l...
"""def f(ops): f = ops print(f) f(1) x=f f=2 print(f) x(3)""" def f(ops): """ Função f Recebe objeto ops Imporime valor de ops Não devolve nada """ num = ops print(num) help(f)
txt = input("Digite uma string: ") txt2= input("Digite outra string: ") print("A string \"{}\" tem {} caracteres".format(txt,len(txt))) print("A string \"{}\" tem {} caracteres".format(txt2,len(txt2))) if len(txt) == len(txt2): print("As duas strings possuem o mesmo tamanho") else: print("As duas strings não po...
print("O saque disponível é entre 10 e 600 reais.") saque = int(input("Qual o valor a ser sacado? ")) if saque<10 or saque>600: print("O valor solicitado está indisponível.") else: print(saque,"reais") n1= 100 n2= 50 n3= 10 n4= 5 n5= 1 n11= saque//n1 n22r= saque%n1 n22= n22r//n2 n33r= n22r%n2 n33= n33r//n3 n4...
idade = int(input("Digite sua idade: ")) if idade >= 18 and idade <21 : print("Você pode ingerir bebida alcoólica") elif idade >= 21 : print("Você é VIP") else: print("Você só pode beber refrigerante")
notas = [] notat = 0 for i in range (1,5): nota = int(input("Digite a %i° nota: " %i)) notas.append("%i° nota = %i" %(i, nota)) notat += nota notas.append("Média total = %g" %(notat/4)) print(notas)
matrizl = [] def matriz(): global matrizl , m, n m = int(input("Digite o número de linhas: ")) n = int(input("Digite o número de colunas: ")) m2 = m for i in range(n): m = m2 lista1 = [] for j in range(m): valor = int(input("Digite o valor para atribuir a matriz %...
l1 = [1,2,3] l1.reverse() print(l1) l2 = [1,2,3] l2.remove(2) print(l2)
num1 = int(input("Digite um número: ")) num2 = int(input("Digite outro número: ")) if num1 > num2: print("O número",num1,"é maior que o número",num2) elif num1 == num2: print("Os dois números são iguais") else: print("O número",num2,"é maior que o número",num1)
num = 12 print("Eu tenho",num,"cachorros") x = 11 y = 13 z = 14 x = y = z #x e y vão ser igual a 14 então. x=y=z=12 #, separa as variavéis atribuídas x,y,z=1,2,3 x = 1 y = 2 z = 3
n = int(input("Digite um número: ")) fat = n print(f"Fatorial de {n}") print(f"{n}! =",n, end="") while n-1 >= 1: n -= 1 fat *= n print(f" . {n}", end="") print(" =",fat)
Dic = {"Lambda": lambda x: x+1} print(Dic["Lambda"](3)) contato = {"Nome":"Enzo","Telefone":23454567,"Celular":998767608,"E-mail":"enfurtini@hotmail.com"} for coisa in contato: print(contato[coisa]) print(len(contato))
nome = input("Digite o seu nome de usuário: ") senha = input("Digite a sua senha: ") ver= False for i in range(len(nome)): if nome[i] == senha[i] or ord(senha[i])- ord(nome[i]) == 32 or ord(senha[i])- ord(nome[i]) == -32: ver = True if nome[i] != senha[i] and ord(senha[i])- ord(nome[i]) != 32 and ord(s...
txt = input("Digite seu nome: ") for i in range(len(txt)): print(txt[i])
def dado(faces): import random n = random.randint(1,faces) return n faces = int(input("Escolha o número de faces do dado: ")) print("Caiu na face:",dado(faces))
import sys import configparser import psycopg2 from datetime import datetime """ This module executes Data Quality checks on the final tables. The output is both printed in the console and saved as a log file in the logs folder. It runs the following data quality checks: - Check that all tables have more than 9 r...
import tkinter from tkinter import * from tkinter import messagebox class MyGUI: def __init__(self): self.main_window = tkinter.Tk() self.top_frame = tkinter.Frame(self.main_window) self.bottom_frame = tkinter.Frame(self.main_window) self.my_button = tkinter.Button(self.main_window,...
m=6 n=9 c=m*n for i in range(1,c+1): if(m%i==0 and n%i==0): gcd=i print("gcd of num is",gcd) lcm=c/gcd print("lcm of num is",lcm)
# new python file warm ups # 12.4.17 #Write a python function #Which accepts the user's #first and last name #and prints them in reverse order #With a space between them # def reverse_order(last_name, first_name) # #print("%s, %s" % last_name, first_name) # print(last_name + "" + first_name) # concatination ...
class DynamicConnectivity(object): # class takes the number of objects n as input, # and initializes a data structure with objects numbered from # 0 to N-1 def __init__(self, n): self.max=n self.groups=[] # union connects point p with point q def union(self, p, q): g_p = self.findGrou...
hours = input("Enter Hours: ") rate = input("Enter Rate: ") hours = float(hours) rate = float(rate) if hours > 40: overtime = hours - 40 pay = (40*rate) + (overtime*(rate*1.5)) else: pay = hours*rate print(pay)
grade = float(input("Please enter grade between 0.0 and 1.0: ")) if grade < 0 or grade > 1: print("Error. Bye.") else: if grade >= 0.9: print("A") elif grade >= 0.8 and grade < 0.9: print("B") elif grade >= 0.7 and grade < 0.8: print("C") elif grade >= 0.6 and grade < 0.7: print("D") else: print("F")
import sqlite3 connection = sqlite3.connect("banco.db") cursor = connection.cursor() criar_tabela = "CREATE TABLE IF NOT EXISTS hoteis(" \ "hotel_id int PRIMARY KEY," \ "nome text," \ "estrelas real," \ "diaria real," \ "cidade text" \ ...
import urllib from bs4 import BeautifulSoup def getLinks(url): l = [] placeholders = ['#', '?'] # Reference - https://stackoverflow.com/questions/15138614/how-can-i-read-the-contents-of-an-url-with-python urlOpen = urllib.urlopen(url) webpage = urlOpen.read() # Reference - https://stackoverflow.com/questions/...
base_a = float(input("Base inferior: ")) base_b = float(input("Base superior: ")) altura = float(input("Altura: ")) area = round(((base_a + base_b)*altura)/2, 1) print(f"Area: {area}")
# -*- coding: utf-8 -*- """ Created on Wed May 4 17:23:16 2022 @author: vince """ from random import randrange numeroAleatorio = randrange(100) intentos = 0 adivinado = False while not(adivinado): numeroSeleccionado = int(input("Ingrese numero: ")) intentos += 1 if(numeroSeleccionado == numeroAleatorio...
# -*- coding: utf-8 -*- """ Created on Thu May 5 16:05:44 2022 @author: vince """ def factorial(n): f = 1 for i in range(1, n + 1): f = f * i return f numero = int(input("Ingrese n: ")) resultado = factorial(numero) print(f"{numero}! : {resultado}")
import pandas data = pandas.read_csv("weather_data.csv") # print(data) # print(data["temp"]) print(type(data)) # Type: Dataframe --> Like a whole table print(type(data["temp"])) # Type: Series --> Like a single column as a list data_dict = data.to_dict() # Convert a Dataframe into a python dictionary pr...
from question_model import Question class QuizBrain: def __init__(self, question_list): self.question_number = 0 self.question_list = question_list self.score = 0 def still_has_questions(self): if self.question_number < len(self.question_list): return True ...
# print("Hello") # num_char = len("Hello") # print(num_char) def my_function(): print("Hello") print("Bye") my_function() # def jump_hurdle(): # turn_left() # while wall_on_right(): # move() # turn_right() # move() # turn_right() # move() # while wall_on_right() and front...
class User: def __init__(self, user_id, username): self.id = user_id self.username = username self.followers = 0 self.following = 0 def follow(self, followed_user): followed_user.followers += 1 self.following += 1 user1 = User("001", "karanbr") user2 = User("0...
# print o of sting Hello # print("Hello"[4]) # -- Integer -- i = 123 j = 345 print(i+j) # underscore comma --> easier to read # print(123_456) # prints 123456 # -- Float -- f = 3.14159 # -- Boolean -- x = True y = False # -- Type checker -- # num_char = input("Whats your name?\n") # print(type(num_char)) # num_c...
import art import random cards = [2, 3, 4, 5, 6, 7, 8, 9, "Jack", "Queen", "King", "Ace"] def hand_out_card(): num = random.randint(1, len(cards) - 1) value = cards[num] cards.remove(cards[num]) return value def hit_or_stop(): answer = input("Hit or stop playing? (hit/stop): ").lower() if a...
# Functions with Outputs def format_name(first_name: str, surname: str): if first_name == "" or surname == "": return "No valid inputs" fullname = first_name.title() + " " + surname.title() return fullname name = format_name("kARAN", "bruellau") print(name) print(format_name("", ""))
import tkinter def button_clicked(): print("I got clicked") # new_text = entry.get() label.config(text=f"{entry.get()}") # Window window = tkinter.Tk() window.title("First Python GUI") window.minsize(width=500, height=300) window.config(padx=20, pady=20) # Label label = tkinter.Label(text="I am a Label...
with open("file1.txt") as file1: nums1 = [int(num) for num in file1.readlines() if num != "\n"] with open("file2.txt") as file2: nums2 = [int(num) for num in file2.readlines() if num != "\n"] print(nums1) print(nums2) result = [number for number in nums2 if number in nums1] # Write your code above 👆 print...
#Faça um Programa que peça o raio de um círculo, calcule e mostre sua área. #Calculo da rea e : A :Pi * R² PI = float(3.14) raio = float(input('Digite o raio do círculo: ')) def area(): return f' A rea total do círculo e : {float(PI*(raio*raio))}' print(area())
import math # Ativa o módulo de funções matemáticas """ Gera a sequência de Fibonacci até ultrapassar um limite que deve ser menor do que 1000, para alinhar os resultados e razão entre cada dois elementos """ # O limite deve ser maior ou igual a 2 Limite = int(input('Entre com o limite (>= 2): ')) N = 2 # Nú...
def reverse(arr,n): start=0;end=n-1 while(start<=end): arr[start],arr[end]=arr[end],arr[start] start+=1 end-=1 def reverse_alter(arr,n): return arr[::-1] def reverse_recursive(arr,start,end): if(start>=end): return arr[start],arr[end]=arr[end],arr[start] return r...
def getMin(arr,n): if(n==1): return arr[0] else: return min(getMin(arr[1:],n-1),arr[0]) def getMax(arr,n): if(n==1): return arr[0] else: return max(getMax(arr[1:],n-1),arr[0]) arr = [ int(x) for x in input().strip().split()] print(getMin(arr,len(arr))) print(getMax(arr,l...
# Python3 program to check if a connected # graph is bipartite or not suing DFS # Function to store the connected nodes def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # Function to check whether a graph is # bipartite or not def isBipartite(adj, v, visited, color): for u in...
class Volume: def change_volume(self, command_volume, current_volume): if command_volume == 'up': current_volume += 1 elif command_volume == 'down': current_volume -= 1 print("Volume: ", current_volume) return current_volume
print('Exercício 4: Programa que lê algo do teclado e dê todas as informações possíveis sobre.') a1 = input('Digite alguma coisa:') print('O tipo primitivo de {} é: '.format(a1)) print(type(a1)) print('"{}{}" é alfanumerico? '.format('\033[31;m', a1), '\033[;m', a1.isalnum()) print('"{}{}" é alfabeto? '.format('\033[31...
print('Exercício 69: Tratamento de dados') maiordezoito = numerohomens = mulhermenor20 = idade = 0 while True: print('=' * 40) print('------- CADASTRO -------') print('=' * 40) idade = int(input('Digite a idade: ')) if idade > 18: maiordezoito += 1 sexo = str(input('Digite o sexo: [Mascu...
#print('Exercício 27: Analisador de nome') #nome = str(input('Insira seu nome completo por favor: ')).strip() #n = nome.split() # mostrar primeiro nome #print('Seu primeiro nome é: "{}". '.format(n[0].capitalize())) # mostrar último nome #print('Seu último nome é: "{}". '.format(n[len(n)-1].capitalize())) print('Exerc...
print('Exercício 31: Programa que pergunte a distância de uma viagem em quilômetros.') # TABELA print('=' * 60) print('TABELA DE PREÇOS:') print(' R$0.50 por quilômetro para viagens de até 200km\n R$0.45 por quilômetro para viagens mais longas') print('=' * 60) # VARIÁVEIS km = int(input('Digite a distância da sua viag...
print('Exercício 52: Programa que lê um número inteiro e diz se é ou não um número primo') numero = int(input('Digite um número: ')) total = 0 for c in range(1, numero + 1): if numero % c == 0: print('\033[34m', end='') total += 1 else: print('\033[31m', end='') print(f'{c}', end=' '...
print('Exercício57: Conferidor de sexo') sexo = str(input('Informe seu sexo: [M/F]:')).strip().upper() while sexo != 'M' and sexo != 'F': sexo = str(input('\033[1;31mOpção inválida!\033[m Informe o seu sexo: [M/F]')).strip().upper() if sexo == 'M': sexo = '\033[34mMasculino\033[m' # azul if sexo == 'F': s...
print('Exercício 8: Programa que leia um valor em metros e converta para centímetos e milímetros.') m = float(input('\033[34;mInsira o valor em metros\033[m:')) km = m / 1000 hm = m / 100 dam = m / 10 dm = m * 10 cm = m * 100 mm = m * 1000 print(' {}m equivale a {:.3f}km;\n {:.2f}hm;\n {:.1f}dam;\n {:.0f}dm;\n {:.0f}cm...
import os import sys def remove_duplicate(csvfile): with open(csvfile,'r') as in_file, open('temp.csv','w') as out_file: seen = set() # set for fast O(1) amortized lookup for line in in_file: if line in seen: continue # skip duplicate seen.add(line) out_file.write(line) os.remove(csvfile) os.rename("te...
# question1 x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] # using slicing from the front print(x[7:12]) #using slicing from the back print(x[-9:-4]) # question2 x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] #even no using slicing print(x[1:16:2]) # qyestion3 #print every 4 no x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]...
ablist = [ "dyiclysmffuhibgfvapygkorkqllqlvokosagyelotobicwcmebnpznjbirzrzsrtzjxhsfpiwyfhzyonmuabtlwin","ndqeyhhcquplmznwslewjzuyfgklssvkqxmqjpwhrshycmvrb","ulrrbpspyudncdlbkxkrqpivfftrggemkpyjl","boygirdlggnh","xmqohbyqwagkjzpyawsydmdaattthmuvjbzwpyopyafphx","nulvimegcsiwvhwuiyednoxpugfeimnnyeoczuzxgxbqjvegcxeqnjb...
A = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] result = [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] def flip_matrix(A): """ :param A: :return: """ # 1. flip horizontally = reverse the elements in the sublists. # reversed returns a iterator object vs .reverse() = inplace # 2. 1-num gives us th...
def is_a_valid_ip_address(word): digits = word.split(".") if len(digits) == 4: for digit in digits: if int(digit) > 255: # IP4 address should always be less than 255 return False return True return False def get_most_frequnent_ip_address(): ...
#!/usr/bin.env python # Copyright (C) Pearson Assessments - 2020. All Rights Reserved. # Proprietary - Use with Pearson Written Permission Only arr1 = [1, 12,15, 26, 38] arr2 = [2, 13, 17, 30 , 45] def get_median_two_sorted_arrays_merge_sort(arr1, arr2): """ Time complexity: O(m+n) Space complexity: O(n) ...
#!/usr/bin.env python # Copyright (C) Pearson Assessments - 2020. All Rights Reserved. # Proprietary - Use with Pearson Written Permission Only """ - Supervised Learning Algorithm - Instance based learning and lazy learning - Classification and Regression - Ref: https://www.analyticsvidhya.com/blog/2018/03/introducti...
""" BFS - Breadth First Search 1) In graphs - we may visit same node more than once 2) Use a boolean array 3) DefaultDict - Representation """ from collections import defaultdict class Graph(object): def __init__(self): # default dictionary to store graphs self.graph = defaultdict(list) def a...
def reverseVowels(astring): astring = list(astring) left = 0 right = len(astring)-1 while left <= right: if astring[left] not in 'aeiouAEIOU': left += 1 continue if astring[right] not in 'aeiouAEIOU': right -= 1 continue if astring[...