Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried to write some line of code for quick sort algorithm using numpy algorithm.
But It seems not working properly .
Can you help me solve it ?
import numpy as np
def quick_sort_np(narr):
"""A numpy version of quick sort algorithm"""
narr = np.array(narr)
if len(narr)<= 1 :
return narr
p = narr[-1] # I take the last item as pivot by convension
print (f"at this level the pivot is {p}")
lnarr = narr[narr<p]
print (f"----------------------> left arr is {lnarr}")
rnarr = narr[narr>p]
print (f"----------------------> right arr is {rnarr}")
return quick_sort_np(lnarr) + p + quick_sort_np(rnarr)
in case of [1,2,6,5,4,8,7,99,33] as input my code returns nothing and that's the question.
+ acting on np.arrays is element wise addition, not concatenation.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
My teacher has asked me to implement an array using python without using any inbuilt functions but I am confused and I don't know how to? this is the complete question...
Write a program in Python to implement the “Array” data structure. Perform operations like add or insert, delete or remove and display. Your program should be able to add/insert at any position in an array or remove/delete any element from an array. Take care of extreme conditions such as an empty array or full array and display an appropriate message to the user.
any help would be highly appreciated.
You can store the array in a list L, and write a function for each list operation. For example, to search for an element x in a list L and return the index of the first occurrence of x in L, rather than using the built-in function index, you would implement the linear search algorithm. So, the following code would be incorrect because it uses the built-in function index:
def search(L,x):
return L.index(x)
The following code would be acceptable because you are implementing the linear search algorithm yourself (presumably your teacher wants you to write programs from scratch, which is very good practice):
def search(L,x):
#input: a list L and an element x
#output: the index of first occurrence of x in L, or -1 if x not in L
n = len(L)
for i in range(n):
if L[i] == x:
return i
return -1
L=[3,1,4,2]
print(search(L,7))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am not sure where I went wrong with my below code, where I used two for loops to firstly iterate statename and then iterate each dictionary that contains that specific statename.
I finally resolved this via my second code (the right code on the snip) however would be keen to know why the first didn't work.
The file used is a census file with statename, countyname (a subdivision of the state) and population being the columns.
Couldn't work with the following snip (on the left) where the error is 'string indices must be integers':
As others have already suggested, please read up on providing a Minimal, Reproducible Example. Nevertheless, I can see what went wrong here. When you loop through for d in census_df, this actually loops through the column names for your data frame, i.e. SUMLEV, REGION etc. This is presumably not what you had in mind.
Then your next line if d['STNAME']==c causes an error, as the message says, because string indices must be integers. In this instance you are trying to index a string using another string STNAME.
If you really want that first method to work, try using iterrows:
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for index, row in census_df.iterrows():
if row['STNAME']==c:
count+=1
list.append(count)
return(max(list))
answer_five()
Don't know why the pic is not coming up...sorry first timer here!
the first code that I tried which I have questions over are: (regarding string indices must be integers):
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for d in census_df:
if d['STNAME']==c:
count+=1
return list.append(count)
answer_five()
The second code helped resolve my question is:
max_county=[]
state_unique=census_df['STNAME'].unique()
def answer_five():
for c in state_unique:
df1=census_df[census_df['STNAME']==c]
max_county.append(len(df1))
return max(max_county)
answer_five()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am a Python novice and need help. I tried searching, but couldn't find posts relevant to what I need.
I have a data frame containing a column called diet which contains many similar values like 'Only Vegetarian', 'Mostly Vegetarian', 'Strictly Vegetarian', 'Veggie' etc. How do I combine these values into a single value called say 'Vegetarian'?
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'col1': ['Only Vegetarian', 'Mostly Vegetarian', 'Strictly Vegetarian', 'Veggie','Meat']})
df1['col2'] = np.where(df1.col1.str.contains('Vege'), 'Vegeterian', 'Not Vegeterian')
You can make a dummy variable by encoding your rule in a function and using pd.Series.apply
def check_veg(x):
# The elipse below signifies you providing all the values somehow
if x in ["Veggie", "Mostly Vegetarian", ...]:
return 1
else:
return 0
df["isVeg"] = df["diet"].apply(check_veg)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have to set the result of
df.groupby(['région'])['counts'].sum())
as the column c2 of my dataframe.
So I do this:
df['c2'] = pd.to_numeric(df.groupby(['région'])['counts'].sum()).astype(float)
Thus
pd.to_numeric(df.groupby(['région'])['counts'].sum()).astype(float)
has type float, and so df['c2'] should also have type float.
However, when I tried to print the column of my dataframe df['c2'] all values are NaN.
How can I solve this?
EDIT 1:
My code is here
In your code, after this part:
import numpy as np
d_copy = d.copy()
Do this:
d_copy['counts2'] = d_copy.groupby(['region'])['counts'].transform('count')
Results:
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to save each second line of a text file into a different element in list. I have studied multiple threads but i need a way so as to use this list and pick a random element from this.
Comprehension as way to solve this:
l = [line for i, line in enumerate(open('list.txt')) if i % 2 == 1 ]
print(l)
Pandas allows you to skip rows according to a function. For example:
import pandas as pd
# read file, excluding even rows
df = pd.read_csv('myfile.csv', skiprows=lambda x: (x+1)%2 == 0)
# convert to list
df_list = df.values.tolist()
This will return a list with elements relating to even lines from the input file.