How to mimic Golang make() function in Python? [closed] - python

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).

Related

array implementation using python from scratch [closed]

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))

Python function that returns independent value based off list input [closed]

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.

It it worth to use a Dict with only keys and null values? [closed]

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

How to rename an array in python? [closed]

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 8 years ago.
Improve this question
I have a list
dl[vr]
where vr is an arbitrary name extracted from a file.
what I want is to create an array with the same name as vr,
so I wonder besides
ar = np.array(dl[vr])
what should I do to name the array the same as the variable vr?
thanks
I am not entirely sure what you're asking for, but it sounds like you want an arbitrary string from a file used to identify an array (presumably filled with data from that same file).
Rather than trying to give the variable itself that arbitrary name, I think you would be better off storing the array in a dictionary and using the arbitrary name as the key:
arrayDict = {}
name = readStringFromFile()
data = readArrayFromFile()
arrayDict[name] = data
Obviously, you should choose more appropriate names for these variables if you can :)
You could create a new variable with an unknown name, but then you would have to access it indirectly as well. You might as well make this more obvious with your own dictionary.
I think you are totally confused with basics.
listA = ['A','C','1']
here listA is a list
dictA = {}
dictA["name"] = "xxxxxxx"
here dictA is a dict
Following links will help you to understand what is list(array)/dict :
https://docs.python.org/2/library/stdtypes.html#mapping-types-dict
https://docs.python.org/2/tutorial/datastructures.html
You can use globals() or locals()
globals()['aaa'] = 'hello world'
print aaa
'hello world'
But in my opinion better use dictionary.

Iterate over list, keep some entities [closed]

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 8 years ago.
Improve this question
I am trying to write over an existing list and skip over any index in the list where value[i] = -1, preserving that value at the correct index.
One problem is the last_item value seems to wrap around to the end of the list, is there a way to prevent that? Otherwise, is there a better way to do this? This seems too clumsy with all the logic.
The data looks like:
-1
1
2
3
-1
1
2
3
And Im trying to get it to look like this:
-1
1
2
3
-1
4
5...
EDIT
I modified the code that Alex posted below, it is working great now. Here is the code I used:
count = 1
for i range(len(my_list)):
if my_list[i] == -1:
new_list.append(-1)
else:
my_list[i] = count
count += 1
new_list.append(my_list[i])
You probably want to brush up on python lists, python loops, and iteration/indexing in general before you start to write this code. Here are some pages you might find useful
An Intro to Python Lists
For Loops in Python
Looping with Lists in Python
Another note, just because you set a variable equal to an element in a list, you can't expect that element in that list to change if you change the variable. That's like saying, I'm going to make a copy of this cookie that looks and tastes just like this other cookie. Then, if you eat the second cookie (the one you made), the first one will still exist until you go in and actually eat that cookie.
The same goes for that iterating variable, i. When you check if i==-1, you're really only saying "Is this the first loop in my loop?" because you're looping starting at -1. This should all make more sense when you glance over those loop articles.
Awesome, the input/output data helps a lot. It makes more sense now.
How about this:
count = 1
for i range(len(my_list)):
if my_list[i] = -1:
continue
else:
my_list[i] = count
count++
Where my_list is the input list
I'm not 100% understanding the problem here, but I think I do. And this code should give you the output you want given the input you provided. HTH

Categories