Jump to content

Search the Community

Showing results for tags 'python'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Comunidade
    • Sugestões, Críticas ou Dúvidas relativas ao P@P
    • Acerca do P@P
  • Comunidade a Trabalhar
    • Apresentação de Projectos de Programação
    • Downloads
    • Revista PROGRAMAR
  • Desenvolvimento Geral
    • C
    • C++
    • Java
    • Pascal
    • Python
    • Bases de Dados
    • Dispositivos Móveis
    • Outras Linguagens
  • Desenvolvimento Orientado para Web
    • PHP
    • HTML
    • CSS
    • Javascript
    • Outras Linguagens de WebDevelopment
    • Desenvolvimento Web
  • Desenvolvimento .NET
    • C#
    • Visual Basic .NET
    • ASP.NET
    • WPF & SilverLight
  • Software e Sistemas Operativos
    • Software de Produtividade
    • Sistemas Operativos
    • Apresentação de Software
  • Informática
    • Interfaces Visuais
    • Computação Gráfica
    • Algoritmia e Lógica
    • Segurança e Redes
    • Hardware
    • Electrónica e Automação Industrial
    • Matemática
    • Software de Contabilidade e Finanças
    • Dúvidas e Discussão de Programação
  • Outras Áreas
    • Notícias de Tecnologia
    • Dúvidas Gerais
    • Discussão Geral
    • Eventos
    • Anúncios de Emprego
    • Tutoriais
    • Snippets / Armazém de Código
  • Arquivo Morto
    • Projectos Descontinuados
    • System Empires

Blogs

  • Blog dos Moderadores
  • Eventos
  • Notícias de Tecnologia
  • Blog do Staff
  • Revista PROGRAMAR
  • Projectos
  • Wiki

Categories

  • Revista PROGRAMAR
  • Tutoriais
  • Textos Académicos
  • Exercícios Académicos
    • Exercícios c/ Solução
    • Exercícios s/ Solução
  • Bibliotecas e Aplicações
  • Outros

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website


GitHub


LinkedIn


Twitter


Facebook

  1. Eu estou a começar a aprender Python mas no VS Code está me a dar este erro e não sei o que se passa. Alguém me consegue ajudar? Quando escrevo as variáveis elas ficam sublinhadas e aparece esta mensagem: Mas mesmo com este "erro" o programa executa normalmente.
  2. Python que gere valores aleatórios para uma matriz. Após, exiba para cada linha, o percentual de valores pares e o percentual de valores ímpares. informe o tamanho da matriz (número de linhas e de colunas), de forma que seja desenvolvido um método para gerar a matriz, onde a quantidade de linhas e colunas sejam recebidas como parâmetros; outro método para completar a matriz com valores aleatórios e um último método para exibir as porcentagens de valores pares e ímpares para cada linha da matriz.
  3. jonhhy

    Try/exception

    Bom dia Comunidade Portugal-a-Programar, é possível colocar as exception's dentro dos if's de modo a executar somente uma exception? Pois neste trecho de código: def readIntandFloat(): try: i = int(input('Tell me a int: ')) except(ValueError, TypeError): print("\033[0;30;41mError: The data type that you enter did not numeric as expected for this purpose.") return readIntandFloat() # finally: # print('') try: f = float(input('Tell me a number: ')) except(ValueError, TypeError): print("\033[0;30;43mError: The data type that you enter did not numeric as expected for this purpose.") readFloat('Tell me a number2: ') except(KeyboardInterrupt): print('\033[0;30;44mError: Not inform more data') readFloat('Tell me a number2: ') # return else: print(f'The int number is {i} and \t The float number is {f}') finally: print('Felizes e contentes') que usa esta função: def readFloat(msg): try: inp = float(input(msg)) except KeyboardInterrupt: # para funcionar tinha no meio de dois input's como acontece no exemplo acima! print("\033[0;30;42mUser didn't inform the data") readFloat('Error: Digit a new number: ') except(ValueError, TypeError): print("\033[0;30;47mThe data type that you enter did not numeric as expected for this purpose") readFloat('Error: Digit a number again: ') except Exception as general: print(f'The problem was {general.__class__}') else: print(f'The number is {inp}') Tell me a int: 6 Tell me a number: Error: The data type that you enter did not numeric as expected for this purpose. Tell me a number2: t The data type that you enter did not numeric as expected for this purpose Error: Digit a number again: The data type that you enter did not numeric as expected for this purpose User didn't inform the data Error: Digit a new number: 9 The number is 9.0 Felizes e contentes Error: Digit a number again Error: Digit a number again: Error: Digit a new number: O programa ao entrar nesta função, sempre que tento parar a execução do trabalho, ele abre 2 abas de input! .. e preenchendo uma delas acontece isto User didn't inform the data Error: Digit a number again: 9 The number is 9.0 Felizes e contentes Error: Digit a new number: A pergunta acima na minha óptica pode resolver a questão, mas gostava de muito a vossa opinião. cumprimentos
  4. Viva try: # (tenta) a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b except: print('Infelizmente tivemos um problema :(') else: print(f'O resultado é {r}') print(f'Resultado 1 casa decimal é {r:.1f}') Numerador: 5 Denominador: 4 O resultado é 1.25 Resultado 1 casa decimal é 1.2 Numerador: 5 Denominador: 3 O resultado é 1.6666666666666667 Resultado 1 casa decimal é 1.7 https://imgur.com/a/uOMJD20 Porque num arredonda para cima e no outro para baixo? Quais são os critérios usados?
  5. jonhhy

    Operator Bitwise

    Boa tarde P@P, em termos, de operador para a resolução deste exercício: "Given the X numpy array, get numbers equal to 2 or 10" tinha pensado assim: mask = X == (2 or 10) # X == (2 or 10) # your code goes here X[mask] contudo, os valores não me deram certo: array([2]) Já na resolução, eles fazem desta forma: X = np.array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10]) mask = (X == 2) | (X == 10) X[mask] e não percebo como funciona este operador bitwise, até porque 2 = 2^1 e 10 = 2^1+2^3.. Grato pela vosso tempo e ajuda, abraço Jonhhy
  6. Bom dia, Em primeiro fico feliz por saber que esta comunidade ainda esta ativa, estive afastado da programação durante uns anos mas agora que voltei e vejo que ainda estamos aqui ativo fiquei bem feliz parabens. Passando a duvida, estou a aprender python, por diversão, e descobri que posso dar clicks em em imagens especificas usando o pyautogui, perfeito e funciona, a minha grande duvida é: Existe alguma forma de eu estar a usar a minha maquina ( teclado e rato ) e usar o pyautogui ao mesmo tempo ? como que dar os clicks ou escrever sem "usar" o meu rato ou teclado ? Forte abraça PS: acredito que possa ter colocado aqui a duvida se nao for peço desculpa e peço que me digam onde.
  7. Bom dia estimados membros da comunidade P@P, hoje trago um exemplo da função decode() disponível neste site: https://www.geeksforgeeks.org/python-pandas-series-str-decode/ Código do site: # importing pandas as pd import pandas as pd # Creating the Series sr = pd.Series([b"b'New_York'", b"b'Lisbon'", b"b'Tokyo'", b"b'Paris'", b"b'Munich'"]) # Creating the index idx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the index sr.index = idx # Print the series print(sr) Output do site: City 1 b"b'New_York'" City 2 b"b'Lisbon'" City 3 b"b'Tokyo'" City 4 b"b'Paris'" City 5 b"b'Munich'" dtype: object Aplicando o decode aos dados: # use 'UTF-8' encoding result = sr.str.decode(encoding = 'UTF-8') # print the result print(result) Resultado do site: City 1 b'New_York' City 2 b'Lisbon' City 3 b'Tokyo' City 4 b'Paris' City 5 b'Munich' dtype: object Perante os resultados da função decode, pergunto-me senão podia também ter tirado o b' ' ... em: b'WORD' ? <- PERGUNTA na dúvida optei por correr sobre o result, Código feito por mim: result2 = result.str.decode(encoding = 'UTF-8') print(result2) City 1 NaN City 2 NaN City 3 NaN City 4 NaN City 5 NaN dtype: float64 Contudo, não era isto que pretendia ou tinha em mente ... (vou,
  8. Bom dia P@P, # number of ...matches could obtained for len(goallist) squad = [] soccerPl = {'nameSP': '', 'goalsbyGame':[], 'totalGoals': '', 'numMatches': ''} # name by input, goalsbygame append list, totalGoals cyclecounter and numMatches <- imply to obtain a len() function by a list (implícita de outra variável) nextOne = '' while True: soccerPl['nameSP'] = str(input(' Say soccerPlayer name? : ')) soccerPl['numMatches'] = int(input(' Say number of matches played? : ')) # vai derivar o número de chaves antes assim, devia por num varíável isolada.., pois consegue ser obtida a partir do len() da lista totalGoals = 0 for i in range(0, soccerPl['numMatches']): print(f'Number of goals scored in match {i} :') soccerPl['goalsbyGame'].append(int(input(''))) totalGoals += soccerPl['goalsbyGame'][i] soccerPl['totalGoals'] = totalGoals squad.append(soccerPl.copy()) print('-='*25) nextOne = str(input('Do you want add more player to the squad? ')).strip().upper() if nextOne == 'N': break print('The Squad player data ...') print(f"{'No.':^5} {'name':^9} {'goals by match':<16} {'totalGoals':<12} {'numMatches':<15} ") for i in range(0,len(squad)): #for squad[i] in range (0squad print(f"{i+1:^5} {squad[i]['nameSP']:^9} ) # squad[i]['nameSP']:^9} não sei como squad[i]['nameSP'] aceder a este campos, isto é uma lista de dicionários, Tenho de fazer 2 ciclos for para chegar a uma key do dicionário? e como?
  9. Bom dia membros da comunidade P@P, tenho uma string de nome, para identificar o grupo que quero destacar, contudo se houvesse forma de extrair só o nome das mulheres (diretamente era muito menos trabalhoso)... como é python penso sempre que deve haver alguma maneira melhor... indo ao exercício e código: # Desafio 094 Crie um programa que leia **nome**, **sexo** e **idade** de **várias pessoas**, guardando os dados de cada pessoa em um **dicionário** e todos os dicionários em uma **lista**. No final, mostre: **A)** Quantas pessoas foram cadastradas **B)** A **média** de idade do grupo. **C)** Uma lista com todas as **mulheres**. **D)** Uma lista com todas as pessoas com **idade** acima da **média**. signup = {'name': '', 'gender': '', 'age': ''} people = [] women = [] oldpeople = [] adelante = '' agesum = 0 while True: signup['name'] = str(input('Say person name: ')) signup['gender'] = str(input('Say person gender: ')) while signup['gender'] not in 'MmFf': signup['gender'] = str(input('We only consider gender: [F/M] ... : ')) signup['age'] = int(input('Say your age: ')) while signup['age'] < 0: signup['age'] = int(input('Age cannot be negative, say a positive number with the years: ')) agesum += signup['age'] people.append(signup.copy()) if signup['gender'].strip().upper() in 'F': #women.append(signup['name'].copy()) women.append(signup.copy()) #signup.clear() adelante = str(input('Did you want continue to sign up person? :')) if adelante in 'Nn': break print(f" People signup was {len(people)}") print(f" Age mean is {agesum/len(people)}") print(f" Women are {women[0]}") for person in people: if person['age'] > (agesum/len(people)): oldpeople.append(person['name']) print(f" Person with more that mean age is {oldpeople}") Say person name: Luísa Say person gender: f Say your age: 26 Did you want continue to sign up person? : yes Say person name: Miguel Say person gender: 31 We only consider gender: [F/M] ... : mas We only consider gender: [F/M] ... : m Say your age: 31 Did you want continue to sign up person? : Yieh Say person name: Sónia Say person gender: 11 We only consider gender: [F/M] ... : f Say your age: 11 Did you want continue to sign up person? :n People signup was 3 Age mean is 22.666666666666668 Women are {'name': 'Luísa', 'gender': 'f', 'age': 26} Person with more that mean age is ['Luísa', 'Miguel'] a dúvida é no primeiro comentário do código, que dá erro..
  10. Bom dia membros do P@P, Como se faz uma atribuição automática de todos os valores num dicionário a partir de uma tupla ou string? Vou mostrar o todo o processo: Inicialmente fiz assim, mas pensei poder automatizar etapas (para treinar): from random import randint plays = {'p1':'', 'p2':'', 'p3':'', 'p4':''} plays['p1'] = randint(1,6) plays['p2'] = randint(1,6) plays['p3'] = randint(1,6) plays['p4'] = randint(1,6) print(plays) {'p1': 4, 'p2': 0, 'p3': 6, 'p4': 0} Contudo, encurtei as linhas assim: gamer = ['p1','p2','p3','p4'] plays2 = dict() for i in gamer: # plays2 += {i:''} plays2[i] = randint(1,6) plays2 {'p1': 5, 'p2': 5, 'p3': 5, 'p4': 1} Depois andei a ver algum código na net e gostaria de conseguir dividir em quatro (individualmente) o tuplo que tem a atribuição vazia '' # Declaring a dictionary d = {} # This is the list which we are # trying to use as a key to # the dictionary a =['p1','p2','p3','p4'] # # converting the list a to a string # p = str(a) # d[p]= '' # converting the list a to a tuple q = tuple(a) d[q]= '' for key, value in d.items(): print(key, ':', value) print(d) ('p1', 'p2', 'p3', 'p4') : {('p1', 'p2', 'p3', 'p4'): ''} Grato pela atenção, cumprimentos jonhhy
  11. Boa tarde caríssimos membros da comunidade P@P, vou apresentar-vos o problema e o esboço de código na tentativa de resolução: Desafio 78 Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. def countPos(extreme, values): for ind, values in enumerate(values): pos = [] oc = values.count(extreme) pst=values.index(extreme) if oc > 1: pos.append(pst) oc -= 1 values = values[oc+1:] countPos(extreme, values) else: return pst if oc == len(values-1): return pos values = [] maxi=mini=0.0 im = iM = [] for i in range(0,5): n = float(input(f'Digit num[{i+1}]: ')) # int(input) também dá erro values.append(n) if i == 0 or values[i] < mini: #mini, im = values[i], i mini = values[i] #im.append(i+1) if i == 0 or float(values[i]) >= maxi: #maxi, iM = values[i], i maxi = values[i] #iM.append(i+1) print('-=' *20) print(f'You digit: {values}') print(f'Maximum is: {maxi} in position {countPos(maxi, values)}') #iM} ') print(f'Minimum is: {mini} in position {countPos(mini, values)}') #im}') O que devo alterar?
  12. Bom dia P@P, neste programa, a ordem dos prints esta a sair trocada: Desafio 059: Crie um programa que leia dois valores e mostre um menu na tela: [1] Somar [2] Multiplicar [3] Maior [4] Novos números [5] Sair do programa Seu programa deverá realizar a operação solicitada em cada caso. def readNums(): a = int(input('Digit a number: ')) b = int(input('Digit other number: ')) return a, b option = 3.5 while True: if option == 3.5: num1, num2 = readNums() else: print('''\nBem Vindo ao Menu! \nDigite uma das opções:\n [1] Somar [2] Multiplicar [3] Maior [4] Novos números [5] Sair do programa\n\n''') while option > 6 and option < 0: option = int(input('Say a option: ')) if option == 1: print('Sum: {} + {} = {}'.format(num1, num2, num1+num2)) elif option == 2: print('Multiplication: {} * {} = {}'.format(num1, num2, num1*num2)) elif option == 3: print('Greater is {}'.format(max(num1, num2))) elif option == 4: num1, num2 = readNums() elif option == 5: print('The End!') break option = int(input('Say a option: ')) Digit a number: 4 Digit other number: 3 Say a option: 1 Bem Vindo ao Menu! Digite uma das opções: [1] Somar [2] Multiplicar [3] Maior [4] Novos números [5] Sair do programa https://imgur.com/5eDOemn <- Output em imagem (representado acima) Sum: 4 + 3 = 7 <- # este print devia ter vindo antes de Bem Vindo ao Menu! (texto a itálico) Say a option: Como faço? (em C à a limpexa de buffer senão estou esquecido ..)
  13. Boa tarde Comunidade P@P, já vos aconteceu este erro antes, como se resolve? AttributeError: 'dict' object has no attribute 'upper Desafio 056 Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: A média de idade do grupo. Qual é o nome do homem mais velho. names = {} ages = {} #sex = [] sex = {} maXman = sum = count = max = 0 maXmanI = -1 # saber o nome do homem mais velho..., implica saber o index do man S = 4 for c in range(0, S): names[c] = str(input(' Digit person name: ')) ages[c] = int(input('Digit person age: ')) sex[c] = str(input('Please, digit your sex: F or M?: ')) sum += ages[c] if sex.upper().strip() == 'F' and ages[c]<20: #if sex.strip() == 'F' and ages[c]<20: count += 1 if sex.upper() == 'M': if (max<ages[c]): max = ages[c] maXmanI = c mean = sum / S print('A média de idades é: {}, o homem mais velho é: {} e\n existem {} mulheres com menos de 20 anos!'.format(mean,names[maXmanI], count)) Quantas mulheres têm menos de 20 anos. Grato pela atenção, cumprimentos jonhhy
  14. Olá Malta, por favor, gostava de otimizar/melhorar uma instrução que fosse possível de viabilizar algo tipo isto: while (date.today() < ano[c]): ano[C] = int(input('Digit the bornYear: ')) ou melhor: while (date.today() < ano[C] = int(input('Digit the bornYear: ')) Contexto, Desafio 054 Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores. O objectivo será o utilizador não inserir, logo de imediato, datas inválidas (neste caso, datas futuras ..em anos)) Solução apresentada: from datetime import date adults = 0 childs = 0 ano = {} actualYear = date.today().year print(actualYear) for c in range(0,7): ano[c] = int(input('Digit the bornYear: ')) # while (date.today() < ano[c]): # ano[C] = int(input('Digit the bornYear: ')) print(ano[c]) if actualYear - ano[c] >= 18: adults += 1 else:#if actualYear - ano[c]< 0: # garantir que não tem datas futuras... childs += 1 print('Number of Babys: {} \n Number of Adults: {}'.format(childs, adults)) Grato pela atenção. jonhhy
  15. Bom dia comunidade P@P, tenho dúvida relacionada com o não reconhecimento dos caracteres \n (newline) https://imgur.com/5MLM7C6 . Disponível neste código: https://github.com/ManJ-PC/PExercises/blob/main/Json.ipynb ou # Dicionário em Python client = { "name": "Nora", "age": 56, "id": "45355", "eye_color": "green", "wears_glasses": False } # Obter uma string formatada em JSON client_JSON = json.dumps(client) client_JSON_B = json.dumps(client, sort_keys=True, indent=4 ) client_JSON_B O output foi: '{\n "age": 56,\n "eye_color": "green",\n "id": "45355",\n "name": "Nora",\n "wears_glasses": false\n}', em vez de: { "age": 56, "eye_color": "green", "id": "45355", "name": "Nora", "wears_glasses": false }
  16. Olá, Eu gostaria de saber como é que consigo chamar o meu executável de python em php para disparar o output em web. Ou seja, eu tenho um ficheiro .py que com o pyinstaller tornei-o em ficheiro executável e chamando esse ficheiro na linha de comandos ele dispara o output correto. O que eu queria fazer era um ficheiro em PHP que executasse no localhost. Mas não aparece a string desejada... Na linha de comandos insiro: 1. cd C:\Users\35196\Documents\Python\pyinstaller\dist\Load_Final_Model\ 2. Load_Final_Model.exe image2.jpg - A image2.jpg é o ficheiro que ele recebe com a instrução sys.argv[1] E fornece o output, como por exemplo: "Classicada por: cat" O que acontece é que, quando executo o php fica tudo branco e não aparece nada. Código PHP: <?php $file = 'image2.jpg'; $command = escapeshellcmd('C:\Users\35196\Documents\Python\pyinstaller\dist\Load_Final_Model\Load_Final_Model.exe '.$file); $output = shell_exec($command); echo $output; ?> Código Python: #!/usr/bin/env python # coding: utf-8 # # CLASSES: # # [0] Airplane # [1] Automobile # [2] Bird # [3] Cat # [4] Deer # [5] Dog # [6] Frog # [7] Horse # [8] Ship # [9] Truck class_nameEN_us = ["airplane", "automobile" , "bird" , "cat" , "deer" , "dog" , "frog" , "horse" , "ship" , "truck"] # evaluate the deep model on the test dataset from tensorflow.keras.datasets import cifar10 from tensorflow.keras.models import load_model from tensorflow.keras.utils import to_categorical # load train and test dataset def load_dataset(): # load dataset (trainX, trainY), (testX, testY) = cifar10.load_data() # one hot encode target values trainY = to_categorical(trainY) testY = to_categorical(testY) return trainX, trainY, testX, testY # call load dataset function trainX, trainY, testX, testY = load_dataset() # scale pixels def prep_pixels(train, test): # convert from integers to floats train_norm = train.astype('float32') test_norm = test.astype('float32') # normalize to range 0-1 train_norm = train_norm / 255.0 test_norm = test_norm / 255.0 # return normalized images return train_norm, test_norm trainX, testX = prep_pixels(trainX, testX) # load model model = load_model('final_model.h5') # evaluate model _, acc = model.evaluate(testX, testY, verbose = 0) print('Hello', sys.argv[1]) print('> %.3f' % (acc * 100.0)) from tensorflow.keras.preprocessing.image import load_img from tensorflow.keras.preprocessing.image import img_to_array import numpy as np # load and prepare the image def load_image(filename): # load the image img = load_img(filename, target_size=(32, 32)) # convert to array img = img_to_array(img) # reshape into a single sample with 3 channels img = img.reshape(1, 32, 32, 3) # prepare pixel data img = img.astype('float32') img = img / 255.0 return img # load model model = load_model('final_model.h5') # load the image caminho_img = 'images/' + sys.argv[1] img = load_image(caminho_img) y_predict = np.argmax(model.predict(img), axis=-1) print("Classicada por: " + class_nameEN_us[y_predict[0]]) Obrigado.
  17. Olá, Estou com um problema a criar um executável em python. O objetivo é fazer um ficheiro executável que chama o modelo de treino e classifique a imagem com as classes atribuídas. Quando tento executar aparece o seguinte erro: 'Sequential' object has no attribute 'predict_classes' Eu estive a ver na internet e falaram que era problemas de versões do tensorflow. Eu já tentei alterar, mas continua a não funcionar... Alguém me pode ajudar? Em baixo envio o código: import tkinter as tk from tkinter import filedialog from tkinter import * from PIL import ImageTk, Image import numpy #load the trained model to classify sign from keras.models import load_model model = load_model('final_model.h5') classes = { 0:'Airplane', 1:'Automobile', 2:'Bird', 3:'Cat', 4:'Deer', 5:'Dog', 6:'Frog)', 7:'Horse', 8:'Ship', 9:'Truck', } #initialise GUI top=tk.Tk() top.geometry('800x600') top.title('Classificação de Images') top.configure(background='#00BFFF') label=Label(top,background='#00BFFF', font=('arial',15,'bold')) sign_image = Label(top) def classify(file_path): global label_packed image = Image.open(file_path) image = image.resize((30,30)) image = numpy.expand_dims(image, axis=0) image = numpy.array(image) print(image.shape) pred = model.predict_classes([image])[0] sign = classes[pred+1] print(sign) label.configure(foreground='#011638', text=sign) def show_classify_button(file_path): classify_b=Button(top,text="Classificar Imagem",command=lambda: classify(file_path),padx=10,pady=5) classify_b.configure(background='#364156', foreground='white',font=('arial',10,'bold')) classify_b.place(relx=0.79,rely=0.46) def upload_image(): try: file_path=filedialog.askopenfilename() uploaded=Image.open(file_path) uploaded.thumbnail(((top.winfo_width()/2.25),(top.winfo_height()/2.25))) im=ImageTk.PhotoImage(uploaded) sign_image.configure(image=im) sign_image.image=im label.configure(text='') show_classify_button(file_path) except: pass upload=Button(top,text="Carregar uma imagem",command=upload_image,padx=10,pady=5) upload.configure(background='#364156', foreground='white',font=('arial',10,'bold')) upload.pack(side=BOTTOM,pady=50) sign_image.pack(side=BOTTOM,expand=True) label.pack(side=BOTTOM,expand=True) heading = Label(top, text="Classificador de Imagens",pady=20, font=('arial',20,'bold')) heading.configure(background='#00BFFF',foreground='#364156') heading.pack() top.mainloop() Obrigado.
  18. Boa tarde P@P, estou a escrever porque peguei num ficheiro JSON, quero ler, contudo, no ficheiro aparece a codificação dos caracteres, como: "It is a biology book with God&apos;s perspective." : Imagem do ficheiro no notepad++ invés "It is a biology book with God's perspective." : https://www.amazon.com/Biology-Living-Creation-Third-Science/dp/0000092878 o que faço para converter e poder ler como no original? Cumps, jonhhy
  19. Boa tarde, quais os valores lógicos (símbolos ou por extenso) que devo usar neste campo e porque: entre símbolos (&, |, ~, ^) e por extenso (and, or, not, xor) https://kanoki.org/2020/01/21/pandas-dataframe-filter-with-multiple-conditions/ https://www.geeksforgeeks.org/difference-between-and-and-in-python/ Saudações Johnhy
  20. Boa tarde. Neste momento estou a desenvolver um trabalho de Python que envolve manipulação de ficheiros CSV, e surgiu o seguinte problema: Ao tentar colocar no 2º ficheiro csv uns dados do 1º ficheiro csv, o resultado é o seguinte: "['nota_da_1_freq', 'nota_da_2_freq', 'nota_trabalho', 'nota_1_miniteste', 'nota_2_miniteste', 'nota_3_miniteste', 'class_final']","[0 16 1 16 2 11 3 12 4 10 5 8 6 10 7 11 8 9,5 Name: nota_1F, dtype: object, 0 14 1 14 2 10 3 11 4 8 5 11 6 12 7 13 8 10 Name: nota_2F, dtype: int64, 0 15 1 15 2 12 3 17 4 12 5 16 6 12 7 20 8 12 Name: nota_TP, dtype: int64, 0 16 1 16 2 14 3 15 4 14 5 14 6 17 7 14 8 15 Name: nota_1MT, dtype: int64, 0 17 1 17 2 12 3 12 4 12 5 0 6 14 7 12 8 18 Name: nota_2MT, dtype: int64, 0 15 1 17 2 13 3 8 4 13 5 9 6 13 7 13 8 17 Name: nota_3MT, dtype: int64]" Os dados do 1º ficheiro CSV são os seguintes: numero_de_aluno;nome;turma;aulas_lecionadas;aulas_assistidas;nota_1F;nota_2F;nota_TP;nota_1MT;nota_2MT;nota_3MT 75897;Luís Briga;1;75;71;16;14;15;16;17;15 76574;Edgar Santos;1;75;57;16;14;15;16;17;17 74632;Pedro Sousa;4;75;41;11;10;12;14;12;13 74632;Gonçalo Pinto;3;75;57;12;11;17;15;12;8 74632;Ana Margarida;4;75;66;10;8;12;14;12;13 74632;Diana Carvalho;5;75;75;8;11;16;14;0;9 74632;Justino Pereira;1;75;21;10;12;12;17;14;13 74632;Tiago Sousa;4;75;72;11;13;20;14;12;13 74632;Dinis Pinto;2;75;70;9,5;10;12;15;18;17 O objetivo era colocar todos os dados alinhados conforme o cabeçalho. O meu código é o seguinte: import csv from operator import index from pickle import FALSE from numpy import append import pandas as pd tabela = pd.read_csv("alunos.csv", sep=";") row_list = [["nota_da_1_freq", "nota_da_2_freq", "nota_trabalho", "nota_1_miniteste", "nota_2_miniteste", "nota_3_miniteste", "class_final"], [tabela['nota_1F'], tabela['nota_2F'], tabela['nota_TP'], tabela['nota_1MT'], tabela['nota_2MT'], tabela['nota_3MT']]] with open('class.csv', 'w') as file: writer = csv.writer(file) writer.writerow(row_list) Desde já peço desculpa pela quantidade de informação, mas não estou mesmo a conseguir resolver este problema. Obrigado.
  21. # SEAL ADVENTURE - JOGO 1º SEMESTRE # GRUPO 3 # CAIO GUIMARÃES SA SILVA # MARCO AURÉLIO SODRÉ # SAMIRA DE BARROS CAVALCANTE # TAIGUARA TALES DA SILVA VITORINO import pygame from pygame.locals import* # import math, random, sys, os class Game(): def __init__(self): pygame.init() pygame.display.set_caption("Seal Adventure") self.running, self.playing = True, False self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False self.DISPLAY_W, self.DISPLAY_H = 800, 600 # Tamanho da tela self.display = pygame.Surface((self.DISPLAY_W,self.DISPLAY_H)) self.window = pygame.display.set_mode(((self.DISPLAY_W,self.DISPLAY_H))) self.font_name = 'fonte/PressStart2P-vaV7.ttf' #self.font_name = pygame.font.get_default_font() self.BLACK,self. BLUE = (0, 0, 0), (63, 255, 223) #Definindo cores self.main_menu = MainMenu(self) #Classes self.options = OptionsMenu(self) self.credits = CreditsMenu(self) self.curr_menu = self.main_menu def game_loop(self): while self.playing: self.check_events() if self.START_KEY: self.playing= False #INICIO # # # CONFIGURAÇÕES DE TELA ------------------------------------------------------------------ larguraTela, alturaTela = 1000, 500 metadeLargura = larguraTela / 2 metadeAltura = alturaTela / 2 areaTela = larguraTela * alturaTela tela = pygame.display.set_mode((larguraTela, alturaTela)) bg = pygame.image.load("Cenario/cenariogelo.jpeg") background = pygame.transform.scale(bg, (larguraTela, alturaTela)) pygame.display.set_caption("Seal Adventure") pygame.init() CLOCK = pygame.time.Clock() FPS = 45 BLACK = (0, 0, 0) # # # MUSICA DO JOGO ----------------------------------------------------------------------------------- pygame.mixer.music.load('Musicas/Snow02.ogg') pygame.mixer.music.play(-1) # # # PERSONAGEM --------------------------------------------------------------------------------- scale_hero=[100,100] left = [pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'desenhoesquerda.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 2.0.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 3.0.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'pertras1.png')),(scale_hero)) ] right = [pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'desenho.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 2.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 3.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'perfren1.png')),(scale_hero)) ] scale_bullet=[35,35] bullet_img = pygame.transform.scale(pygame.image.load(os.path.join('Bullets', 'poder.png')), (scale_bullet)) x = 100 y = 395 radius = 80 vel = 5 move_left = False move_right = False stepIndex = 0 class Hero: def __init__(self, x, y): # walk self.x = x self.y = y self.velx = 6 self.vely = 15 self.face_right = True self.face_left = False self.stepIndex = 0 # Jump self.jump = False # Bullet self.bullets = [] self.cool_down_count = 0 # Health self.hitbox = (self.x, self.y, 64, 64) self.health = 40 self.lives = 1 self.alive = True # kills #self.kills = 0 def move_hero(self, userInput): if userInput[pygame.K_RIGHT] and self.x <= larguraTela - radius: self.x += self.velx self.face_right = True self.face_left = False elif userInput[pygame.K_LEFT] and self.x >= 0: self.x -= self.velx self.face_right = False self.face_left = True else: self.stepIndex = 0 def draw(self, tela): self.hitbox = (self.x, self.y, 78, 90) pygame.draw.rect(tela, (255, 0, 0), (self.x + 30, self.y - 10, 40, 10)) if self.health >= 0: pygame.draw.rect(tela, (0, 255, 0), (self.x + 30, self.y - 10, self.health, 10)) if self.stepIndex >= 16: self.stepIndex = 0 if self.face_left: tela.blit(left[self.stepIndex // 4], (self.x, self.y)) self.stepIndex += 1 if self.face_right: tela.blit(right[self.stepIndex // 4], (self.x, self.y)) self.stepIndex += 1 def jump_motion(self, userInput): if userInput[pygame.K_SPACE] and self.jump is False: jumpvar = pygame.mixer.Sound('Musicas/SFX_Jump_17.wav') jumpvar.play() self.jump = True if self.jump: self.y -= self.vely * 2 self.vely -= 1 if self.vely < -15: self.jump = False self.vely = 15 def direction(self): if self.face_right: return 1 if self.face_left: return -1 def cooldown(self): if self.cool_down_count >= 20: self.cool_down_count = 0 elif self.cool_down_count > 0: self.cool_down_count += 1 def shoot(self): self.hit() self.cooldown() if (userInput[pygame.K_f] and self.cool_down_count == 0): shootvar=pygame.mixer.Sound('Musicas/fogo.wav') shootvar.play() bullet = Bullet(self.x, self.y, self.direction()) self.bullets.append(bullet) self.cool_down_count = 1 #scale_hero = [100, 100] ataque = pygame.image.load(os.path.join('Personagens', 'ataque.png')) tela.blit(ataque, (90,90)) for bullet in self.bullets: bullet.move() if bullet.off_screen(): self.bullets.remove(bullet) def hit(self): for enemy in enemies: for bullet in self.bullets: if enemy.hitbox[0] < bullet.x < enemy.hitbox[0] + enemy.hitbox[2] and enemy.hitbox[ 1] < bullet.y < enemy.hitbox[1] + enemy.hitbox[3]: dano = pygame.image.load(os.path.join('Personagens', 'dano.png')) tela.blit(dano, (100, 100)) enemy.health -= 25 player.bullets.remove(bullet) class Bullet: def __init__(self, x, y, direction): self.x = x + 70 self.y = y + 30 self.direction = direction def draw_bullet(self): tela.blit(bullet_img, (self.x, self.y)) def move(self): if self.direction == 1: self.x += 15 if self.direction == -1: self.x -= 15 def off_screen(self): return not (self.x >= 0 and self.x <= larguraTela) # INIMIGO ---------------------------------------------------------------------------------------- scale_enimy=[100,100] left_enemy = [pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.png')),(scale_enimy)) ] right_enemy = [pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.0.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.0.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.0.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.0.png')),(scale_enimy)) ] class Enemy: def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction self.stepIndex = 0 # Health self.hitbox = (self.x, self.y, 64, 64) self.health = 40 self.kills=0 #self.ultimakills=0 def step(self): if self.stepIndex >= 32: self.stepIndex = 0 def draw(self, tela): self.hitbox = (self.x, self.y, 78, 90) pygame.draw.rect(tela, (255, 0, 0), (self.x + 20, self.y - 10, 40, 10)) if self.health >= 0: pygame.draw.rect(tela, (0, 255, 0), (self.x + 20, self.y - 10, self.health, 10)) self.step() if self.direction == left: tela.blit(left_enemy[self.stepIndex // 8], (self.x, self.y)) if self.direction == right: tela.blit(right_enemy[self.stepIndex // 8], (self.x, self.y)) self.stepIndex += 1 def move(self): self.hit() if self.direction == left: self.x -= 10 if self.direction == right: self.x += 9 def hit(self): if player.hitbox[0] < enemy.x + 32 < player.hitbox[0] + player.hitbox[2] and player.hitbox[1] < enemy.y + 32 < player.hitbox[1] + player.hitbox[3]: if player.health > 0: player.health -= 1 if player.health == 0 and player.lives > 0: player.lives -= 1 player.health = 40 elif player.health == 0 and player.lives == 0: player.alive = False def off_screen(self): return not (self.x >= -80 and self.x <= larguraTela + 30) # # # FUNÇÃO TELA ------------------------------------------------------------------------------ def draw_game(): tela.fill(BLACK) tela.blit(background, (0, 0)) # Draw Playerf player.draw(tela) # Draw Bullets for bullet in player.bullets: bullet.draw_bullet() # Draw Enemies for enemy in enemies: enemy.draw(tela) # Player Health if player.alive == False: tela.fill((0, 0, 0)) SCALE_FUNDO=[1000,500] SCALE_FUNDO= pygame.transform.scale(pygame.image.load(os.path.join('Cenario/menu.jpeg')), (SCALE_FUNDO)) tela.blit(SCALE_FUNDO, (0,0)) font = pygame.font.Font('fonte/PressStart2P-vaV7.ttf', 32) text = font.render('GAME OVER! pressione R', True, (138, 47, 47)) textRect = text.get_rect() textRect.center = (metadeLargura, metadeAltura) tela.blit(text, textRect) #self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem if userInput[pygame.K_r]: player.alive = True player.lives = 1 player.health = 40 #kills = 0 font = pygame.font.Font('fonte/PressStart2P-vaV7.ttf', 27) text = font.render('Mortos: ' + str(kills) + ' Vidas: ' + str(player.lives), True, (63, 255, 223)) # text2 = font.render('Última pontuação de mortes: ' + str(ultimakills) , True, (63, 255, 223)) # text3 = font.render('Recorde de mortes: ' + str(highkills) , True, (63, 255, 223)) tela.blit(text, (180, 20)) #tela.blit(text2, (180, 55)) #tela.blit(text3, (180, 90)) pygame.display.update() CLOCK.tick(FPS) # ultimakills=0 #highkills=kills #contador = kills player = Hero(250, 320) enemies = [] kills=0 # # # LOOP ------------------------------------------------------------------------ run = True while run: # # # FECHAR TELA ------------------------------------------------------------ for i in pygame.event.get(): if i.type == pygame.QUIT: pygame.quit() sys.exit() # Input userInput = pygame.key.get_pressed() # shoot player.shoot() # Movement player.move_hero(userInput) player.jump_motion(userInput) # # # CONTROLE INIMIGOS if len(enemies) == 0: rand_nr = random.randint(0, 1) if rand_nr == 1: enemy = Enemy(1010, 320, left) enemies.append(enemy) if rand_nr == 0: enemy = Enemy(0, 320, right) enemies.append(enemy) for enemy in enemies: enemy.move() if enemy.off_screen() or enemy.health <= 0: enemies.remove(enemy) if enemy.health <= 0: kills += 1 # Draw game in windows draw_game() #FIM def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running, self.playing = False, False self.curr_menu.run_display = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: self.START_KEY = True if event.key == pygame.K_BACKSPACE or event.key == pygame.K_ESCAPE: self.BACK_KEY = True if event.key == pygame.K_DOWN or event.key == pygame.K_s: self.DOWN_KEY = True if event.key == pygame.K_UP or event.key == pygame.K_w: self.UP_KEY = True def reset_keys(self): self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False def draw_text(self, text, size, x, y ): #Cor da letra, tamanho font = pygame.font.Font(self.font_name,size) text_surface = font.render(text, True, self.BLUE) text_rect = text_surface.get_rect() text_rect.center = (x,y) self.display.blit(text_surface,text_rect) class Menu(): def __init__(self, game): self.game = game self.mid_w, self.mid_h = self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 self.run_display = True self.cursor_rect = pygame.Rect(0, 0, 130, 130) self.offset = - 100 def draw_cursor(self): self.game.draw_text('▶', 20, self.cursor_rect.x, self.cursor_rect.y) def blit_screen(self): self.game.window.blit(self.game.display, (0, 0)) pygame.display.update() self.game.reset_keys() class MainMenu(Menu): def __init__(self, game): Menu.__init__(self, game) self.state = "Iniciar" self.startx, self.starty = self.mid_w, self.mid_h+80 self.tutorialx, self.tutorialy = self.mid_w, self.mid_h + 120 self.creditsx, self.creditsy = self.mid_w, self.mid_h + 160 self.exitx, self.exity = self.mid_w, self.mid_h + 200 self.cursor_rect.midtop = (self.startx + self.offset, self.starty) def display_menu(self): # Aparência do Menu self.run_display = True menuprincipal = pygame.image.load('Cenario/menu.jpeg') menuprincipal2 = pygame.transform.scale(menuprincipal, (800, 600)) pygame.mixer.music.load('Musicas/prologue.mp3') pygame.mixer.music.play(-1) while self.run_display: self.game.check_events() self.check_input() self.game.display.blit(menuprincipal2,(0,0)) # Preenchendo tela com imagem self.game.draw_text("Jogar", 20, self.startx, self.starty) self.game.draw_text("Como Jogar?", 20, self.tutorialx, self.tutorialy) self.game.draw_text("Créditos", 20, self.creditsx, self.creditsy) self.game.draw_text("Sair", 20, self.exitx, self.exity) self.game.draw_text("Voltar: ESC", 10, self.mid_w - 200, self.mid_h + 260) self.game.draw_text("Avançar: Enter", 10, self.mid_w + 200, self.mid_h + 260) self.draw_cursor() self.blit_screen() def move_cursor(self): # Movimentação do Cursor (Setinha) if self.game.DOWN_KEY: # Usando seta pra baixo if self.state == 'Iniciar': self.cursor_rect.midtop = (self.tutorialx + self.offset, self.tutorialy) self.state = 'Como Jogar?' elif self.state == 'Como Jogar?': self.cursor_rect.midtop = (self.creditsx + self.offset, self.creditsy) self.state = 'Créditos' elif self.state == 'Créditos': self.cursor_rect.midtop = (self.exitx + self.offset, self.exity) self.state = 'Sair' elif self.state == 'Sair': self.cursor_rect.midtop = (self.startx + self.offset, self.starty) self.state = 'Iniciar' elif self.game.UP_KEY: # Usando ceta pra cima if self.state == 'Iniciar': self.cursor_rect.midtop = (self.exitx + self.offset, self.exity) self.state = 'Sair' elif self.state == 'Sair': self.cursor_rect.midtop = (self.creditsx + self.offset, self.creditsy) self.state = 'Créditos' elif self.state == 'Como Jogar?': self.cursor_rect.midtop = (self.startx + self.offset, self.starty) self.state = 'Iniciar' elif self.state == 'Créditos': self.cursor_rect.midtop = (self.tutorialx + self.offset, self.tutorialy) self.state = 'Como Jogar?' def check_input(self): self.move_cursor() if self.game.START_KEY: if self.state == 'Iniciar': self.game.playing = True elif self.state == 'Como Jogar?': self.game.curr_menu = self.game.options elif self.state == 'Créditos': self.game.curr_menu = self.game.credits elif self.state == 'Sair': self.game.exiting = sys.exit() self.run_display = False class OptionsMenu(Menu): def __init__(self, game): Menu.__init__(self, game) self.arrowx, self.arrowy = self.mid_w, self.mid_h + 0 self.rightx, self.righty = self.mid_w, self.mid_h + 60 self.leftx, self.lefty = self.mid_w, self.mid_h + 90 self.shotx, self.shoty = self.mid_w, self.mid_h + 120 self.shotz, self.shoth = self.mid_w, self.mid_h + 150 def display_menu(self): self.run_display = True menuprincipal = pygame.image.load('Cenario/menu.jpeg') menuprincipal2 = pygame.transform.scale(menuprincipal, (800, 600)) self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem while self.run_display: self.game.check_events() self.check_input() self.game.display.fill((0, 0, 0)) self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem self.game.draw_text('Tutorial', 40, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 120) self.game.draw_text("Teclado", 30, self.arrowx, self.arrowy) self.game.draw_text("Andar para Direita: →", 15, self.rightx, self.righty) self.game.draw_text("Andar para Esquerda: ←", 15, self.leftx, self.lefty) self.game.draw_text("Disparar Tiro: F", 15, self.shotx, self.shoty) self.game.draw_text("Pular: Barra de Espaço", 15, self.shotz, self.shoth) self.game.draw_text("Voltar: ESC", 10, self.mid_w - 200, self.mid_h + 260) self.game.draw_text("Avançar: Enter", 10, self.mid_w + 200, self.mid_h + 260) self.blit_screen() def check_input(self): if self.game.BACK_KEY: self.game.curr_menu = self.game.main_menu self.run_display = False elif self.game.START_KEY: pass class CreditsMenu(Menu): def __init__(self, game): Menu.__init__(self, game) def display_menu(self): self.run_display = True menuprincipal = pygame.image.load('Cenario/menu.jpeg') menuprincipal2 = pygame.transform.scale(menuprincipal, (800, 600)) while self.run_display: self.game.check_events() if self.game.START_KEY or self.game.BACK_KEY: self.game.curr_menu = self.game.main_menu self.run_display = False self.game.display.fill(self.game.BLACK) self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem self.game.draw_text('CRIADORES DO SEAL ADVENTURE', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 4 - 20) self.game.draw_text('CAIO GUIMARÃES SA SILVA', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 10) self.game.draw_text('MARCO AURÉLIO SODRÉ', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 30) self.game.draw_text('SAMIRA DE BARROS CAVALCANTE FIGUEIREDO', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 50) self.game.draw_text('TAIGUARA TALES DA SILVA VITORINO', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 70) self.game.draw_text("Voltar: ESC", 10, self.mid_w - 200, self.mid_h + 260) self.game.draw_text("Avançar: Enter", 10, self.mid_w + 200, self.mid_h + 260) self.blit_screen() def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running, self.playing = False, False self.curr_menu.run_display = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: self.START_KEY = True if event.key == pygame.K_BACKSPACE or event.key == pygame.K_ESCAPE: self.BACK_KEY = True if event.key == pygame.K_DOWN or event.key == pygame.K_s: self.DOWN_KEY = True if event.key == pygame.K_UP or event.key == pygame.K_w: self.UP_KEY = True # INICIALIDADOR DO JOGO g = Game() while g.running: g.curr_menu.display_menu() g.game_loop() #Gostaria de algumas ajuda ,do arquivo abaixo: #1º - Não estou conseguindo zerar o contador de mortes, quando se inicia uma nova partida. Contador fica acumulado. #2º - Não estou conseguindo executar um sprite ,quando eu aperto o botão de pulo (space) e o botão de ataque (Tecla F). #3º - Não estou conseguindo fazer o placar de mais mortes e última quantidade de mortes.
  22. Segundo uma notícia do jornal Público, os programas de matemática do ensino secundário vão incluir programação estatística utilizando Python, assim como literacia financeira. Claro que tudo isto ainda está numa fase de discussão.
  23. Boa tarde Malta, espero que estejam bem. Conseguem-me dizer onde faço a indentação mal? def greater(s1,s2,s3): if s1 > s2: if s1 > s3: return s1 else: return s3 elif s2 > s3: return s2 else: return s3 Imagem do erro no Notebook cumps. jonhhy
  24. Bom dia, tenho uma dúvida sobre como faço para verificar a diferença das implementações das funções nas várias linguagens de programação. Uma vez ao verificar a linguagem R , verifico que a implementação difere do python e gostaria de saber os fundamentos para perceber como a função está implementada num caso e no outro. mtcars.head() Error: could not find function "mtcars.head" # Call head() on mtcars head(mtcars) ------------------------------ Suppose you want to output the first and last 10 rows of the iris data set. In R: data(iris) head(iris, 10) tail(iris, 10) In Python (scikit-learn required to load the iris data set): import pandas as pd from sklearn import datasets iris = pd.DataFrame(datasets.load_iris().data) iris.head(10) iris.tail(10) ------- fonte: https://stackoverflow.com/questions/25211220/python-equivalent-of-rs-head-and-tail-function
  25. estou criando uma consulta whois em python import whois dominio = "dominio.com" consultaWhois = whois.whois(dominio) print consultaWhois.email print consultaWhois["email"] print consultaWhois.txt podem me dizer como corrigir esse erro
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.