Posts by Ed S • 2,057 points
164 posts
-
0
votes0
answers46
viewsQ: Python script to calculate a series
Data n, print the value of Sn = 1/n + 2/(n-1) + 3/(n-2) + ... + n. This is what I tried to do: n =2 soma =1 for i in range(1,n+1): if n>i: soma+=i/n + i/(n-1) But it only works when n=2. Someone…
python-3.xasked Ed S 2,057 -
1
votes1
answer123
viewsQ: Displaying only integer values on X-axis in matplotlib chart
I would like to show X-axis only integer values of K: k in range(20) import matplotlib.pyplot as plt %matplotlib inline X = [k for k in range(20)] y = rmse_val plt.plot(X,y,color='green' ,…
-
5
votes1
answer95
viewsQ: Get equivalent expression to list(zip(list, Heights)) using the map() function
Be: heights = [x*0.0254 for x in [69,77,54]] lista = [69,77,54] The expression: print(list(zip(lista,heights))) has as output: [(69, 1.7526), (77, 1.9558), (54, 1.3716)] My goal is to get the same…
-
3
votes2
answers1637
viewsQ: How to print 4 triangles patterns next to each other in Python?
I need to write a program that prints 4 triangles patterns, one next to the other, separated by three horizontal spaces, as in this image below: To solve this, I wrote the following code: for i in…
-
1
votes1
answer442
viewsQ: Adding a column of numbers 1 to a numpy array
Let X be the numpy array below: array([ 6.1101, 5.5277, 8.5186, 7.0032, 5.8598, 8.3829, 7.4764, 8.5781, 6.4862, 5.0546, 5.7107, 14.164 , 5.734 , 8.4084, 5.6407, 5.3794, 6.3654, 5.1301, 6.4296,…
-
1
votes1
answer73
viewsA: Displaying the tags of a web page with indentation proportional to the depth of the element in the document tree structure
The methods handle_starttag() and handle_endtag() need to be reset. Each should display the name of the element corresponding to the tag, set back appropriately. Indentation is an integer value…
-
1
votes1
answer73
viewsQ: Displaying the tags of a web page with indentation proportional to the depth of the element in the document tree structure
Issue: Develop the Myhtmlparser class as an Htmlparser subclass which, when fed with an HTML file, displays the names of the start and end tags in the order they appear in the document, and with a…
-
1
votes1
answer154
viewsQ: Extracting email addresses from a web page using regular expressions in python
What I did: from urllib.request import urlopen from re import findall def emails(url): content = urlopen(url).read().decode() #print(content) padrao =…
-
3
votes2
answers420
viewsQ: Regular expression that recognizes Portuguese words (accented) using Python
Develop the function frequency(), that takes a string as input, calculates the frequency of each word in the string and returns a dictionary that maps words in the string at its frequency. You must…
-
0
votes1
answer334
viewsQ: How to do a file search using Python
Problem: Implement the function search(), which accepts as input the name of a file and the path of a folder, to search for the file in the folder and in any folder contained therein, directly or…
-
3
votes2
answers145
viewsQ: Recursive method to display the representation of an integer in a base
Write a recursive method base() which accepts a non-negative integer n and a positive whole 1 < b < 10 and present the basic representation b of the whole n. >>> base(0, 2) 0…
-
-1
votes2
answers94
viewsA: Program to remove ONLY a copy of duplicate values from a list
def rem(lista): i = 0 seen = set() nova_lista = lista.copy() while i < len(lista): # print(lista[i]) if lista.count(lista[i]) >= 2: if lista[i] not…
-
-2
votes2
answers94
viewsQ: Program to remove ONLY a copy of duplicate values from a list
Write a method rem() that accepts as input a list possibly containing duplicate values, and return a copy of the list where a copy of each duplicate value is removed. What I did: def rem(lista): i =…
-
1
votes2
answers75
viewsQ: Counting the number of executed operations over the same input for a recursive call
idea: Compare a recursive version of the exponentiation implementation with a non-recursive version. Recursive version: def power(base,expoente): global cont if base == 1: return 1 elif expoente ==…
-
1
votes2
answers100
viewsQ: Recursive program that accepts a non-negative integer as input and displays its vertically stacked digits
I developed the recursive function vertical(), which accepts a non-negative integer as input and displays its vertically stacked digits. For example: >>> vertical(3124) 3 1 2 4 Solution:…
-
1
votes1
answer111
viewsQ: Program to check number of words and a sentence of a text file
text file used: https://easyupload.io/j5agtq The method is part of a class called Arqtext Objective: The method does not use input and returns, in a tuple object, (1) the average number of words per…
-
2
votes2
answers98
viewsQ: What is the difference between a string defined within a text file and another defined as a variable?
Imagine the following: texto = "They fly quickly over the snow in their sledges; the motion is pleasant, and, in my opinion, far more agreeable than that of an English stagecoach" texto1 =…
-
1
votes2
answers149
viewsQ: How to extract only words from any text, ignoring punctuation and uppercase letters?
Be the text below: This is the most favourable period for travelling in Russia. They fly quickly over the snow in their sledges; the motion is pleasant, and, in my opinion, far more agreeable than…
-
0
votes2
answers107
viewsQ: How to partition people in a network of friends?
In your class, many students are friends. Let’s assume that two students who share a friend should be friends; in other words, if students 0 and 1 are friends and students 1 and 2 are friends, then…
-
1
votes3
answers344
viewsA: How to read a text file and generate a dictionary?
def simbolo(arquivo): empresas = {} with open("nasdaq.txt") as f: texto = f.read() #print(texto) caracteres = ["\t"] for i in caracteres: texto =…
-
2
votes3
answers344
viewsQ: How to read a text file and generate a dictionary?
Write the function símbolo() who accepts a string (the name of a file: Nasdaq.txt) as input. The archive will have company names and stock symbols. In this file, a company name will occupy a line…
-
0
votes3
answers6054
viewsA: Draw a rectangle using Python repeating structures
larg = int(input("Digite a largura: ")) alt = int(input("Digite a altura: ")) i=1 while i <=alt: if i==1 or i==alt: print(larg*"#") i+=1 elif larg== alt: …
-
-1
votes2
answers50
viewsQ: Overwriting the occurrences of a string in a text file. Differences presented with several file opening modes
The goal is to replace each occurrence of the word "secret" with "XXXX" in the Crypto.txt file. My code: def crypto(arquivo): #palavras = [] with open(arquivo,"r") as crypto: data = crypto.read()…
-
3
votes1
answer248
viewsQ: Formatted printing that replaces the use of . format() in python versions from 3.6 onwards. How to use?
We know that: "{0}:{1}:{2}".format(hora,minuto, segundo) is equivalent to: f"{hora}:{minuto}:{segundo}" What is the equivalent of the expression below using the notation f" " ?…
-
-2
votes2
answers100
viewsQ: What is wrong with python below? Any suggestions for another solution?
Problem: Having a 5 5 matrix filled with random (real) values between 0 and 99, show which is the second highest value existing in the matrix. Can’t use numpy or similar. My solution: n=2 def…
-
3
votes1
answer153
viewsQ: Any more pythonic way to solve the problem below?
Create a function that returns the expression value: 2/3 + 3/5 + 4/7 + 5/9 + ... + n/m, to a user-defined value of n. Check that the user-defined n value is positive and, if not, request another…
-
1
votes1
answer175
viewsQ: How to select ALL lines that have a value exceeding 3 or -3 in a pandas dataframe?
Be it: data = pd.DataFrame(np.random.randn(1000, 4)) I found the following to select ALL lines that have a value exceeding 3 or -3: data[(np.abs(data) >3).any(1)] I didn’t understand Any’s…
-
1
votes1
answer401
viewsQ: How to use a quadratic regression model?
I’m trying to learn how to adjust a quadratic regression model. The dataset can be downloaded at: https://filebin.net/ztr9har5nio7x78v Let Adjsaleprice be the target variable and…
-
1
votes1
answer151
viewsQ: Validating a model with cross validation (logistic regression). What is Grid search for?
scores = cross_val_score(logmodel,y_test.astype(float).reshape(-1, 1),predictions.reshape(-1, 1), scoring="neg_mean_squared_error",cv=10) log_rmse_scores = np.sqrt(-scores) def…
machine-learningasked Ed S 2,057 -
2
votes2
answers1020
viewsQ: How to balance classes in a machine Learning regression problem with Python?
Problem using the dataset of the book "Hands-On Machine Learning with Scikit-Learn and Tensorflow" https://github.com/ageron/handson-ml dataset of house prices. Objective: to create a model of house…
-
0
votes1
answer70
viewsQ: Valueerror in Kfold from Scikit-Earn: My dataset has two classes! What’s going on?
I tried to cross-validate with a logistic regression using the Scikit-Learn . Follows the code: kf = KFold(n_splits=5, random_state=None, shuffle=False) kf.get_n_splits(previsores) for train_index,…
-
0
votes1
answer1113
viewsQ: Merging two columns into a new column named 'Class' (dataframe Pandas)
df_downsampled[df_downsampled['attack_cat']=="DoS"] Take all the dataframe 'df_downsampled' where the column 'attack_cat' has the value Dos. Dataset:…
-
-2
votes1
answer1290
viewsQ: Pycharm build error: can’t find python libraries 3.6
Operating System: Ubuntu 16.04 64 bits Python 3.6 installed via apt-get When compiling a program in the terminal using: python3.6 programa.py No error is presented. When running the same program…
-
3
votes0
answers69
viewsQ: Error executing pycuda code: "nvcc fatal : Value 'sm_61' is not defined for option 'gpu-Architecture"
I just installed the pycuda on Ubuntu 16.04 and I’m trying to check if it’s working. I’m trying to execute: #https://documen.tician.de/pycuda/tutorial.html import pycuda.driver as cuda import…
-
0
votes2
answers6913
viewsA: Counting Nan and null values in a pandas dataframe
1 and 2: how much Nan data is in the above dataset -> po.Isna(). sum(). sum()
-
0
votes1
answer590
viewsQ: Code evaluation: Logistic regression with K fold validation. Is that correct?
The code below is an attempt to make a logistic regression with k fold cross validation. The idea is to take the confusion matrices generated in each fold and then generate an average confounding…
-
1
votes2
answers6913
viewsQ: Counting Nan and null values in a pandas dataframe
Imagine we have a CSV file called.csv data: col1 col2 col3 col4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 33 44 import numpy as np import pandas as pd po = pd.read_csv('/dados.csv') My goal is to better…
-
2
votes1
answer1686
viewsQ: sklearn’s classification_report and confusion_matrix: do the values not match?
Model: logistic regression with sklearn. I decided to compare the results shown in the classification_report, calculating them using the confusion matrix but apparently the results do not match:…
-
1
votes1
answer156
viewsQ: Classification of network attack data (attack or no attack)
I’m using the dataset: https://www.unsw.adfa.edu.au/unsw-canberra-cyber/cybersecurity/ADFA-NB15-Datasets/ The goal is to classify a sample as attack or no attack. A good idea would be to use…
-
2
votes1
answer95
viewsQ: Problems with incorrect data in a dataset (using Pandas)
I have a dataset called Auto.csv, which has the form: mpg cylinders displacement horsepower weight acceleration year origin name 18 8 307 130 3504 12 70 1 chevrolet chevelle malibu 15 8 350 165 3693…
-
0
votes1
answer530
viewsA: How to print only the first column of a dataset with numpy?
I managed to solve by making a Slice of dataframe: date[0:,0:1] -> will only take the first column of the entire dataset. The program gets: import numpy as np data =…
-
1
votes1
answer3590
viewsQ: Sum all columns of an array using numpy. Is there a better way to do it?
I did so: import numpy as np #soma de todas as colunas de mat! mat = np.arange(1,26).reshape(5,5) print(mat) lista =[] for i in np.arange(0,len(mat)): lista.append(np.sum(mat[0:,i:i+1]))…
-
0
votes1
answer530
viewsQ: How to print only the first column of a dataset with numpy?
How to print only the first column of a dataset with numpy? My code: import numpy as np data = np.genfromtxt("iris.data",delimiter = ",",usecols=(0,1,2,3)) print(data) My dataset (part of it):…
-
0
votes1
answer170
viewsQ: Receiving Nan (not a number) when reading a file. CSV with numpy
Using python 3.6.5 import numpy as np valores = np.genfromtxt("arquivo.csv",delimiter = ";",skip_header = 1) print(valores) CSV file.: Valores1,Valores2,Valores3 10,20,30 40,50,60 70,80,90 34,54,23…
-
2
votes2
answers789
viewsQ: Replace all characters in a string with another character
def getGuessedWord(secretWord, lettersGuessed): secretWord_copy = "" for i in secretWord: print(i) secretWord_copy = secretWord.replace(i," _ ") print(secretWord_copy) secretWord = 'apple' I’m…
-
0
votes2
answers106
viewsQ: Function that determines whether all letters contained in one string are in the other
def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the…
-
0
votes2
answers322
viewsQ: How to implement Fibonacci more efficiently using dictionaries?
One recursive Fibonacci implementation is: def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) The problem is that it is somewhat inefficient, since, for example, to…
-
3
votes1
answer948
viewsQ: Determine the key of a dictionary that contains the highest amount of values
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') Be the dictionary animals defined above. The…
-
4
votes4
answers6745
viewsQ: How to implement a recursive MDC calculation algorithm in Python?
Non-recurring version is below: def mdc(a,b): while b !=0: resto = a % b a = b b = resto return a print(mdc(50,2)) A recursive attempt would be: def mdc(a, b): if b == 0: return a resto = a % b a =…
-
0
votes2
answers4695
viewsA: How to change the value of a variable by function in Python?
def func(a): global x x = 2 + 3 x = 7 func(x) print(x)