text
stringlengths
37
1.41M
# Write a function that takes in two non-empty arrays of integers, finds the pair of # numbers (one from each array) whose absolute difference is closest to zero, and # returns an array containing these two numbers, with the number from the first array in # the first position. # Note that the absolute difference of two...
# Given an array of positive integers representing coin denominations and a single non- # negative integer n representing a target amount of money, write a function that # returns the smallest number of coins needed to make change for (to sum up to) that # target amount using the given coin denominations. # Note that y...
# Sample Input : # array = [0, 1, 21, 33, 45, 45, 61, 71, 72, 73] # target = 33 # Sample Output: # 3 def binarySearch(array, target): # Write your code here. return binarySearchHelper(array,target,0,len(array)-1) def binarySearchHelper(array,target,left,right): if left >right: return -1 middle = (left +...
####note################################################### #return [i for i in data if data.count(i) > 1] ########################################################### #Your optional code here #You can import some modules or create additional functions def checkio(data): #Your code here #It's main function. Do...
def find_two(): with open('one.input', 'r') as f: data = f.readlines() data = [int(x) for x in data] for x in data: for y in data: if x + y == 2020: print(x*y) return print('Sum not found') def find_three(): with open('one.input', 'r') a...
# Quick sort 10000 random numbers between 0 and 10000 # Print the Initial list and final result only. import random from itertools import chain def quick_sort(dl): if len(dl) == 1: # One Number return dl all_same = True # All same numbers for i in range(len(dl)): if dl[0] != dl[i]: ...
import abc class Feature(object): __metaclass__ = abc.ABCMeta """ class to wrap all the scripts/method to aggregate features from the database """ @abc.abstractmethod def createFeature(self,collectionName,param): """ Method to define how a feature/set of features is computed. ...
def readfiles(fnames): for i in fnames: f = open(i, 'r') for line in f: yield line def grep(pattern, lines): a = [] for line in lines: if pattern in line: a.append(line) return a def printlines(lines): for line in lines: print line def main(...
""" Program to list all the files in the given directory along with their length and last modification time.""" import os path = input("Enter the path of the file to be listed, enclosed in double quotes.\n") dirs = os.listdir(path) for i in dirs: path_n = path + "/%s" %(i) s = os.stat(path) print i ...
#!/usr/bin/env python3 import json import math import operator import argparse import numpy as np import pandas as pd import vocab import preprocessing import plot class TFIDF(): def __init__(self, documents, vocab): """ Term Frequency - Inverse Document Frequency Class It takes a set of ...
# -*- coding: utf-8 -*- import itertools import os import matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot as plt import numpy as np import pandas as pd from sklearn.feature_selection import VarianceThreshold from sklearn.preprocessing import normalize from sklearn.decomposition import PCA from utils...
import math def list(a, x): smallest = math.inf largest = 0 five = [] other = [] for i in range(len(a)): if a[i] < smallest: smallest = a[i] elif a[i] > largest: largest = a[i] print('Smallest: ', smallest) print('Largest: ', largest) ...
''''lista_telefonica = [('Rafael', '11-9-7072.3887'), ('Fernanda', '11-9999.000'), ("Gustavo", '11-8888.0000'), ('Vicente', '11-7777.8888'), ('Luzia', '1111.2222')] print (lista_telefonica) print (lista_telefonica[0]) print (lista_telefonica[0][0]) contatos = dict (lista_telefonica) nome = input("Digite um nome: ") p...
##5. Faça um programa que calcule através de uma função o IMC de uma pessoa que tenha 1,68 e pese 75kg. '''def IMC(altura,peso): imc_calculado = peso /(altura ** 2) if imc_calculado < 18.5: print("Magreza") elif imc_calculado >= 18.5 and imc_calculado < 24.9: print("Normal") elif imc_ca...
'''Exercício 1 1. Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: a. tamanho da lista. b. maior valor da lista. c. menor valor da lista. d. soma de todos os elementos da lista. e. lista em ordem crescente. f. lista em ordem decrescente.''' '''listaL = [5, 7, 2, 9, 4, 1...
## 6.Escreva uma função que, dado um número nota representando a nota de um estudante, converte o valor de nota para um conceito (A, B, C, D, E e F). ''' def nota_aluno(): notaluno = float(input("Digite a nota do aluno: ")) if notaluno <= 5.9: print ("nota F") elif notaluno >=6.0 and notaluno <=6.9:...
#https://wiki.python.org.br/EstruturaSequencial from number import Number num = Number() metros = input("Informe um valor em metros ") if num.isnumber(metros): print(metros + " metro(s) são " + str(int(metros) * 60) + " centímetros") else: print("Você não informou um número válido!")
# Task 1.1 replace " ' def replace (stroka): print (stroka) i = 0 strokanew = "" while i < len(stroka): if stroka[i] == "'": strokanew = strokanew + '"' elif stroka[i] == '"': strokanew = strokanew + "'" else: strokanew = strokanew +...
def reverse(str): res = "" for c in str: res = c + res return res s = input() print(reverse(s))
#################################################### #################################################### ############# Welcome to lesson 1 ################## ############## Python 3.3 ################# #################################################### #################################################### #...
import math # print (1) # ceil()向上取整 ''' help(math) print(math.ceil(5.1) ) # floor()向下取整 # print(math.floor(5.9)) # 查看系统关键字 不能用来当做变量名 import keyword print (keyword.kwlist) # 四舍五入 python 内置函数 print(round(5.3)) print(round(5.5)) # sqrt()开平方 返回浮点数 print(math.sqrt(9)) # sin 正弦 # pwd()与幂运算差不多,计算一个数的几次方,有两个参数,第一个是底数,第二个...
# 피보나치 함수(Fibonacci Function)을 재귀함수로 구현 def fibo(x): if x == 1 or x == 2: return 1 return fibo(x-1) + fibo(x-2) print(fibo(4)) # 피보나치 수열 : 탑다운 # 한 번 계산된 결과를 메모이제이션하기 위한 리스트 초기화 d = [0] * 100 def fibo_topdown(x): if x == 1 or x == 2: return 1 if d[x] != 0: return d[x] d[x] = fibo_topdown(x-1) + ...
# 배열 문법 공부하자 # 1) 1차원 배열 arr1 = [0, 0, 0, 0, 0] print(arr1) arr2 = [0] * 5 print(arr2) arr2[0] = 1 print(arr2) # 2) 2차원 배열 arr3 = [[0]*5 for _ in range(5)] print(arr3) arr3[0][1] = 1 print(arr3)
def calculate_exponent(base,exponent): return base**exponent print("Please enter the base") base = int(input()) print("Please enter the exponent") exponent = int(input()) calculate_exponent(base,exponent)
op = int(input("""Enter an operation (1) for addition (2) for multiplication""")) a = int(input("Enter the first value")) b = int(input("Enter the second value")) if (op == 1): print("a + b = ",a+b) elif (op == 2): print("a*b = ", a*b) else: print("Wrong option!")
# 모델링할 경우 lstm을 2~3개 이상 사용하면 효율이 저하 될수 있음 # return sequence는 2개이상의 lstm을 사용할 경우 사용함. # lstm에서 output shape의 dimension을 하나 늘려주기 위해 return_sequences=True 옵션을 사용한다. from numpy import array from keras.models import Sequential from keras.layers import Dense, LSTM #1. 데이터 x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,...
#searches through a text file with entries of the form name, phone number, address #each line represent one person, uses regex to extract data import re #regexp import sys #for command line arguments if len(sys.argv) < 2 : print("Error, no file given") else: filename = sys.argv[1] #the first argument is actually ...
"""Level 2""" def answer(codes): """Find number of distinct access codes in a list of possibilities. Two codes are equivalent if they are the same or reverses of one another. Two codes which are not equivalent are distinct. For example, 'abc' is equivalent to 'abc' and 'cba', but not to 'bca'. Th...
bits=[1,1,0] class Solution: def isOneBitCharacter(self, bits): i = 0 while i < len(bits): if bits[i]==0: if i == len(bits)-1: return True i += 1 if bits[i]==1: if i == len(bits)-2: return False i += 2 x=Solution() print(x.isOneBitCharacter(bits))
#inputString = "abcabcbb" # the answer is "abc", which the length is 3. #inputString = "au" # the answer is "b", with the length of 1. inputString = "pwwkew" # the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. class Solution: def lengt...
class Solution: def setZeroes(self, matrix): zeroXIndex = {} zeroYIndex = {} for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: zeroXIndex[i] = 1 zeroYIndex[j] = 1 for i in range(len(m...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ arry = [] ...
#retorna uma string sem espaços e com a primeira letra de cada palavra maiuscula def split_string(string): strArray = string.split() newString = '' for str in strArray: newString += str.title() return newString
my_variable=10 my-boolan=True #布尔值首字母大写,后面不用打分号 print my_boolean def spam(): #一个函数 eggs = 12 #需要空4格 return eggs # return print spam() #返回12 """ 三个双引号就苏多行注释 """ eight = 2 ** 3 # 2的3次方 'he'\s'#\代表 name='ly'[1] print name #y print len(name) #2 print name.lower() #ly print name.upper() #LY ...
def tower_builder(n_floors): # build here myList = [] for i in range(1, n_floors + 1): if (i == 1): myList.append((' ' * (n_floors - 1)) + '*' + (' ' * (n_floors - 1))) elif (i < n_floors): myList.append( (' ' * (n_floors - i)) + ('*' * ((i * 2)-1)) + (' ' * (n_floors...
import pygame import random import solver from eval_expression import * """ CREDITS: Pygame basics and image loading: https://youtu.be/UdsNBIzsmlI Pygame mouse interactions: https://youtu.be/vhNiwvUv4Jw Pygame image scaling: https://www.pygame.org/docs/ref/transform.html Pygame font usage: https://www.pygame.org/d...
''' Sauer's book page 43. Derive three different g(x) for finding roots to six correct decimal places of the following f(x) = 0 by Fixed-Point Iteration. Run FPI for each g(x) and report results, convergence or divergence. Each equation f (x) = 0 has three roots. Derive more g(x) if necessary until all roots are found...
# Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples # of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # # real 0m0.045s # user 0m0.027s # sys 0m0.014s sum = 0 for i in range(1, 1000): if i % 3 == 0 or i...
# Python3 implementation of the approach # Link list node class Node: def __init__(self): self.data = 0 self.next = None # Function to get the intersection point # of the given linked lists def getIntersectionNode(head1, head2): curr1 = head1 curr2 = head2 # While both the pointers a...
class Solution(object): def majorityElement(nums): """ :type nums: List[int] :rtype: int """ count = 0 candidate = None for num in nums: if count == 0: candidate = num if num == candidate: count = count...
def removeAdjDup(s, n): chars = list(s) # k maintains the index of next free location in the result k = 0 # i maintains the current index in the String # start from the second character i = 1 print(chars) while i < len(chars): # if current character is not same as the ...
square = {2: 4, 3: 9, -1: 1, -2: 4} # the smallest key key1 = min(square) print("The smallest key:", key1) # -2 # the key whose value is the smallest key2 = min(square, key = lambda k: square[k]) print("The key with the smallest value:", key2) # -1 # getting the smallest value print("The smallest value:", squ...
def twosum(arr,target): dm={} for i in range(0,len(arr)): val=target-arr[i] if val in dm: print("sum of",arr[i],str(val)) return True else: dm[arr[i]]=i a = twosum(arr=[2, 3, 7, 9], target=10) print(a)
''' In this chapter, you'll be introduced to fundamental concepts in network analytics while exploring a real-world Twitter network dataset. You'll also learn about NetworkX, a library that allows you to manipulate, analyze, and model graph data. You'll learn about the different types of graphs and how to rationally vi...
import math as m h = float(input("Digite a altura da parede: ")) w = float(input("Digite a largura da parede: ")) area = h * w areaTinta = 2 print("Para pintar uma parede de {:0.2f} m^2 é necessário {} litros de tinta".format(area, m.ceil(area/areaTinta)))
n = int(input("Digite um número inteiro: ")) divisores = 0 divisor = 1 while (divisores <= 2 and divisor <= n): if n % divisor == 0: divisores+= 1 divisor += 1 if (divisores == 2): print("primo") else: print("não primo")
print("\033[7;30m-=\033[m"*20) print("\033[7;30m{:^40s}\033[m".format("MÉDIA DE NOTAS")) print("\033[7;30m-=\033[m"*20) n1 = float(input("Digite a primeira nota do aluno: ")) n2 = float(input("Digite a segunda nota do aluno: ")) media = (n1+n2)/2 print("A média das notas do aluno foi \033[41;30m{:.2f}\033[m".format...
''' Course: Writing Efficient Python Code Chapter: 1 - Foundations for efficiencies In this chapter, you'll learn what it means to write efficient Python code. You'll explore Python's Standard Library, learn about NumPy arrays, and practice using some of Python's built-in tools. This chapter builds a foundation fo...
n = int(input("Digite o valor de n: ")) i = 0 x = 0 while (x < n): if (not i % 2 == 0): print(i) x +=1 i +=1
''' Having been exposed to the toolbox of data engineers, it's now time to jump into the bread and butter of a data engineer's workflow! With ETL, you will learn how to extract raw data from various sources, transform this raw data into actionable insights, and load it into relevant databases ready for consumption! '''...
n = int(input("Digite um número: ")) cores = {"limpa": "\033[m", "inverte": "\033[7;30m"} print("{}dobro de {} = {}{}\n" "Triplo de {} = {}\n" "{}Raiz quadrada de {} = {:.2f}{}" .format(cores["inverte"], n, n*2, cores["limpa"], n, n*3,cores["inverte"], n, n**(1/2), cores["limpa"]))
def pay(hour, rate): if hours > 40: pay = 40 * rate pay = pay + (hours - 40) * (rate * 1.5) else: pay = hours * rate return pay print("Hello user") hoursSTR = input("Enter how many hours your work this month: ") try: hours = float(hoursSTR) except Exception as e: hours = -1...
i = 1 lista = [] while i != 0: i = int(input("Digite um número: ")) lista.append(i) tam = len(lista) while tam > 1: print(lista[tam-2]) tam -= 1
''' Now that you know the primary differences between a data engineer and a data scientist, get ready to explore the data engineer's toolbox! Learn in detail about different types of databases data engineers use, how parallel computing is a cornerstone of the data engineer's toolkit, and how to schedule data processing...
n = float(input("Digite um valor em m: ")) print("A medida de {:.2f} m é equivalente a {:.1f} cm e a {:.0f} mm".format(n, n *100, n*1000))
n = int(input("Digite um número inteiro: ")) print("-"*12) for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: print("{} x {:2} = {}".format(n, i, n*i)) print("-"*12)
import math as m x1 = int(input("Digite o primeiro número: ")) y1 = int(input("Digite o segundo número: ")) x2 = int(input("Digite o terceiro número: ")) y2 = int(input("Digite o quarto número: ")) D = m.sqrt(m.pow(x2-x1, 2) + m.pow(y2-y1, 2)) if D >= 10: print("longe") else: print("perto")
cidade = input("Informe o nome da sua cidade: ").strip() duvida = "santo" in cidade.split()[0].lower() if duvida: print("Sua cidade começa com a palavra Santo") else: print("A cidade não começa com a palavra Santo")
''' Course: Working with Dates and Times in Python Chapter 4: Easy and Powerful: Dates and Times in Pandas To conclude this course, you'll apply everything you've learned about working with dates and times in standard Python to working with dates and times in Pandas. With additional information about each bike rid...
#/usr/bin/python3 def count(string, word): counter=0 word_length = len(word) for index, value in enumerate(string): print(string[index:word_length + index]) if string[index:word_length + index] == word: counter += 1 return counter def calculate_score(string): ''' ...
# 0 1 2 3 4 5 6 7 lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] if __name__ == '__main__': print(lst[::2]) # Output: ['a', 'c', 'e', 'g'] print(lst[2:4]) # Output: ['c', 'd'] print(lst[2:]) # Output: ['c', 'd', 'e', 'f', 'g', 'h']
def fourthpower(x): """ Inputs x. Takes x to the fourth (4th) power. It does so using a function inside a function -- secondpower(x). This is an exercise in using functions and scopes/namespaces. """ def secondpower(x): x = x ** 2 secondpower(secondpower(x))
# -*- coding: utf-8 -*- """ Created on Tue Nov 28 18:59:34 2017 @author: Dimitar Nikolov """ # This is Iteration 3, or the second refactoring of my Zen of Python script. # This is by far my cleanest attempt at storing and printing the poem. How it works: # The poem is stored in a text file called Poem.txt. Then, a fu...
def is_palindrome(word): """Return True/False if this word is a palindrome. >>> is_palindrome("a") True >>> is_palindrome("noon") True >>> is_palindrome("racecar") True >>> is_palindrome("porcupine") False >>> is_palindrome("Racecar") False """ # # using list s...
def is_pangram(sentence): """Given a string, return True if it is a pangram, False otherwise. >>> is_pangram("The quick brown fox jumps over the lazy dog!") True >>> is_pangram("I like cats, but not mice") False """ # a panagram is a sentence that contains all of the letters of the engli...
"""Stack implemented using Python list""" class StackEmptyError(IndexError): """Attempt to pop an empty stack.""" class Stack(object): """LIFO stack. Implemented using a Python list; since stacks just need to pop and push, a list is a good implementation as popping and appending to the end of a ...
"""Using a queue to make a console to make a console task manager""" class Queue(object): """A simple queue, implemented using a list.""" # NOTE: this is a straightforward way to implement a # queue -- but it's also inefficient if you'll have # many items in the queue. For a more efficient queue #...
############################## Linked List Basics ######################## # class Node(object): # """Node in a linked list""" # def __init__(self, data): # self.data = data # self.next = None # apple_node = Node("apple") # berry_node = Node("berry") # cherry_node = Node("cherry") # app...
def show_evens(nums): """Given list of ints, return list of *indices* of even numbers in list.' >>> lst = [1, 2, 3, 4, 6, 8] >>> show_evens(lst) [1, 3, 4, 5] """ # using list comprehension: # if num % 2 is equal to zero, return the indices as list return [i for i, num in enumerate(nu...
import random class Animal(object): """An animal class""" name = None species = None def __init__(self, name, species): self.name = name self.species = species self.age = random.randint(1, 10) def speak(self): return "Hey! I am a {species} named {name}".format(s...
def deduped(items): """Return new list from items with duplicates removed. >>> deduped([1, 1, 1]) [1] >>> deduped([1, 2, 1, 1, 3]) [1, 2, 3] >>> deduped([1, 2, 3]) [1, 2, 3] >>> a = [1, 2, 3] >>> b = deduped(a) >>> a == b True >>> a is b False >>> dedu...
############################# Merge Sort ####################################### def make_one_sorted_list(lst1, lst2): """Merge two sorted lists""" merged_list = [] while len(lst1) > 0 or len(lst2) > 0: if lst1 == []: merged_list.extend(lst2) elif lst2 == []: merge...
from tkinter import * '''Por ser um recurso desenvolvido para dois exercícios específicos, o número de nós e suas posições são fixas, mas nada impede de desenhar novas linhas de altura com algumas linhas a mais de código É uma pseudoárvore já que apesar de aparentar ser um grafo, não existem nós, são ...
#This small program proves how Numpy is much much faster than traditional python. import numpy as np import matplotlib.pyplot as plt import pandas as pd #Let us store 10 lac elements indexed from 0 to 9,99,999 in a traditional python list. my_list = list(range(1000000)) #Now we will store the same 10 la...
元组(tuple) example: tuple1=12,34,'ma',890 emptyTuple=() notes: 与列表不同的是元组的元组值一旦确定就不能被修改 列表(list) example: list1=[1,2,3,4,] emptyList=[] control lists: 1.元素赋值,list[2]=45 2.删除元素,del list1[2] 3.分片操作,list_2[6:] = list("hello") 4.索引列表,list1[3] 5.循环枚举,for i in list1: print(i) Built-In-Functions:(均以list1为例...
''' infile=open("test-1.txt","r") for i in range(5): line=infile.readline() print(line[:-1]) #字典中的遍历 for key in dictionaryName: print(key+":"+str(dictionaryName[])) '''
class Solution(object): def evalRPN(self, tokens): operator=["+","-","*","/"] stack=[] for i in tokens: if i not in operator: stack.append(int(i)) else: num1=stack.pop() num2=stack.pop() if i=="+": ...
class Solution(object): def decodeString(self, s): num,char=[],[] i=0 length=len(s) while i <length: index=i+1 if s[i].isdigit(): number=int(s[i]) while index<length: if s[index].isdigit(): ...
#credit: https://github.com/ProgrammerRaj-py/Hangman/blob/master/hangman.py # Importing Libraries import random # function def hangman(winning_word, char_guessed): for i in winning_word: if i in char_guessed: print(f' {i} ', end='') else: print(' __ ', end='') print() ...
#most credit: https://github.com/AVIGNAN18/kingdom/blob/c669ea1ffc696c79dc9f65fbf8c5303d7ef60966/rock.py from random import randint t = ['Rock','Paper','Scissors'] computer=t[randint(0,2)] player=True while player: player = input("Rock, Paper, Scissors? Type Q for quit: ") if player==computer: print(...
import pygame, math from pygame.locals import * from tetris_pieces import * pygame.init() # Colors black = (0,0,0) cyan = (0,255,255) blue = (0,0,255) orange = (255,100,10) red = (255,0,0) yellow = (255,255,0) green = (0,255,0) purple = (160,32,240) gray = (190, 190, 190) colors = [black, cyan, blue, orange, yellow, ...
# Exercício 3 - Vogais # Escreva a função vogal que recebe um único caractere como parâmetro e devolve True se ele for uma vogal e False se for uma consoante. # Dica: Lembre-se que para passar uma vogal como parâmetro ela precisa ser um texto, ou seja, precisa estar entre aspas. # Nota:10/10 def vogal(a): a = a.lo...
# Faça um programa que calcule o IMC de uma pessoa, mostre o IMC e uma das # mensagens abaixo de acordo com seu índice. # Resultado | Mensagem # Abaixo de 17 | Muito abaixo do peso # Entre 17 e 18,49 | Abaixo do peso # Entre 18,5 e 24,99 | Peso normal # Entre 25 e 29,99 | Acima do peso # Entre 30 e 34,99 | Obesidade I ...
#!/usr/bin/python #Filename : helloworld.py ##### ##### print 'Hello World' print r'This is what??? """hahahhahah/"""' '\\ ' # i = 5 # print i # i = i + 1 # print i # s = '''This is a multi-line string. # This is the second line.''' # print s # ss = 'This is a string. \ # This continues the string.' # print ss ...
# Faça um programa que leia o comprimento # do cateto oposto e do cateto adjacente # de um triângulo retângulo, calule e # mostre o comprimento da hipotenusa. from math import hypot x = float(input('Informe o valor do cateto adjacente: ')) y = float(input('Informe o valor do cateto oposto: ')) print('O valor da hipo...
""" Escreva um programa que leia a velocidade de um carro Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$ 7,00 por cada KM acima do limite. It's such a shame for us to part Nobody said it was easy No one ever said it would be this hard ...
""" Escreva um programa que leia um número n inteiro qualquer e mostre na tela os n primeiros elementos de uma sequência de Fibonacci. Ai, amor Será que tu divide a dor Do teu peito cansado Com alguém que não vai te sarar? Ai, amor - Anavitória ♪♫ """ n = int(input('Insira o valor...
""" Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão. Get up on the floor Dancin' all night long Get up on the floor Dancin' till the break of dawn Get up on the floor Dancin' till the break of dawn ...
""" Crie um programa que leia duas notas de um aluno e calcule sua méia, mostrando uma mensagem no final. m < 5 = reprovado 5 < m < 6.9 = recuperação m >= 7 = aprovado É uma índia com colar A tarde linda que não quer se pôr Dançam as ilhas sobre o mar Sua cartilha tem o A de que c...
n = s = 0 while True: n = int(input('Digite um número: ')) if n == 9999: break s += n print(f'A somma vale {s}')
""" Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valor lido. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. Mas, ora Você partiu antes de mim Nem...
""" Já que você não está aqui O que posso fazer é cuidar de mim Quero ser feliz ao menos Lembra que o plano era ficarmos bem? Vento no Litoral - Legião Urbana ♪♫ """ nome = input('Qual é o seu nome ? ') if nome.upper() == 'MATEUS': print('Que nome bosta !') elif nome.upper() == 'PEDRO' or nome....
# Crie um programa que leia o nome # de uma pessoa e diga se ela tem # 'SILVA' no nome. nome = input("Diga seu nome: ") print('SILVA' in nome)
'''Exercise 2: Implementing Binary Search Trees.''' from btree import BTree, BTNode class BST(BTree): '''A Binary Search Tree.''' def insert(self, value): '''Insert a new BTNode with value value into this BST. Do not insert duplicates. ''' pass def find(self, value): ...
cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) cars.sort(reverse = True) print(cars) print(len(cars)) travels = ["Bali","Taiguo","Janpan","America","Australia"] print(travels) print(sorted(travels)) print(travels) #travels.sort() print(travels) travels.reverse() print("-----",travels)
name = "Eric" show_toast = "Hello " show_toast1 = ",would you like to learn some Python today?" show_info = show_toast + name + show_toast1 print(show_info) new_name = "meng" # 首字母大写 print(new_name.title()) # 全部大写 print(new_name.upper()) # 全部小写 print(new_name.lower()) talks = "Albert Einstein once said:" content = "'...
users = ["admin","python","java","android","html"] for user in users: print("Hello," + user) if "admin" in users: print("Hello admin, would you like to see a status report?") else: print("Hello Eric, thank you for logging in again") userss = [] if userss : for using in userss: print("hello,user:" + using) p...
from random import randint class Die: def __init__(self, sides=6): self.sides = sides def roll_die(self, time): while time <= 10: self.sides = randint(1, 6) print("This sides is " + str(self.sides)) time += 1 my_sides = Die() my_sides.roll_die(1)
#-*- coding:UTF-8 -*- cars = ['bmw', 'audi', 'toyota', 'subaru'] #cars.sort() print(cars) # #cars.sort(reverse=True) print(cars) print(sorted(cars)) print(cars) #Ŵӡ cars.reverse() print(cars) print(len(cars)) print(cars) cars.reverse() print(cars)
class User: def __init__(self, first, last, sex): self.first = first self.last = last self.sex = sex def describe_user(self): print("The user name is " + self.first + " " + self.last + ", the sex is " + str(self.sex)) def greet_user(self): print("Hello," + self.firs...