text
stringlengths
37
1.41M
#Programming exercises chapter 3 # exercise 10 # A program to determine the length of a ladder def main(): print("The length of a ladder required to reach a given height") import math from math import pi height = eval(input("Enter the height of the house: ")) angle = eval(input(" Enter the angle o...
# KMtoM # THis is a program that converts distances measured in kilometers to miles def main(): kilometers = eval(input("What is the length in kilometers? ")) miles = 0.62 * kilometers print("the lenght in miles is: ", miles) main()
# Programming exercises chapter 5 # exercise 9 # A program that counts the numbers of words in a sentence def main(): print("A program that counts the numbers of words") words = input("Enter a sentence: ") count = 0 for string in words.split(): count = count + 1 print("There are", count, "...
# Programming exercises chapter 7 # exercise 9 # A program for computing easter dates in the years 1982-2048 def main(): year = eval(input("Enter a year between 1982 and 2048: ")) if 1982 <= year <= 2048: a = year % 19 b = year % 4 c = year & 7 d = (19 * a + 24) % 30 e =...
# Programming exercises chapter 11 #exercise 10 # sieve of eratosthenes import math def main(): number = int(input("Please enter a number: ")) primes = [] for i in range(2,number+1): primes.append(i) i = 2 while(i <= int(math.sqrt(number))): if i in primes: for x in ran...
# Programming exercises chapter 3 # exercise 13 # A program to sum a series of numbers entered by the user def main(): print("The sum of a series of numbers.") n = int(input("How many numbers are to be summed: ")) sum = 0 for i in range(n): x = eval(input("Enter a natural number: ")) su...
# Programming exercises chapter 7 # exercise 2 def main(): score = eval(input("Enter your points: ")) if score == 5: print("A") elif score == 4: print("B") elif score == 3: print("C") elif score == 2: print("D") elif score <= 1: print("F") main()
#Programming exercises chapter 3 # exercise 5 # A program to calculate the cost of an order at the Konditorei coffee shop. def main(): print("A calculation for the cost of an order at the Konditorei.") pound = eval(input("How many pounds of coffee are you ordering: ")) total = pound * 10.50 + pound * 0.86...
x = 0 while x <= 5: print(x) x = x + 1 counties = ["Arapahoe", "Denver", "Jefferson"] for county in counties: print(county) numbers = [0,1,2,3,4] for num in numbers: print(num) for i in range(len(counties)): print(counties[i]) counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jeffers...
import math class Buffer(object): def __init__(self, source): self.index = 0 self.source = source self.lines = [] self.current_line = () self.current() def pop(self): current = self.current() self.index += 1 return current @property def mo...
from collections import namedtuple CitiesRow = namedtuple("Row", ["latitude", "longitude", "name"]) cities = [CitiesRow(38, 122, "Berkeley"), CitiesRow(42, 71, "Cambridge"), CitiesRow(43, 93, "Minneapolis")] DistancesRow = namedtuple("Row", ["name", "distance"]) def select(cities_row): latit...
empty = 'empty' def mutable_link(): """Return a functional implementation of a mutable linked list.""" contents = empty def dispatch(message, value = None): nonlocal contents if message == 'len': return len_link(contents) elif message == 'getitem': return geti...
#__*__ encoding:utf8 __*__ """12. Leia vários códigos do jogador (1 ou 2) que ganhou o ponto, em uma partida de pingue-pongue, e responda quem ganha a partida. A partida chega ao final se: · Um dos jogadores chega a 21 pontos e a diferença de pontos entre os jogadores é maior ou igual a 2. · Se a primeira não for ...
def main(): idade = input('digite sua idade: ') soma_idade_otimo = 0 qtd_otimo = 0 qtd_regular = 0 qtd_total = 0 qtd_bom = 0 while idade > 0: op = int(input('digite sua opniao: ')) qtd_total = qtd_total + 1 if op == 1: soma_idade_otimo = soma_idade_otimo + idade qtd_otimo = qtd_otimo + 1 elif op ==...
"""43. Um sistema de equacoes lineares do tipo , pode ser resolvido segundo mostrado abaixo Escreva um algoritmo que leia os coeficientes a, b, c, d, e e f, calcule e escreva os valores de x e y.""" a = input ('Digite o valor de a: ') b = input ('\nDigite o valor de b: ') c = input ('\nDigite o valor de c: ') d ...
from Questao06_funcoes import * def main(): bd_alunos = [] bd_alunos += inicializar_alunos() while True: menu = ' 1 - Listar \n 2 - Buscar \n 0 - Sair \n Opcao: ' opcao = int(input(menu)) if opcao == 1: while True: menu1 = ' 1 - Listar tabela com as notas, media e situacao \n'\ ' 2...
"""13. Leia N e uma lista de N numeros e escreva o maior numero da lista.""" def main(): numero_n = input('Digite o valor de N: ') maior = 0 for i in range(1,numero_n+1): lista_numero_n = input('Digite um numero: ') if i == 1: maior = lista_numero_n else: if lista_numero_n > maior: maio...
def main(): n_1 = 1 n_2 = 1 total = 0 for i in range(50): print('%d/%d' % (n_1, n_2)) total = total + (n_1/n_2) n_1 += 2 n_2 += 1 print('Total : %.2f.' % total) if __name__ == '__main__': main()
#__*__ encoding:utf8 __*__ """16. O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira: Até 5 Kg Acima de 5 Kg File 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 ap...
def calcula_salario(qtd_horas, valor_hora): salario = qtd_horas * valor_hora return salario def main(): print '$$$ Calcula Salario $$$' valor_hora_prof1 = input('Valor do hora Prof1: ') qtd_horas_prof1 = input('Horas Prof1: ') valor_hora_prof2 = input('Valor do hora Prof2: ') qtd_horas_prof2 = input('Horas Pro...
"""4. Leia o valor do dolar e um valor em dolar, calcule e escreva o equivalente em real (R$).""" cotacao = input("Digite a cotacao: ") valor_dolar = input("Digite o valor em dolar: ") valor_reais = cotacao * valor_dolar print "O valor %.2f dolares com cotacao a %.2f equivale a %.2f reais" %(valor_dolar, cotacao, valo...
def verifica_data(dia,mes,ano): if dia > 0 and dia <= 31: if mes > 0 and mes <= 12: if ano > 0: return "data valida" return "data invalida" def main(): print 'programa verifica data valida:' dia = int(raw_input('digite o dia: ')) mes = int(raw_input('digite o mes: ')) ano = int(raw_input('d...
#__*__ encoding:utf8 __*__ """1. Leia uma velocidade em m/s, calcule e escreva esta velocidade em km/h. (Vkm/h = Vm/s * 3.6)""" def calcula_velocidade(velocidade): velocidade_total = velocidade * 3.6 return velocidade_total def main(): velocidade = input ('Digite a velocidade em m/s: ') velocidade_total = 0...
""" Numero pares entre 1 e N """ def main(): qtd = input('N: ') for i in range(2, qtd+1, 2): print i if __name__ == '__main__': main()
#__*__ encoding:utf8 __*__ """9. Leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda etc.), se digitar outro valor deve aparecer valor inválido.""" def main(): numero = input('Digite um numero: ') if numero == 1: print('Domingo') elif numero == 2: print('Segunda') elif numero...
def main(): palavra = raw_input('Palavra: ') letra = raw_input('Letra: ') contador = 0 for l in palavra: if letra == l: contador += 1 print 'Qtd = %d' % contador if __name__ == '__main__': main()
"""17. Leia valores inteiros em duas variaveis distintas e se o resto da divisao da primeira pela segunda for 1 escreva a soma dessas variaveis mais o resto da divisao; se for 2 escreva se o primeiro e o segundo valor sao pares ou impares; se for igual a 3 multiplique a soma dos valores lidos pelo primeiro; se for ig...
"""26. Leia um numero inteiro de dias, calcule e escreva quantas semanas e quantos dias ele corresponde.""" dias = input ('Digite um valor inteiro de dias: ') semanas = dias / 7 dias1 = dias % 7 print ('\nO equivalente em semanas e dias de %d dias e %d semanas e %d dias ') % (dias,semanas,dias1)
"""17. Leia o valor da base e altura de um retangulo, calcule e escreva sua area. (area = base * altura)""" base = input ('Digite o valor da base de um retangulo : ' ) altura = input ('Digite o valor da altura de um retangulo: ') area = base * altura print ('\nA area do retangulo e %.2f') % (area)
#__*__ encoding:utf8 __*__ """4. Leia uma frase e gere uma nova frase, duplicando cada caractere da frase digitada.""" def main(): frase = raw_input('Digite uma frase: ') nova_frase = '' for letra in frase: nova_frase += frase.replace(frase,letra*2) print nova_frase if __name__ == '__main__': main()
#By E. def main(): num1, num2 = input('N1: '), input('N2: ') resultado = mmc(num1, num2) print 'MMC = %d' % resultado def mmc(numero1, numero2): multiplo = 1 while True: if multiplo % numero1 == 0 and multiplo % numero2 == 0: return multiplo else: multiplo = multiplo + 1 if __name__ == '__main__': ...
"""29. Escreva um algoritmo que calcula o retorno de um investimento financeiro. O usuario deve informar quanto sera investido por mes e qual sera a taxa de juros mensal. O algoritmo deve informar o saldo do investimento apos um ano (soma das aplicacoes mensais + juros compostos), e perguntar ao usuario se deseja ca...
"""15. Leia o valor da base e altura de um triangulo, calcule e escreva sua area. (area=(base * altura)/2)""" base = input ('Digite o valor da base de um triangulo: ' ) altura = input ('\nDigite a altura de um triangulo: ') area = (base * altura) / 2 print ('\nA area do triangulo e %.2f') % (area)
def main(): palavra = raw_input('Frase: ') for i in range(len(palavra)): contador = 0 for j in range(i+1, len(palavra)): if palavra[i] == palavra[j]: print 'Letra %s Repetida' % palavra[i] if __name__ == '__main__': main()
""" Progressao Geometrica """ def main(): inicio = input('Inicio: ') limite = input("Limite: ") razao = input("Razao: ") atual = 1 print atual, ultimo = atual for i in range(inicio, limite + 1): atual = ultimo * razao if atual <= limite: print atual, ...
"""11. Leia LimiteSuperior e LimiteInferior e escreva todos os numeros primos entre os limites lidos.""" from math import sqrt as raiz def main(): limite_inferior = input('Digite o limite inferior: ') limite_superior = input('\nDigite o limite superior: ') print('Os numeros primos entre %d e %d ') % (limite...
"""15. Leia a quantidade de horas aula dadas por dois professores e o valor por hora recebido por cada um. Escreva na tela qual dos professores tem salario total maior.""" def main(): horas_prof1 = input ('Digite a quantidade de horas aula dadas pelo professor 1: ') valor_horas_prof1 = input ('\nDigite o valor da...
def main(): quantidade_teste = int(input('Quantidade de teste: ')) for i in range(quantidade_teste): valores = input('Valores de X e Y: ').split(' ') valor_x = int(valores[0]) valor_y = int(valores[1]) funcao_r = ((3*valor_x)**2) + (valor_y**2) funcao_b = (2*(valor_x**2)) + ((5*valor_y)**2) funcao_c = (-1...
# # Zaimplementuj iterator zwracający jedynie samogłoski z zadanego ciągu znaków: # ​ # Przykładowe użycie: # for char in Vowels('ala ma kota a kot ma ale'): # class Vowels: def __init__(self, sentence: str): self.sentence = sentence self.vowels = ['a', 'ą', 'e', 'ę', 'i', 'o', 'u', 'y'] def __...
x = list(range(1, 11)) print(x) print([el ** 3 for el in x]) print([el ** 3 for el in x if el % 2 ==0]) print({el ** 3 for el in x if el % 2 ==0}) # zbiór print({el: el ** 3 for el in x if el % 2 ==0}) # slownik print(tuple(el ** 3 for el in x if el % 2 ==0)) # tuple # zadania print([x / 10 for x in range(11)])
def more_than(example_text, counter): results = set() for sign in set(example_text): if example_text.count(sign) > counter: results.add(sign) return results print(more_than('ala ma kota a kot ma ale', 2)) print(more_than('aaa bbb', 2)) def test_more_than(): assert more_than('aaa',...
word = 'podaj slowo lub zdanie:' dict1 = dict() for sign in word: dict1[sign] = dict1.get(sign, 0) + 1 for znak, ilosc in dict1.items(): print(f'{znak} -> {ilosc}') from collections import defaultdict zliczenia = defaultdict(int) for znak in word: zliczenia[znak] += 1 print("333: ", zliczenia)
# ### Zadanie 1.1 | Interakcja i proste obliczenia (ok. 2 godz.) # ​ # Napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków. Niech program # policzy i wyświetli, ile trzeba będzie zapłacić za pięć kilo ziemniaków. # ​ # Potem napisz program, który prosi użytkownika (przez ...
# В этом модуле описывается функция, которая возвращает список имен брендов. Имена брендов в этом списке пишутся # ЗАГЛАВНЫМИ буквами! Список формируется на основе значений, указанных построчно в файле Database\Config\list_brands.txt def getBrandNames(): BRANDS = [] with open('Database\Config\list_brands.txt',...
import Structure import Player import Bot import random class Main: isPlayerTurn = False isBotTurn = False playerSymbol = '' botSymbol = '' def __init__(self, row, col, defVal, botname): self.board = Structure.Board(row, col, defVal) playerName = input('Enter your Na...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by weizhenjin on 17-2-7 def b(fn): return lambda s: r'<b>%s<\b>' % fn(s) def em(fn): return lambda s: r'<em>%s<\em>' % fn(s) @b @em def greet(name): return 'Hello %s' % name def sayhi(name): return 'Hi %s' % name sayhi = em(sayhi) sayhi =...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by weizhenjin on 17-2-22 def as_pandas(cursor): """Return a pandas `DataFrame` out of an impyla cursor. This will pull the entire result set into memory. For richer pandas-like functionality on distributed data sets, see the Ibis project. Parame...
from socket import * import sys msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailServer mailServer = 'localhost' # using private testing SMTP server mailPort = 1010 # port number # Create socket called clientSocket and establish a TCP c...
''' PLANNNING print("Let's find out who your bestie is in BTS!") print('What do you like doing in your free time?') print("Please type in a letter based on the selection below.\n" + "Fishing 1\n" + "Taking a walk in the park 3 Gaming 5 Sleeping 7 Travel to other countries 9 What is your favorite food? ...
# Person Class class Person: # Constructor def __init__(self, id, fname, lname): self.id = id self.fname = fname self.lname = lname # Display first name and last name of person. def displayDetails(self): print("Name:", self.fname, self.lname) # Student Class class Stud...
import math def is_accurate_enough(num1, num2, accuracy): # we use abs so we don't have to care about the order of the 2 numbers if (abs(num1 - num2) < accuracy): return True else: return False def calculate_e(accuracy): # we initialize e_previous to a dummy value # so we can ente...
# MAINMENU Main script to run the bacterial analysis program utilizing # the functions of the other files imported from the same directory ## # Usage: mainMenu() ## # Author: Thomas B. Frederiksen, s183729@student.dtu.dk, 2020 import os.path folder = os.path.dirname(os.path.abspath(__file...
class planet(object): def __init__(self, name, color, planetType): self.name = name self.color = color self.planetType = planetType def print(self): return f"Name: {self.name}, Color: {self.color}, Planet Type: {self.planetType}" ...
#!/bin/python3 import os import sys # Complete the totalForecastInaccuracy function below. def totalForecastInaccuracy(t, f): first = [1,2,3,4,5,6,7] second = [1,2,3,4,5,6,7] three = map(lambda x, y: x+y,first,second) print(9) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH...
class Person: def __init__(self,name,age,telephone): self.name=name self.age=age self.telephone=telephone def pick_up(self,person): print(f"{self.name} pick up {person}") class Telephone: def __init__(self, brand,color,price,owner): self.brand = brand se...
""" Public Data Hacking Total number of registered automobiles in Romania in 2017 1. Top 5 counties by number of registered cars 2. Top 5 car brands in a user defined county, and also the percentage compared to the whole country. 3. A lot of possibilities... Mostly an excuse to play with Python's list comprehe...
#import os # #x=[d for d in os.listdir('.')] #print(x) #输出任意目录下的文件(例如 C:\) import os #def fun(): # return [d for d in os.listdir('.')] #def fun(x,y): # L=[] # for d in os.listdir(x): # if d != y: # L.append(d) # return L # # #if __name__ == '__main__': # path=input('Please input a...
b=input("Please input one number:") a=int(b) if a>=0: print(a) else: print(-a)
import random def Sieves(): n1=random.randint(1, 6) n2=random.randint(1, 6) return n1,n2 def run(): sum1=0 sum2=0 for i in range(10): s1,s2=Sieves() print("(第%d次)玩家1:筛子A:%d 筛子B:%d 总分:%d"%(i+1,s1,s2,sum1+s1+s2)) sum1=sum1++s1+s2 c1,c2=Sieves() print("(第...
##Nhan Nguyen class BankingAccount: def __init__(self): self.balance = 0 print(15* " ","Welcome to Illinois TechCash Service") def get_balance(self): return self.balance def deposit(self): #deposit to balance amount_d = float(input("Enter amount to be Deposited: ")) ...
#closures:-function returning func def power(x): def base(a): return a**x return base var=power(7) print(var(4))
##any and all l=[2,3,4,6,8,10] a=[] for i in l: a.append(i%2==0) print(all(a))
##label 1 ##label 2 ## ##add sub div mul ## ##result in entry box import tkinter as tk from tkinter import ttk from tkinter import * win=tk.Tk() win.title("Calculator") win.geometry('600x400+500+200') win.configure(background="blue") ##win.wm_attributes('-transparentcolor','black') ## ##filename = PhotoI...
def fact(a): if a==1: return 1 else: return a * fact(a-1) num=int(input("NUMBER:")) print(fact(num)) #print (x)
##comprehension l=[i for i in range(1,11)] print (l) l1=[i for i in range(1,11) if i%2==0 ] print (l1) d={i:i**3 for i in range(1,11)} print (d) s={i for i in range(1,15,2)} print (s) g=(i for i in range(2,20,2)) ##generator print (g) for i in g: print (i, end=" ")
list = [("student1", "A"),("student2", "B"),("student3","A"),("student4","F"),("student5","D"),("student6","B")] dict={} dict['A'] = [] dict['B'] = [] dict['C'] = [] dict['D'] = [] dict['F'] = [] while list: dict[list[0][1]].append(list.pop(0)[0]) print(dict)
number = input() if len(number) < 4: while len(number) < 4: number = "0" + number part1 = number[0:2] part2 = number[3] + number[2] if int(part1) == int(part2): print(1) else: print(0)
def min4(a, b, c, d): min1 = min(a, b) min2 = min(c, d) return min(min1, min2) a = input() b = input() c = input() d = input() print(min4(a, b, c, d))
now = int(input()) max = 0 i = 0 while now != 0: if now == max: i += 1 elif now > max: max = now i = 1 now = int(input()) print(i)
n = int(input()) k = 0 while 2**k < n: k += 1 else: print(k)
# coding: utf-8 # Author: gjwei """ 冒泡排序法 """ def bubble_sort(nums): has_sorted = False for i in range(0, len(nums)): if has_sorted: break has_sorted = True for j in range(0, len(nums) - i - 1): if nums[j + 1] < nums[j]: has_sorted = False ...
# coding: utf-8 # 从1到n整数中,1出现的次数 def count1s(n): if n == 0: return 0 if n < 10: return 1 n = str(n) head = int(n[0]) tail = int(n[1:]) if head == 1: return count1s(10 ** (len(n) - 1) - 1) + tail + 1 + count1s(tail) else: return head * count1s(10 ** (len(n)...
# coding: utf-8 # Author: gjwei class Heap(object): """大根堆""" def __init__(self, nums): self.heap = nums def sink(self, index): while 2 * index + 1 < len(self.heap): c = 2 * index + 1 # Compare parent to the larger child if c + 1 < len(self.heap) and se...
# coding: utf-8 # Author: gjwei """ 选择排序:每次选择出数据中最小的元素,和第一个元素进行交换。然后从剩下的元素中选择最小的,和第二个元素交换位置 依次进行下去 """ def select_sort(nums): for i in range(len(nums)): min_index = i for j in range(i, len(nums)): if nums[j] < nums[min_index]: min_index = j nums[i], nums[min_inde...
# coding: utf-8 def power(num, k): if k < 0: return 1 / power(nums, -k) result = 1 while k > 0: if k & 1 == 1: result *= num k -= 1 else: result *= result k //= 2 return result print(power(5, 3))
# coding: utf-8 # Author: gjwei def swap_nums(a, b): a = a - b b = a + b a = b - a return a, b def swap_nums_2(a, b): a = a ^ b b = a ^ b a = a ^ b return a, b
""" title: Error_Catch_Pratice author: sxv3240 date: 1/7/2019 2:36 PM """ # try: # print(4 +spam +4) # # except NameError as error: # print("Hey,that's not cool!", error) # # try: # print("2" + spam + 15) # except (NameError, TypeError): # print("Very sorry, we are unable to evaluate yo...
""" title: macaw_math author: sxv3240 date: 1/7/2019 1:32 PM """ import math # percent_of_weight = 1/3 # coconut_weight = 1450 # macaw_weight = 900 # number_of_macaws = coconut_weight / (macaw_weight * percent_of_weight) # # print(math.ceil(number_of_macaws)) # name = input("What's your name?") # print(f"Hello ,{na...
#!/usr/bin/env python3 # Challenge 3 solution # One small letter, surrounded by EXACTLY three big bodyguards on each of its sides. #################################### # Dependencies: # 1. Beautiful Soup # 2. UrlLib # 3. re #################################### import bs4 from urllib.request import urlopen as uReq ...
''' This problem was asked by Facebook. Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. ''' import numpy as np arr = list(map(int, input().split())) #simulate input stream for i in arr: if np.random.randint(2) == 0: print(i) #Proba...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Signs a URL using a URL signing secret """ ##对签名进行验证代码 import hashlib import hmac import base64 import urllib.parse def sign_url(input_url=None, secret=None): """ Sign a request URL with a URL signing secret. Usage: from urlsigner import sign_url signed...
import unittest from HW07_Neil_Gupte import HW07 from typing import * class AnagramListTest(unittest.TestCase): """ test anagram list function""" def test_anagram_list(self)->None: a:str="hello" b:str="loleh" self.assertEqual(HW07.anagrams_lst(a,b),True) self.assertEqual(HW07.an...
#! /usr/bin/python3 entero = int(input('Digite un numero entero: ')) entero2 = entero + 1 caracter = input('Digite un caracter: ') while entero > 0: entero = entero - 1 while entero < entero2: for x in range(entero): print(caracter,end='') print() entero = entero + 1
import sqlite3 import os class main: def checkuser(obj): user_id = obj.getId() password=obj.getPassword() if os.path.exists("Mydb"): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT id,password,name FROM users WH...
def f(a, b): a += b return a x = 1 y = 2 f(x, y) x, y a = [1, 2] b = [3, 4] f(a, b) a, b t = (10, 20) u = (30, 40) f(t, u) t, u
"""Example 7-8""" class Averager: def __init__(self): self.series = [] def __call__(self, new_value): self.series.append(new_value) total = sum(self.series) return total/len(self.series) avg = Averager() avg(10) avg(11) avg(12)
"""Example 16-13 A coroutine to compute a running average >>> coro_avg = averager() 1 >>> from inspect import getgeneratorstate >>> getgeneratorstate(coro_avg) 2 'GEN_SUSPENDED' >>> coro_avg.send(10) 3 10.0 >>> coro_avg.send(30) 20.0 >>> coro_avg.send(5) 15.0 """ from colle...
""" This the declarative model for the first scenario to test and compare several algorithms. In this planning domain, an automomous agent must travel through a 2D grid-map avoiding obastacles which have been modeled as dead-ends. That is to say, states from which it is impossible to leave thus the agent will n...
#!/usr/bin/env python3 # Created by Ryan Nguyen # Created on January 2021 # This program uses functions to create # a mailing address def Construct_address(addressee, street_number, street_name, city, province, postal, apartment=None): # puts the mailing address together address = ad...
""" Problem Link: https://practice.geeksforgeeks.org/problems/sort-a-stack/1 Given a stack, the task is to sort it such that the top of the stack has the greatest element. Input: The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an in...
""" Given a stream of characters consisting only '0' and '1', print the last index of the '1' present in it. Input stream may either be sorted in decreasing order or increasing order. If not present than print "-1". Input: First line of the input contains the number of test cases (T) , T lines follow each containin...
""" Problem Link: https://practice.geeksforgeeks.org/problems/missing-number-in-array/0 Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. Input: The first line of input contains an integer T denoting the number of test cases. For eac...
""" Problem Link: https://practice.geeksforgeeks.org/problems/alone-in-couple/0 In a party everyone is in couple except one. People who are in couple have same numbers. Find out the person who is not in couple. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/element-appearing-once2552/1 Given a sorted array A[] of N positive integers having all the numbers occurring exactly twice, except for one number which will occur only once. Find the number occurring only once. Example 1: Input: N = 5 A = {1, 1, 2, 5, 5...
""" Given an integer array, for each element in the array check whether there exist a smaller element on the next immediate position of the array. If it exist print the smaller element. If there is no smaller element on the immediate next to the element then print -1. Input: The first line of input contains an integ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/series-gp/0 Given the first 2 terms A and B of a Geometric Series. The task is to find the Nth term of the series. Input: First line contains an integer, the number of test cases 'T'. T testcases follow. Each test case in its first line contains two posit...
""" Problem Link: https://practice.geeksforgeeks.org/problems/consecutive-elements/0 For a given string delete the elements which are appearing more than once consecutively. All letters are of lowercase. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, a stri...
""" Problem Link: https://practice.geeksforgeeks.org/problems/pascal-triangle/0 Given a positive integer K, return the Kth row of pascal triangle. Pascal's triangle is a triangular array of the binomial coefficients formed by summing up the elements of previous row. Example : 1 1 1 1 2 1 1 3 3 1 For K = 3, return 3rd...
""" Problem Link: https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1 Given a singly linked list of N nodes. The task is to find middle of the linked list. For example, if given linked list is 1->2->3->4->5 then output should be 3. If there are even nodes, then there would be two mi...
""" Problem Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/maximize-the-earning-137963bc-323025a6/ """ def rupeesEarned(buildings,cost): height = -1 count = 0 for building in buildings: if building > height: count += 1 height...