text
stringlengths
37
1.41M
import argparse import json parser = argparse.ArgumentParser(description='convert csv file to json file') parser.add_argument('-i', '--input', metavar='input', help='Specify input csv file name') parser.add_argument('-o', '--output', metavar='output', help='Specify output json file name') args, rem = parser.parse_kno...
from random import randint while True: palpite = int(input('Digite o palpite du número digitado pelo computador (0 à 5): ')) if palpite < 0 or palpite > 5: print('\nOpa! Palpite inválido!\nTente novamente!!!', end='\n') else: break n = randint(0, 5) print('ACERTOU!' if palpite == n else 'ER...
n = int(input('Entre com o número: ')) print('Tabuada do {}'.format(n),end=' >>> \n\n') for i in range(1, 11, 1): print('{:2} X {} = {:3}'.format(i, n, (i*n)))
flag = True num = int(input('\nDigite um número para verificação se é primo ou não: ')) for i in range(2, num): if num % i == 0: flag = False break print('O número {} '.format(num)+('é primo!' if flag else 'não é primo!'))
while True: op = str(input('Digite o seu sexo: ')).upper() if op != 'M' and op != 'F': print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m') else: break
valores = list() i = 0 naList5 = False print() while True: aux = (int(input(f'Digite o valor {i+1} (Digite 0 para terminar): '))) if aux == 0: break else: if aux == 5: naList5 = True valores.append(aux) i += 1 valores.sort(reverse=True) print(f'\nForam digitado...
from random import randint sorteios = list() jogo = list() n = 0 print() while True: n = int(input('Quantos jogos você quer gerar? >>> ')) if n <= 0: print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m') else: break print('\n================================================') fo...
from math import floor n = float(input('Entre com um número: ')) print('O número {} tem como parte inteira {}'.format(n, floor(n)))
n = float(input('Digite quantos R$ tem na carteira: ')) print('Cotação do dolar: US$1.00 = R${:,.2f}\nLogo pode com R${:,.2f} você pode comprar US${:,.2f}' .format(3.27, n, (n/3.27), 2))
n = 0 somaN = 0 keep = 'S' allN = [] print() while keep != 'N': n = int(input('Entre com um número (digite 999 para parar o programa): ')) if n == 999: allN.sort() break somaN += n allN.append(n) print(f'\nQuantidade de números digitados: {len(allN)}\nSoma de todos os números digitados:...
brasileiro = ('Athetico', 'Atlético-MG', 'Avaí', 'Bahia', 'Botafogo', 'Ceará', 'Chapecoense', 'Corinthians', 'Cruzeiro', 'CSA', 'Flamengo', 'Fluminense', 'Fortaleza', 'Goiás', 'Grêmio', 'Internacional', 'Palmeiras', 'Santos', 'São Paulo', 'Vasco') print(f'\nPrimeiros 5 colocad...
fibo = [0, 1] i = 0 while True: n = int(input('\nDigite quantos termos da série de fibonnaci você deseja (0 para sair): ')) if n < 0: print('\033[1;31mERRO! Entrada inválida! Tente novamente!\033[m') else: if n == 1: print('Primeiro termo da série Fibonacci: {}'.format(fibo[0]), ...
peso = 0 alt = 0 while True: peso = float(input('Entre com o seu peso: ')) if peso < 0: print('\033[1;31mERRO! Peso inválido!\033[m') else: break while True: alt = float(input('Entre com a sua altura: ')) if alt < 0: print('\033[1;31mERRO! Altura inválida!\033[m') else:...
pessoas =[[] for _ in range(3)] plus18, qtdHomem, woman20minus = 0, 0, 0 aux1, aux2, aux3 = 0, 0, 0 flag = False while not flag: aux1 = str(input('\nNome da pessoa >>> ')) while True: aux2 = int(input('Qual a idade? >>> ')) if aux2 < 0: print('\033[1;31mERRO! Entrada inválida! Tente...
# posteriors # Compute the likelihood of posteriors # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Tue Sep 09 16:15:32 2014 -0400 # # Copyright (C) 2014 Bengfort.com # For license information, see LICENSE.txt # # ID: posteriors.py [] benjamin@bengfort.com $ """ Compute the likelihood of posteriors...
# python3 import sys def compute_min_refills(distance, miles, tank, stops): # write your code here num_refill, curr_refill, limit = 0, 0, miles while limit < distance: if curr_refill >= tank or stops[curr_refill] > limit: return -1 while curr_refill < tank - 1 and stops[curr_re...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if(n == 0): r...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # use list as a queue from collections import deque class Solution: def zigzagLevelOrder(self, root): """ :type root: TreeNode :rt...
from Validations import ValidTypes, ValidDates from datetime import datetime class StringOperations: """ This class should implement all the methods needed to process all kind of string operations """ @staticmethod def getLastChar(string_var): """ Returns the last element of...
from datetime import datetime # My libraries from Validations import ValidTime, ValidCustom from Utilities import StringOperations class PicoPlaca: """ This class has all the restrictions operations required for Pico y Placa """ @staticmethod def __timeRestriction(): """ ...
def bubble_sort(elements): elements_copy = elements[:] n = 1 for i in range(len(elements_copy)-1): for j in range(len(elements_copy)-n): if elements_copy[j] > elements_copy[j+1]: elements_copy[j], elements_copy[j+1] = ( elements_copy[j+1], elements_cop...
def partition(alist, first, last): pivot_pos = last cur_pos = first while pivot_pos != cur_pos: cur, pivot = alist[cur_pos], alist[pivot_pos] if cur > pivot: alist[cur_pos] = alist[pivot_pos-1] alist[pivot_pos-1], alist[pivot_pos] = pivot, cur pivot_pos -...
#math module import math print (math.ceil(123.12424)) #concatinate x='hello world' print (x[:6]+'bangladesh') #string var1 = 'Hello World!' var2 = "Python Programming" print(var1[10]) print("var2[1:5]: ", var2[1:5]) #lists x=[1,2,3,4,5] print(x[2:4]) #tuples tup1=(12,34.56); tup2=('abc','xyz')...
''' Created on Mar 5, 2016 @author: shivam.maharshi ''' from oop.Employee import Employee from oop.Citizen import Citizen from logging import Manager class Manager(Employee, Citizen): " This is Manager class. A sub class of an Employee class." def __init__(self, name="Manager", salary=1000, l...
''' Created on May 22, 2016 Given a matrix with traversal cost on the nodes, find the lowest cost of travelling from point 0,0 to m,n. Link: http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/ @author: shivam.maharshi ''' def naiveGet(a, x, y, dx, dy, val): if(x > dx or y > dy): ...
from collections import Iterable # python迭代是通过for...in来实现的。 # python的for不仅仅可以用在list和tuple,还可以用在其他任何可以迭代的对象上 # list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代 d = {'a': 123, 'b': 245, 'c': 'oop', 'd': 'ddc'} # 打印出d的所有key,因为dict的存储顺序不想list一样顺序存储所以,迭代的顺序可能不一样。 for key in d: print(key) # 默认情况下dict...
# python内建函数map学习 # map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 L = [a for a in range(1, 11)] def function(x): return x*x r = map(function, L) print(list(r)) print(list(map(str, [a for a in range(1, 11)])))
''' Created on Jun 7, 2017 @author: jwang02 ''' '''program causing an error with an undefined variable''' def main(): x = 3 f() def f(): print(x) # error: f does not know about the x defined in main main() '''A change to badScope.py avoiding any error by passing a parameter''' ''' def main(): x = ...
''' Created on Jun 9, 2017 @author: student ''' # Finds the maximum of a series of numbers def main(): a, b, c = input("Please enter the coefficients (a, b, c): ") if a >= b: if a >= c: my_max = a else: my_max = c else: if b >= c: ...
# Faça um programa que peça o tamanho de um arquivo para download (em MB) e a # velocidade de um link de Internet (em Mbps), calcule e informe o tempo # aproximado de download do arquivo usando este link (em minutos). def download_file(): file_size = float(input('Informe o tamanho do arquivo para download (em MBs)...
# Faca um Programa que peca dois numeros e imprima a soma. number_one = float(input('Informe o primeiro numero: ')) number_two = float(input('Informe o segundo numero: ')) add_numbers = number_one + number_two print('A soma de ' + str(number_one) + ' + ' + str(number_two) + ' e ' + str(add_numbers) + '.')
pineapples = 5 zebras = 3 print(zebras < pineapples) print(pineapples > zebras) print(pineapples == zebras) print(pineapples != zebras) print(pineapples == 4) and (zebras == 2) print(pineapples == 5) or (zebras == 1) age = 10 height = 60 print(age > 7) and (height > 46)
from random import randint def get_number(): """ Returns: User input """ # while loop to evaluate its correctness while True: try: user_input = int(input('Please provide number: ')) break except ValueError: print('Provided value is not a number, ...
#Albert Valado Pujol #Práctica 7 - Ejercico 12b #Escribir un programa que lea una frase, y pase ésta como parámetro a una función #que debe contar el número de palabras que contiene. #Debe imprimir el programa principal el resultado. #No se sabe cómo están separadas las palabras. Pueden estar separadas por más de un bl...
#Albert Valado Pujol - Práctica 2 - Introducción a Python #Ejercicio 1 - Calcular el área de un triángulo print ("Vamos a calcular el área de un triángulo.\n") base= int(input("Introduce la base.\n")) altura= int(input ("Introduce la altura.\n")) area= int(base*altura)/2 print ("El área del triangulo es %d." %(area)) i...
#Albert Valado Pujol #Práctica 6 - Ejercicio 11 import random import time random.seed (time.time ()) print("El ordenador va a pensar un número. Trate de adivinarlo.\n") minimo = int (input ( "Introduzca un valor mínimo:\n")) maximo = int (input ( "Introduzca un valor máximo:\n")) secreto = random.randint (minimo, maxi...
#Albert Valado Pujol #Practica 3 - Ejercicio 5 #Pida un número que como máximo tenga tres cifras (por ejemplo serían válidos 1, 99 i 213 pero no 1001). Si el usuario introduce un número de más de tres cifras debe un informar con un mensaje de error como este “ ERROR: El número 1005 tiene más de tres cifras”. num=int(in...
#Albert Valado Pujol #Práctica 5 - Ejercicio 7 #Escribe un programa que pida la anchura de un triángulo y lo dibuje de #la siguiente manera: ancho=int(input("Introduce la anchura del triángulo.\n")) for i in range(ancho): print("*"*i) for j in range(ancho, 0, -1): print("*"*j) input(" ")
#Albert Valado Pujol #Practica 3 - Ejercicio 6 #Pida al usuario el precio de un producto y el nombre del producto y muestre el mensaje con el precio del IVA (21%). Por ejemplo: “ Tu bicicleta vale 100 euros y con el 21 % de IVA se queda en 121 euros en total”. nombre=input("Introduzca su producto.\n") precio=float(inpu...
fruits = ['Banana', 'Warermellon', 'Grapes', 'Mango'] for items in fruits: print(items)
# Write a programm using function to find greater of three number def greater(num1, num2, num3): if num1 > num2: if num1 > num3: return num1 else: return num3 else: if num2 > num3: return num2 else: return num3 m = greater(5, 8, 2...
l1 = [1, 8, 7, 2, 21, 15] print(l1) # l1.sort() # sort the list # l1.reverse() # reverses the list # l1.append(45) # appends the list # l1.insert(2, 544) # insert 544 at index 2 # l1.pop(2) # remove element at index 2 l1.remove(21) # removes 21 from list print(l1)
# The game() function in a programm lets a user play a game and returns the score as an integer. You need to read a file 'hiscore.txt' which is either blank or contains the previous hi-score. You need to write a programm to update the hiscore whenever game() breaks the hiscore. import random def game(): n = random...
# If else and elif syntax. # a = 45 # if(a > 3): # print("The value of a is greater then 3") # elif(a > 7): # print("The value of a is greater than 7") # else: # print("The value is not greater than 3 or 7") # 2. Multiple if statements a = 45 if(a > 3): print("The value of a is greater then 3") if(a...
def percent(marks): # return ((marks[0] + marks[1] + marks[2] + marks[3])/400)*100 return sum(marks)/4 marks1 = [45, 78, 86, 77] percentage = percent(marks1) marks2 = [55, 40, 50, 70] percentage2 = percent(marks2) print(percentage, percentage2)
# Write a programm to format the following letter using escape sequence chracter letter = "Dear Shibu, This Python course is nice! Thanks!" formatter_letter = "Dear Shibu,\n\tThis Python course is nice!\nThanks!" print(formatter_letter)
# Write a programm to mine a log file and find out whethir it contains "python". and also find line number. content = True i = 1 with open("log.txt") as f: while content: content = f.readline() if 'python' in content.lower(): print(content) print(f"python is present on li...
nterms =[] res=[] for i in range(0,1): a=int(input()) nterms.append(a) n1 = 0 n2 = 1 count = 0 if nterms[0] <= 0: print("Please enter a positive integer") elif nterms[0] == 1: print("Fibonacci sequence upto",nterms,":") res.append(n1) else: print("Fibonacci sequence upto",nterms,":") while count < nte...
lower,upper=input().split() lower = int(lower) upper = int(upper) for num in range(lower, upper): order = len(str(num)) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10
a=int(input()) sum1 = 0 while(a > 0): sum1=sum1+a a=a-1 print(sum1)
# TWI DAY NAME DETECTOR PROGRAM # Yaw Asare, June 12 2020 # This is primarily a test of boolean and comparison operators print() print('*** TWI DAY NAME DETECTOR ***') print() print('Tell me the day of the week you were born and your gender, I will tell you your dayname in Twi') print() # getting the user's gender g...
import random print('Put in a number between 1 and 10 and I will see if I can guess it!') userNumber = input() print() numberOfGuesses = 0 while True: compGuess = random.randint(1, 10) numberOfGuesses = numberOfGuesses + 1 if compGuess == int(userNumber): print('I got it right!! Your number is: '...
''' - Given a github username extrac all his/her folowers and store them into a CSV File https://api.github.com/users/{user}/followers ''' import requests, csv page = 1 cycle = True COLUMNS = ['login', 'id', 'node_id', 'avatar_url', 'gravatar_id', 'url', 'html_url', 'followers_url', 'following_url', 'gists_url', 'st...
import time import json from pprint import pprint as pp # placed into variables for easy use tickets_file_location = '../json/tickets.json' ticket_types_file_location = '../json/ticket_types.json' users_file_location = '../json/users.json' def create_ticket(ticket_id, ticket_type_id, ticket_description, ticket_open...
number = int (input(" enter any number : ")) for i in range(0,number ): chr = 65 for j in range(0,number - i): print (chr , end = " ") print(" ")
from .pessoa import Pessoa # primeiro importamos a classe Mãe class PessoaFisica(Pessoa): # Para indicar que uma classe extende a outra, passamos ela como "Parâmetro" na definição da class def __init__(self, nome, endereco, cpf, nascimento): super().__init__(nome, endereco) # a instrução super() chama e...
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem from itertools import combinations_with_replacement if __name__ == '__main__': # break input into list of size and string mystringlist = [ str(x) for x in input().split(' ')] # break string into...
#anju num=int(input()) for i in range (1,num+1): if(num%i==0): print (i, end=" ")
num=int(input()) f=1 if(num<0): print("0") if(num==0): print("1") else: for i in range(1,num+1): f=f*i print(f)
#anju x=input() z=list(x) y=len(z) f=0 if y%2==0: i=y//2 z[i]='*' z[i-1]='*' t=''.join(z) print(t) else: f=y//2 z[f]='*' e=''.join(z) print(e)
#anju string=list(input()) a=(sorted(string)) for i in range(0,len(a)): print(a[i],end="")
# coding: utf-8 # In[2]: #define dictionary data structure #dictionaries have key: value for the elements example_dict = { "class" : "astr 119", "prof" : "Brant", "awesomeness" : 100 } print(type(example_dict)) #will print type dict #get a value via key example_dict["awesomeness"] += 1 #increase...
# coding: utf-8 # In[1]: #if else control #define function def flow_control(k): #define string based on k value if(k==0): s = "variable k = %d equals 0" % k elif(k==1): s = "variable k = %d equals 1" % k else: s = "variable k = %d does not equal 0 or 1" % k # print vari...
bottles_remaining = 99 while bottles_remaining > 0: print(f"{bottles_remaining} bottles of beer on the wall, {bottles_remaining} of beer") print("Take one down, pass it around") bottles_remaining = bottles_remaining - 1 print(f"{bottles_remaining} bottles of beer on the wall")
username = input("Enter username:") print("Username is: " + username) price = 50 txt = "The price is {} dollars" print(txt.format(price)) myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Telsa", model = "Model Y")) age = 21 name = "Alex" txt = "His name is {1}. {1} is {0} years old." ...
client_list = {1: "Anirban", 2: "John", 3: "Messi", 4:"sergio", 5: "James", 6:"Ronaldo"} lock_list = {1: "Exercise", 2: "Diet", 3:"Games"} def getdate(): import datetime return datetime.datetime.now() try: print("Select Client Name:") for key, value in client_list.items(): print(...
from abc import ABC, abstractmethod class Strain_2d(ABC): """ Implement a generic 2D strain rate method Strain_2d(grid_inc, strain_range, data_range) Parameters ------------- grid_inc : list of [float, float] xinc, yinc in degrees for the rectilinear grid on which strain is calculated...
#!/usr/bin/env python3 import os os.system("clear") print("") print("") print("Use this script to remove the random junk characters that youtube-dl") print(" adds to the end of mp3 filenames.") print("") print(" ____________________") print(" | ...
#!/usr/bin/env python class Libro: """Clase que modela un Libro""" # Atributos miembros de la clase contador = 0 # Metodo de inicializacion def __init__(self, isbn = '', autor = '', pags = 0): # Atributos de datos self.__isbn = isbn self.__autor = autor self.__p...
att = 0 ans1 = '' ans2 = '' ans3 = '' while ans1 != '19': ans1 = input('What is 9+10?') if ans1 == '19': print('Correct!') else: print('Wrong') att = att + 1 while ans2 != 'kcvi': ans2 = input('What is the best school?') if ans2 == 'kcvi': print('Correct...
temp = float(input('Temperature?')) print((temp - 32)*5/9,'celsius')
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ pre = ListNode(-1) pre.next ...
class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ pin2, pin = head, head while pin2 and pin2.next: pin, pin2 = pin.next, pin2.next.next if pin2 is pin: return True return False
class Solution(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums)<3: return True count,count2 = -1,-1 for i in range(1,len(nums)): if nums[i-1]>nums[i]: count = i-1 ...
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ for i in range(9): if not self.isValidList([board[i][j] for j in range(9)]) or not self.isValidList([board[j][i] for j in range(9)]): return F...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ return self....
import re def get_float(input_str="",text="", format_=float): while not re.match(r'^[+-]?\d{0,}\.?\d+$', input_str): # use construction try, except for input_str = input('Enter the value {0}: '.format(text)) if input_str == "" or input_str == " " or len(input_str) <= 0 or 'exit' in input...
""" You are in charge of a display advertising program. Your ads are displayed on websites all over the internet. You have some CSV input data that counts how many times you showed an ad on each individual domain. Every line consists of a count and a domain name. It looks like this: counts = [ "900,google.com", ...
""" Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", which the length is 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 ...
""" Given a sorted array of intergers and an target integer, return the index of the target integer. If the target in not found, return None. """ def binary_search(lst, num): left = 0 right = len(lst) - 1 while left <= right: mid = (left + right) / 2 if lst[mid] == num: return...
""" Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, yo...
# recursively def merge_sort_recursive(list1, list2, merged_list=None): """Merge 2 sorted lists in order recursively""" if merged_list is None: merged_list = [] if list1 and list2: if list1[0] < list2[0]: merged_list.append(list1.pop(0)) else: merged_list.app...
""" Implement the merge sort algorithm with optimal runtime. """ def merge_sort(lst): """Given an unsorted list, returns the sorted list using merging.""" if len(lst) < 2: return lst mid = len(lst) / 2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) return make_merge(left,...
import unittest """ Compute the nth fibonacci number. """ def compute_fibonacci(n): if n == 0 or n == 1: return n return compute_fibonacci(n - 1) + compute_fibonacci(n - 2) def compute_finonacci_memo(n, memo=None): if not memo: memo = [0] * (n + 1) if n == 0 or n == 1: ret...
# taylor expansion for cosine around 0 # cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - ... import numpy as np import matplotlib.pyplot as plt # Initialize range and number of terms xrange = np.arange(-10, 10, .1) print('\n\nThe Taylor Expansion of Cosine around 0 takes the form:\n' 'cos(x) = 1 - x^2/2! + x^...
def quick_sort(A,low,high): if low<high: pivot = partition(A,low,high) quick_sort(A,low,pivot-1) quick_sort(A,pivot+1,high) def partition(A,low, high): pivot= low swap(A,pivot,high) for i in range(low,high): if A[i]<=A[high]: swap(A,i,low) low +=1 swap(A,low,high) return low def swap...
#!/usr/bin/env python # 0 1 2 3 fruits = ['apple', 'cherry', 'orange', 'kiwi', 'banana', 'pear', 'fig'] # 012345678 name = "Eric Idle" # 0 1 2 knight = 'King', 'Arthur', 'Britain' print(fruits[3]) # <1> print(name[0]) # <2> print(knight[1]) # <3> p...
#!/usr/bin/env python x = ["bear"] x.extend(x) print(x) print(dir(x)) animals = ['bear', 'otter', 'wolf', 'moose'] print('\n'.join(animals)) # sep.join(SEQUENCE-of-STRINGS) print("/".join(animals)) for animal in animals: print(f"{animal}\n")
def string_comparison (first, second): if type (first) != str or type (second) != str : return 0 if first == second: return 1 if len(first) > len(second): return 2 if second == 'learn': return 3 return ('Такого условия нет') print ('Результат работы функции по прописанным переменным: ') print(strin...
ParentsList = ["latch","louise"] KidsList = ["daisy","ajay"] PetsList = ["ted","amos","cybil"] FamilyList = ParentsList + KidsList + PetsList print("random order:" + str(FamilyList)) FamilyList.sort() print ("alphabetical order:" + str(FamilyList))
""" *@file * *@brief The MainStarter class has main in it that runs the whole program. * You are able to do 6 things with the train line as detailed in the * description below. * * @author Raiza Soares * @mainpage Program - Python * * @description The program starts with displaying the menu. The use...
# You are given three integers: a, b, and m. Print two lines. # On the first line, print the result of pow(a,b). On the second line, print the result of pow(a,b,m). # Enter your code here. Read input from STDIN. Print output to STDOUT import math a = int(input()) b = int(input()) m = int(input()) print(pow(a,b)) pri...
import sqlite3 from sqlite3 import * connexion = sqlite3.connect("game.db") curseur = connexion.cursor() data = curseur.execute("SELECT * from Map;") table = [] for row in data: ligne = { 'name': row[1], 'nbuse':row[3], 'path':row[2] } table.append(ligne) print(table...
array = [10,9,8,7,6,5,4,3,2,1,11,12,13,16,15,14,17,19,18,20] n = len(array) for i in range(1,n): print(array) insertedValue = array[i] nextIndex = i - 1 while nextIndex >= 0: if insertedValue < array[nextIndex]: array[nextIndex+1] = array[nextIndex] else: bre...
# f = open("input.txt", 'r') # line = f.readline() line = input() num = int(line) array = [] for i in range(num): # line = f.readline() line = input() if not(line in array): array.append(line) array = sorted(array) array = sorted(array, key=lambda x:len(x)) for i in array: print(i)
from collections import defaultdict import collections # This class represents a directed graph using adjacency # list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edg...
import unittest import magic_sauce import os class HighestSuitibilityScoreTest(unittest.TestCase): # Read in test input file def setUp(self): test_input_file_dir = os.path.join(os.getcwd(), "TestInputFiles") self.simple_customer_input = os.path.join(test_input_file_dir, "simple_customer_input.txt") self.test...
# implementation od BFS algorithm in python graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } visited=[] queue=[] def bfs(visited,graph,source): visited.append(source) queue.append(source) while queue: s=queue.pop(0) print(s,end=' ') ...
''' Binary Search in python ''' import random import sys sys.setrecursionlimit(150000) def binarysearch(list,l,h,key): if h>=1: mid=(h-l)//2 if list[mid]==key: return mid elif list[mid]>key: return binarysearch(list,l,mid-1,key) else: return bina...
from random import randint class ChuteNumero: def __init__(self): self.ranking = [] self.iniciar() def iniciar(self): continuar_brincando = True while continuar_brincando: self.numero_aleatorio = randint(0, 1000) self.chute() decisao = input...