text
stringlengths
37
1.41M
# Problem: # Reference: https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&contestProbId=AWD3Y27q3QIDFAUZ&categoryId=AWD3Y27q3QIDFAUZ&categoryType=CODE&problemTitle=&orderBy=FIRST_REG_DATETIME&selectCodeLang=PYTHON&select-1=3&pageSize=10&pageIndex=6 # My Solution: answer = [1 for _ in range(...
# Problem: # Print how many times the string appears in the given sentence. # My Solution: answer = [] for i in range(10): tn = int(input()) toFind = input() fromString = input() answer.append(fromString.count(toFind)) for i in range(len(answer)): print("#{} {}".format(i + 1, answer[i]))
# Problem: # Given a list of phone numbers, return true if any phone number is not the part of other phone number's head or false. # My Solution: def solution(phone_book): phone_book.sort() for i in range(len(phone_book) - 1): temp1 = phone_book[i] for j in range(i + 1, len(phone_book)): ...
# Problem: # Given a string and a number 'n', Return an encrypted string that pushes each alphabet of one sentence to another by a certain distance. # My Solution: def solution(s, n): answer = '' for a in s: if a == ' ': answer += a continue elif ord(a) in range(ord('A'...
# Problem: # Given the number of students and the number of students who submitted the assignment, print the number of students who did not submit the assignment in ascending order. # My Solution: T = int(input()) for i in range(T): N, K = map(int, input().split()) S = list(map(int, input().split())) print...
# Problem: # Given a list of integers, return a list that the same number does not com out in a row. # My Solution: def solution(arr): pre = -1 answer = [] for num in arr: if pre == num: continue else: pre = num answer.append(num) return answer
# Problem: # Given the range of number, return the number of prime numbers. # My Solution: def solution(n): answer = 0 isprime = [True for i in range(n)] for num in range(2, int(n ** 0.5) + 1): if isprime[num - 1]: for i in range(num + num, n + 1, num): isprime[i - 1] = ...
# Problem: # Print out the rock, paper, scissors winner. # Condition(s): # 1. 1 is the scissors. # 2. 2 is the rock. # 3. 3 is the paper. # My Solution: A, B = map(int, input().split()) if A > B: if B == 1 and A == 3: print('B') else: print('A') else: if A == 1 and B == 3: print('A'...
# Problem: # Given the string(s), print if it is palindrome. # My Solution: T = int(input()) for i in range(T): string = list(input()) print("#{}".format(i + 1), end=" ") if string == list(reversed(string)): print(1) else: print(0)
# Problem: # Print the n-th fibonacci number. # My Solution: import sys fibo = [0 for _ in range(91)] fibo[1] = 1 for i in range(2, len(fibo)): fibo[i] = fibo[i - 1] + fibo[i - 2] n = int(sys.stdin.readline().rstrip()) print(fibo[n])
# Problem: # Reference: https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&contestProbId=AWMedCxalW8DFAXd&categoryId=AWMedCxalW8DFAXd&categoryType=CODE&problemTitle=&orderBy=FIRST_REG_DATETIME&selectCodeLang=PYTHON&select-1=3&pageSize=10&pageIndex=5 # My Solution: T = int(input()) for i in r...
# Problem: # Given a number, print the sum of the numbers from 1 to the given number. # My Solution: N = int(input()) total = 0 for i in range(1, N + 1): total += i print(total)
# We'll put some classes here. # Yup, we sure will! import collections def responds_to(instance, func): return isinstance(getattr(instance, func, None), collections.Callable) class Cat(): # This is a class variable or a "class attribute" num_legs = 4 def __init__(self, name): # self.name is c...
import random def quick_sort_easy(arr): if len(arr) <= 1: return arr pivot = random.randint(0, len(arr) - 1) less = [] greater = [] for index, value in enumerate(arr): if index == pivot: continue if value <= arr[pivot]: less.append(value) ...
class Foo: def __str__(self): return "foo object in string 的格式" def __repr__(self): return "foo object in repr 的格式" f1 = Foo() print(f1) print((f1,)) print([f1]) print({f1}) print('%s, %r, %a' % (f1, f1, f1)) print('{0!r}, {0!s},{0!a}'.format(f1))
rut = input('ingrese rut: ') lista = [int(i) for i in rut if i.isdigit()] print(lista) lista.insert(2,'.') lista.insert(6,'.') lista.insert(10,'-') print(lista) i=0 listaStr =[] while(i<12): listaStr.append(str(lista[i])) i=i+1 listaFinal =''.join(listaStr) print(listaFinal)
print('╔════════╦═════════════╦═══════════╗') print('║ CODIGO ║ NOMBRE DPTO ║ DESCUENTO ║') print('╠════════╬═════════════╬═══════════╣') print('║ 1 ║ DAMA ║ 30% ║') print('║ 2 ║ VARON ║ 05% ║') print('║ 3 ║ NIÑO ║ 20% ║') print('║ 4 ║ ELECTRO ║ 15%...
""" 3408. 세가지 합 구하기 """ # def three(n): # return int(n*(n+1)/2), n**2, n*(n+1) for t in range(int(input())): n = int(input()); a = n*(n+1)//2; e = a*2; o = e-n print(f'#{t+1} {a} {o} {e}')
import nltk nltk.download('wordnet') def tokenize(text): return nltk.word_tokenize(text) if __name__ == '__main__': test_string = 'alices adventures in wonderland commonly shortened to alice ' \ 'in wonderland is an one thousand eight hundred and sixty five ' \ 'novel wr...
aliensDictionary = {"we": "vorag", "come": "thang", "in": "zon", "peace": "argh", "hello": "kodar", "can": "znak", "i": "az", "borrow": "liftit", "some": "zum", "rocket": "upgoman", "fuel": "kakboom", "please": "selpin", "don't": "baaaaaaaaaaaarn", "shoot": "flabil", "welcome": "unkip", "our": "mandig", "new": "bran...
fruits = ['Apples', 'Oranges', 'Bananas', 'Strawberries', 'Raspberries'] fruits_with_g = [] for i in range(len(fruits)): if i % 2 == 1 and str('g') in fruits[i]: fruits_with_g.append(fruits[i]) print(fruits_with_g)
def my_method(arg1, arg2): return arg1 + arg2 my_method(5, 6) def my_log_method(arg1, arg2, arg3, arg4): return arg1 + arg2 + arg3 + arg4 def my_list_adddition(list_args): return sum(list_arg) my_long_method(3,5,7,12) my_list_adddition([3,5,7,12,15,234,23]) def addition_simplified(*args): return s...
class Queue: def __init__(self): self.queue = [] def is_empty(self): return self.queue == [] def size(self): return len(self.queue) def enqueue(self, data): self.queue.append(data) def dequeue(self): data = self.queue[0] del self.queue[0] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 19 22:06:37 2020 @author: aliciachen """ # code that gives your age, given year you were born! birth_year = int(input("What year were you born?")) current_year = int(input("What year is it right now?")) age = current_year - birth_year print("You...
print('hello world') x=5.0/2 print(x) if x>3: print("small") else: print('big') array=[1,1,2,3,5,8] for val in array: print(val) sum=0 position=0 while position<len(array): sum = sum + array[position] position= position + 1 print(sum) hash = {'a':125637, 'b':43876} print(hash) sum = 0 fo...
#!/usr/bin/env python """ SYNOPSIS random_pass_gen.py No command line arguments involved. DESCRIPTION Enter a number between 8 and 16, a randomised password will be output. EXAMPLES User enters a number of 13. Output should give a randomised password, such as 'iuuqfAFWQF&2;'. AUTHOR J...
#!/usr/bin/env python """ SYNOPSIS Caesar.py No command line arguments involved. DESCRIPTION Enter a plaintext message and then the rotation key. The plaintext is then converted to cypher text and saved to a file. EXAMPLES User enters 'Hello!' and a key of 13. Output should give 'Uryyb!' an...
import time from binary_search_tree import BinarySearchTree start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] # Return th...
def first(n): return str(n)[0] def last(n): return str(n)[-1] def middle(n): return str(n)[1:-1] def is_palindrome(n): if len(str(n)) <= 1: return True if first(n) != last(n): return False else: return is_palindrome(middle(n)) if __name__ == '__main__': palindr...
""" @author: Sebastian Cepeda @email: sebastian.cepeda.fuentealba@gmail.com """ import numpy as np def line_from_2_points(x1, y1, x2, y2): """ Gets the coefficients of a line, given 2 points :param x1: :param y1: :param x2: :param y2: :return: """ a = y1 - y2 b = x2 - x1 c...
import random import sys import os import time os.system('clear') deck = ['A',2,3,4,5,6,7,8,9,10,10,10,10] user_cards_drawn = [] computer_cards_drawn = [] sum_user = 0 sum_computer= 0 withdraw = False blackjack = False A_counter = 0 def user_continue(user_cards_drawn,how_many=1): global sum_user,A_counter, black...
class BaggingClassifier(): def __init__(self, base_estimator, n_estimators=100): ''' :param base_estimator: The base estimator model instance from which the bagged ensemble is built (e.g., DecisionTree(), LinearRegression()). You can pass the object of the estimator c...
# Cipher's Symbol Set SYMBOL_SET = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`a bcdefghijklmnopqrstuvwxyz{|}~' SYMBOL_SET_SIZE = len(SYMBOL_SET) def cipher(mode, message, key): result = '' for symbol in message: if symbol not in SYMBOL_SET: raise ValueError("Symbol...
''' Basic Definitions: test ''' import random items = [] on = 90 off = 91 win = 92 lose = 93 game = on alive = True ''' Defining all the locations: ''' city = "City" forest = "Forest" forest_nw = "Northwestern Forest" huntershack = "Hunter's Shack" blacksmith = "Blacksmith's shop" cave = "Mined ...
import unittest """ https://www.codewars.com/kata/52597aa56021e91c93000cb0/train/python """ def move_zeros(array): n_array = [n for n in array if n != 0] temp = [n for n in array if n == 0] # n_list = n_array + temp return n_array + temp class TestSimple(unittest.TestCase): def test_simple(sel...
import os import sys import pdb try: file_name = sys.argv[1] output_file = file_name.split('.')[0]+'.out' except(IndexError): sys.exit("Please enter a valid file name") matching_word_positions = {} def reading_file_input(file_name): with open(file_name, 'r') as file: lines = file.readlines()...
# -*- coding: utf-8 -*- """ Created on Sat Jan 30 19:34:19 2021 @author: zhangyuanqi """ sum=0 for number in range(2,101,2): sum=sum+number print(sum)
###Correct code '''output Highest palindrome formed by product of two 3-digit numbers 995,911 is 906609 real 0m0.846s user 0m0.832s sys 0m0.012s''' n=3 palindrome=[] for i in range(10**(n-1),10**(n)): for j in range(10**(n-1),10**(n)): temp=str(i*j) z=0 for k in range(0,len(temp)/2): if(temp[k]!=temp[len(...
'''input:-- output:- a= 10 b= 20 c= 30 d= 20 b= 20 c= 30 description:Implementation of global and local variable date: 03-09-2021 Author name: Shruti Nahar''' a=10 def fun(b): c=30 print("a=",a) print("b=",b) print("c=",c) fun(20) """ to access global variable inside a function use...
'''input:-- output:Num1 + Num2= 30 Num1 - Num2= -10 Num1 * Num2= 200 Num1 / Num2= 0.5 5^3= 125 20%3= 2 22//7= 3 description:perform Arithmetic Operation date: 24-08-2021 Author name: Shruti Nahar''' num1=10 num2=20 print("Num1 + Num2= ",num1+num2) print("Nu...
'''input:- madam Output:-Palidrome Description: Check the string is palidrome or not Date: 27-08-2021 Author name: Shruti Nahar''' def palidrome(num): x=num[::-1] if(x==num): print("Palidrome") else: print("Not a Palidrome ") palidrome("madam ")
'''input:- -- output:- (1, 2, 3) 1 2 3 MUMBAI (1, 2, 3, 'MUMBAI') 1 (1, 2, 3, 'MUMBAI') A (1, 2, 3, 4, 5, 6) (1, 2, 3, ['english', 'python']) 1 3 ('physic', 'chemistry', 1987, 8976) (1, 2, 3, 4, 5) ('a', 'b', 'c', 'd') () (50,) tup1[0]: physic tup2[1:5]: (2, 3, 4, 5) (12, 34.56, 'ab...
'''input:- -- output:- {1: 'apple', 2: 'ball'} Accessing element apple len() 2 key() dict_keys([1, 2]) values() dict_values(['apple', 'ball']) dictionary {1: 'apple', 2: 'ball'} items() dict_items([(1, 'apple'), (2, 'ball')]) update() {1: 'apple', 2: 'ball', 3: 'apple'} get() apple pop() ball {1: '...
#!/usr/bin/env python # coding: utf-8 import sys, re def Name(line): raw_Kanji = ur'[一-龠]+' raw_Hiragana = ur'[ぁ-ゞ]+' raw_Katakana = ur'[ァ-ヾ]+' raw_Setsubiji = ur'(くん|きゅん|君|さん|ちゃん|様|殿|たん|氏|マン|夫人|先生|選手)' name_pattern = re.compile(ur'(%s|%s|%s)%s' % \ (raw_Kanji, raw_Hiragana, raw...
import random def qselect(k, a): print(a) if a == []: return [] else: rand = random.randrange(0, len(a)) pivot = a[rand] #print("pivot is " + str(pivot)) #print(a) left = [x for x in a[:rand] if x <= pivot] + [x for x in a[rand+1:] if x <= pivot] right...
transcription = { 'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U', } def transcribe_rna(dna): rna = '' if len(dna) != 4: return None for letter in dna: rna += transcription[letter] return rna def validate_dna(dna): return set(dna).issubset(set('GCTA')) def main(): w...
num = input() revnum = num[::-1] if num == revnum: print('yes') else: print('no')
import argparse import sys ############################################################################## def map_char(s1, s2): count = {} counter = 0 match = 0 if len(s1) != len(s2): print("false") else: for char in s1: if char in count: count[char] += ...
import turtle as t import random as r wndSize = 400 print("How many turtles do you wanna use?") n_turtles=input() t.setup(wndSize, wndSize) wndDivision = wndSize/(n_turtles+1) l=[] cont=(0-(wndSize/2)) t.speed(1) for i in range(0, n_turtles-1): tartaruga=t.Turtle() tartaruga.penup() tartaruga.s...
from cryptography.fernet import Fernet import sqlite3 import dotenv import os dotenv.load_dotenv() #Setting up database database = sqlite3.connect('emails.db') cursor = database.cursor() #Try to make table unless table already exist try: cursor.execute('CREATE TABLE emails (email text)') except sqlite3.Operation...
current=100#in amps. resistance=0.2020#in ohms. voltage=current*resistance#in voltage. print('the voltage is {} volts'.format(voltage)) print('the voltage is {v:1.2f} volts' .format(v=voltage)) print('the voltage is {v:10.2f} volts' .format(v=voltage))
l1=[1,2,3,4,5,6,7,8,9,10] for n in l1: if n%2==0: print(n) l2=[1,2,3,4,5] sum=0 for num in l2: sum=sum+num print(sum)
#Booleans are operators that allows you to convey true or false statements. #These are very important later on when we deal with control flow and logic b1=1>2 print(b1) b2=1==1 print(b2) #if we want to know the type of the values true/false print(type(True)) print(type(False))
patient_name=input("enter patient name:") age=input("enter patient age:") print('patient name is {},and his age is {}' .format(patient_name,age)) print('patient name is {1},and his age is {0}' .format(patient_name,age)) print('patient name is {1},and his age is {1}' .format(patient_name,age)) print('patient name i...
#Define a function which returns the resistance by taking voltage and current. def resistance(voltage,current): resistance=voltage/current return resistance R=resistance(12,2) print(R) #Here you can see the value of resistance from given voltage and resistance. #In the above function we use return keywor...
bread = 11 pb = 3 j =2 if bread >=2 and pb >0 and j > 0: print "You can make a PBJ sandwich!" if bread/2 >=2 and pb >=(bread/2) and j>=(bread/2): sandwich = (bread/2) print "You can make {0} sandwiches!".format(sandwich) elif bread/2 >=2 and pb < (bread/2) or j < (bread/2): print "There is not enough pb o...
''' Enunciado: desenvolva um programa que ajude um jogador da MegaSena a criar palpites. O programa deverá perguntar qtos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo (sem repetir números), cadastrando tudo em uma única lista composta. ''' from random import randint from time import sleep ...
from ex109 import moeda p = float(input('Digite um valor: R$ ')) print() print(f'Um aumento de 10% de R$ {moeda.moeda(p)} vai para R$ {moeda.aumentar(p, 10, True)}') print(f'Uma redução de 13% de R$ {moeda.moeda(p)} vai para R$ {moeda.diminuir(p, 13, True)}') print(f'O dobro de R$ {moeda.moeda(p)} é R$ {moeda.dobro(p,...
# Faça um programa que leia um numero inteiro e mostre na tela o seu sucessor e seu antecessor n1 = int(input('Digite um valor: ')) a = n1 - 1 p = n1 + 1 print('O numero anterior a {} é {}'.format(n1, a)) print('O numero posterior a {} é {}'.format(n1, p))
# Desafio 59: desenvolve um programa que leia 2 numeros e, em seguida, mostre # um menu na tela. Esse programa deverá realizar a operação solicitada em cada # caso - vide figura anexa. num1 = int(input('\nInforme o 1º numero: ')) num2 = int(input('Informe o 2º numero: ')) soma = mult = maior = menor = novo = sair = ...
# Enunciado: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e a condição de pagamento: # à vista dinheiro/cheque: 10% de desconto # à vista no cartão: 5% de desconto # em até 2x no cartão: preço normal # 3x ou mais no cartão: 20% de juros print('\n' + '='*10 + ' Con...
# Enunciado: desenvolva um programa que tenha uma função chamada área() que receba as dimensões de um terreno # retangular (largura x comprimento) e mostre a qual a área do terreno. def area(larg, comp): a = larg * comp print(f'A área de um terreno de {larg} m x {comp} m é de {a:.2f} m²') # programa principal...
#Enunciado: Crie um programa que leia o nome de uma cidade e diga se ela começa, ou não, com a palavra "SANTO" cidade = str(input('\nInforme o nome da cidade: ')) pal = cidade.upper().find('SANTO') if pal == 0: print('\nA cidade possui SANTO no nome !') if pal != 0: print('\nA cidade não possui SANTO no nome...
# Enunciado: faça um programa que leia um ano qualquer e mostre se ele é BISEXTO. ano = int(input('\nInforme o ano: ')) ano1 = ano % 4 ano2 = ano % 100 if ano1 == 0 and ano2 != 0: print('\nO ano de {} é Bissexto !!'.format(ano)) else: print('\nO ano de {} não foi Bissexto !!'.format(ano))
filme = { 'Titulo':'Star Wars', 'Ano':1977, 'Diretor':'George Lucas' } # Nesse exemplo temos 3 elementos, também chamados de KEYS (Titulo, Ano e Diretor) ''' print(filme) print(filme.values()) print(filme.keys()) print(filme.items()) ''' # a seguir, um exemplo de manipulação de dicionario através do 'for...
################################## # exemplo de código de exibição da # sequencia de Fibonacci extraído # da documentçção do Python 2.8.0 ################################## print('*' * 40) # declarando as variáveis... a, b = 0, 1 # lógica de desenvolvimento da sequencia... while a < 1000: print(a, end=', ') # se...
# Enunciado: faça um algoritmo que leia o preço de um produto e mostre seu novo valor, com o desconto de 5% preco = float(input('Qual o valor do produto ? R$ ')) novo = preco - (preco * 5/100) print('Este produto que custava R$ {:.2f}, com o desconto de 5%, passa a custar R$ {:.2f}'.format(preco, novo))
''' lanche = ('Hamburger','Suco','Pizza','Pudim','Batata Frita') # Tuplas são imutáveis #lanche[1] = 'Refrigerante' # Uma forma de exibir a lista # for comida in lanche: # print(f'Eu vou comer {comida}') # print('\nUfa !! Comi pra caramba !!') # Outra forma de exibir a lista ''' ''' for cont in range(0, len(lanc...
def parOuImpar(n = 0): if n % 2 == 0: return True else: return False num = int(input('Digite um número: ')) # print(parOuImpar(num)) if parOuImpar(num): print('O número é PAR !') else: print('O número é IMPAR !')
''' Enunciado: desenvolva um programa que leia 4 valores e guarde-os em uma tupla. No final: A) quantas vezes apareceu o valor 9 B) em que posição foi digitado o primeiro valor 3 C) quais foram os números pares ''' ''' As dicas a seguir foram extraídas do link: http://www3.ifrn.edu.br/~jurandy/fdp/doc/aprenda-python/...
# Enunciado: faça um programa que leia um ano qualquer e mostre se ele é BISEXTO. while True: ano = int(input('\nInforme o ano: ')) ano1 = ano % 4 ano2 = ano % 100 ano3 = ano % 400 if ano1 == 0 and ano2 != 0 or ano3 == 0: print('\nO ano de {} é Bissexto !!'.format(ano)) else: ...
############################################ # Nessa aula foi apresentado o conceito # de variável composto suas 3 variantes: # a Tupla, a Lista e o Dicionário. # # Abaixo foi apresentado 3 formas diferentes # de exibir o conteúdo de uma Tupla... ############################################ # atribuindo valores a uma ...
# Crie um programa que tenha uma função camada voto(), que irá receber como parâmetro o ano de nascimento de uma # pessoa, retornando um valor literal indicando se a pessoa tem VOTO NEGADO, OPCIONAL OU OBRIGATÓRIO nas eleições. #-------------------------------------------------------------------- # o conteúdo abaixo f...
'''Enunciado: Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triangulo retangulo, calcule e mostre o comprimento da hipotenusa. ''' print('O exemplo a seguir usará o método tradicional)' print('A hipotenusa é a raiz quadrada da soma do quadrado do cateto oposto e do cateto adjacen...
def teste(): x = 8 # aqui, x é considerado um escopo local print(f'Na função teste, n vale {n}') print(f'Na função teste, x vale {x}') # Programa principal n = 2 # aqui n é considerado um escopo global print(f'No programa principal, n vale {n}') teste() print('À seguir, o Python irá apresentar mensagens d...
'''Enunciado: O mesmo professor do desafio anterior quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.''' from random import shuffle a1 = input('Informe o nome do 1ª aluno: ') a2 = input('Informe o nome do 2ª aluno: ') a3 = inpu...
# Desafio 60: desenvolva um programa que leia um numero qualquer e mostre o seu # fatorial. Ex.:5! = 1x2x3x4x5 = 120 num1 = int(input('Informe o numero que deseja fatorar: ')) fat = 1 cnt = num1 print('\n{}! = '.format(num1), end='') while cnt >= 1: print(cnt, end='') if cnt != 1: print(' x ', end=''...
from random import randint num = randint(0,100) bingo =False print('what number do I think') while bingo == False: answer = input() if answer < num : print ('%d is too small' %answer) elif answer >num : print ('%d is too big' %answer) else: bingo =True print ('bingo,%d ...
from random import choice print 'which side will you choice' print 'left.right,middle?' yourchoice = raw_input() print 'your choice is %s' %yourchoice direction = ['left','right','middle'] randomchoice = choice(direction) if randomchoice == yourchoice: print 'congratuatios, goal' else: print 'oops %s' %rando...
a = 1 b = [1, "test"] b[0] = 2 print("a = ",a) print("b = ",b) print("b[0], b[1] = ",b[0], b[1]) #b[2] = 6 b.append(5.80) print("b[0]=%5d, b[1]=%5s, b[2]=%5.2f" %(b[0], b[1], b[2])) b[0] = "a" print("b[0]=%5s" %(b[0])) #print("b[0] = %5d" %(b[0]))
# ^__^ / \ # (oo) ( Milk is logical. ) # /-------\/ --'\________________/ # / | || # * ||W---|| # ^^ ^^ # 1.1 def adder(tall1, tall2): return (tall1 + tall2) print("Resultat 1:", adder(10, 10)) print("Resultat 2:", adder(25, 75)) # 1.2 # 1.3 tekst = input("Skriv ...
def print_personalia(): navn = input("Skriv inn navn: ") bosted = input("Hvor kommer du fra: ") print("Hei, " + navn + "! Du er fra " + bosted) for x in range(3): print_personalia()
def partition(a, left, right): pivot = right j = left for i in range(left, right): if a[i] <= a[pivot]: a[i], a[j] = a[j], a[i] j += 1 a[j], a[pivot] = a[pivot], a[j] return j def partition2(a, left, right): pivot = right j = left for i in range(left, ri...
from replit import clear #HINT: You can call clear() to clear the output in the console. from art import logo print(logo) name = input("What is your name ? ") bid_price = int(input("Bid price: ")) dictionary = { name : bid_price } stop = 1 #flag = input("Are there other user want to bid ?").lower() name_max = "" ma...
# 1089 Insert or Merge (25分) def InsertSort(lst01, lst02): flag = 0 for i in range(1, len(lst01)): for j in range(i, 0, -1): if lst01[j] < lst01[j - 1]: lst01[j], lst01[j - 1] = lst01[j - 1], lst01[j] else: break if flag == 1: ...
# 1127 ZigZagging on a Tree (30分) def create_tree(inlist: list, postlist: list, node_graph: dict): if inlist: ele = postlist[-1] index = inlist.index(ele) if len(inlist) == 1: node_graph[ele] = [None, None] else: if index == 0: node_gr...
#1096 Consecutive Factors ''' Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3 5*6*7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, ...
# step 1 daft_punk = [] print("Step 1:", daft_punk) # step 2 daft_punk.append("Thomas Bangalter") daft_punk.append("Guy-Manuel") print("Step 2:", daft_punk) # step 3 for i in range(2): daft_punk.append(input()) print("Step 3:", daft_punk) # step 4 del daft_punk[-1] del daft_punk[-1] print("Step 4:", daft_punk) ...
sum=0 for count in range(0,20,2): if count==10: continue sum+=count print('计数器',count,'总数',sum)
# B_R_R # M_S_A_W # Have the user ask their investment amount and expected interest rate. """Each year the investment will increase by original investmen plus compounded investment multiplied to interest reate""" # Print out the investment in 10 years. inves=float(input("How much is your investment: ")) # we convert...
# B_R_R # M_S_A_W while True: us_inp=eval(input('How old are you: ')) # If age is under 5, then wait to grow to Kindergarden if us_inp<5: print(""""Wait some time to turn to be 5 years old, so you can go to Kindergarden""") # If age is 5, then go to Kindergarden elif us_inp==5: print("Go to Kindergarde...
x=input() while x!='q': print(x) else: print('q')
x=input() #前面可以加eval(字串轉數字) y=input() z=input() if x>y: if x>z: print(x) else: print(z) if y>x: if y>z: print(y) else: print(z)
""" 257. Binary Tree Paths Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 """ # Definition for a binary tree node. # class TreeNode: # d...
""" 709. To Lower Case Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. Example 1: Input: "Hello" Output: "hello" Example 2: Input: "here" Output: "here" Example 3: Input: "LOVELY" Output: "lovely" """ class Solution: def toLowerCase(self, str): result ...
""" 500. Keyboard Row Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. Example: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: You may use one character in the keyboard more than once. You may...
""" This is the gui module for the gross_net calculator. """ # TDD # tkinter import tkinter as tk from gross_net_calculator import gross_net_calculator as gncalc class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() d...
def add(a, b): print(f"Adding {a} + {b}") return a + b def subtract(a, b): print(f"Subtracting {a} - {b}") return a - b def multiply(a, b): print(f"multiplying {a} * {b}") return a * b def divide(a, b): print(f"dividing {a} / {b}") return a / b mercedes = add(56, 71) print("Mercedes ...
def janky_format_prereq(prereq_str: str) -> str: janky_str = prereq_str useless_phrases = ["Undergraduate Semester level", "Minimum Grade of C", "Minimum Grade of D"] for phrase in useless_phrases: janky_str = janky_str.replace(phrase,"") return " ".join(janky_str.split()) # trims external and *internal* whitespa...
import calendar """ trying out the calendar""" #sep=calendar.TextCalendar(calendar.MONDAY) #sep.prmonth(2019, 3) #print(sep) #year=int(input("Enter the year to display: ")) #print(calendar.prcal(year)) cal=open("/Users/chris/pygit/cal.html", "w") c=calendar.HTMLCalendar(calendar.MONDAY) cal.write(c.formatyear(2019)) ...