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))
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am trying to rewrite go code to python and I don't understand how the make() function in Golang works.
As an example I have this code which I'm trying to rewrite to Python:
a = make([]string, 1)
b = make([]int, 1)
c = make(map[string]string)
Any help is appreciated.
No need to make anything in Python... or in other words, no need to write a function that mimics make. Unlike Go where you have to be explicit about allocating something, in Python this is implicit as objects are allocated automatically on creation for you.
a = make([]string, 1): this is a slice of string of size 1 and capacity 1, in Python you can just create an empty list instead: a = [] and then .append() strings into it. Unlike Go for slices or arrays, Python does not require all elements of a list to be of the same type. If you want you could create a = [None] just to be able to index the list right away (in general a = [default_value] * size).
b = make([]int, 1): same here, just b = [] or b = [0] if you need to index the list right away. Note that Go initializes all elements to 0 for []int.
c = make(map[string]string): this creates a map with string as keys and values. Closest thing in Python would be a dictionary: c = {}. And again, you are not constrained by types in Python so you can later do c["foo"] = "bar" without a problem.
NOTE THAT Go slices have different semantics than Python slices. Doing a[1:10] in Go creates a slice that is merely a view on the underlying object, while in Python a[1:10] potentially copies all the elements in the range creating a new object (this is true for the built-in list and tuple).
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 1 year ago.
Improve this question
I have the below JSON response, I want to write a function that:
runs through the response looking for a match of 'risk-level' = [medium OR high]
if match found returns the corresponding alert-id in a list / array format (I think we should use .append here)
if no match is found, exit the program (I'm pretty sure it would "exit()" here)
I have managed to get it to match / find one input and bring back that response, I'm just struggling with feeding it a list with an "OR" logic to bring back an independent result.
[
{'event-num': 5520, 'alert-id': '6e310403-ca53-32ut-aec6-16ffc648f7b7', 'risk-level': 'very-low'},
{'event-num': 5521, 'alert-id': '0a6b15b7-3db3-2x7t-b4ab-b023cfb85eaf', 'risk-level': 'low'},
{'event-num': 5523, 'alert-id': '6e310403-3db3-4b5f-cehd-16ffc648f7b7', 'risk-level': 'medium'},
{'event-num': 5523, 'alert-id': '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf', 'risk-level': 'high'}
]
You could use .append() as you mentioned, or, you could do this in a quick list comprehension.
Let's say your list is called events.
risky_events = [event['alert-id']
for event in events
if event['risk-level'] in {'medium','high'}]
The above code simply creates a list of matching risk levels. How would you use the snippet above to implement your exit() requirement? You would need to check if the list created above was empty. Give it a try.
What went wrong in the approach you took? Did you try using .append() yourself? Look up the Python docs section on lists to understand how append works, and give that approach a try.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So in my niche use case I want to create a hash map in python to store a large list dataset. This list has a key value as a tuple (i.e (1,2)) and my goal is to search the list and see if the tuple exists.
I know this is achievable with a regular list but I wanted the time complexity of O(1) with the hash map functionality. But when adding elements to the dictionary, I am doing this:
dictionary[(1,2)] = None
Because I couldn't care less about the value associated with the key.
Is this good coding practice or is there something else I should use?
If you don't give a toss about the value, you can use a set. From the python source code (line 4 of Objects/setobject.c):
Derived from Lib/sets.py and Objects/dictobject.c.
If you need to iterate over a set, you should use a list or do the conversion as needed.
I would suggest using defaultdict. By default, any values not in the dictionary would be False.
from collections import defaultdict
lookup = defaultdict(bool)
lookup[(1,2)] = True
Examples:
l = [(1,2), (3,4), (5,6)]
for e in l:
lookup[e] = True
print(lookup[(3,4)])
# True
print(lookup[(8, 9)])
# False
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.
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()