How to write this for loop from C to Python? [closed] - python

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 6 years ago.
Improve this question
I am new to Python, could someone give some pointers as to how this C code can be done in Python:
for(i=0, j=0; j<n; i++, j++){
A[i] = A2[j];
}
I gave this as a example. I am working on a web scraping project where I have to compare each word in a string given by the user to another string and should count proximity of each word and the strings I've to compare are in an array.

You are basically copying an array, equivalent to a python list. You could simply do:
A = list(A2)
In a for loop scenario (which isn't even needed due to the availability of the list call), you'd do:
for ind, val in enumerate(A2):
A[ind] = val
you really have many other options too, A2.copy(), A2[:], a list comprehension and in most recent python versions [*A2]. Python generally makes it very easy to do this.

Python supports iteration over collections/iterables (so range, for example) which are generally discrete. So, you can rewrite that as a while loop:
i = 0
j = 0
while j < n:
A[i] = A2[j]
i += 1
j += 1

Related

Need Help to program in python. Desperate Python newbie here :-} [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.
The community is reviewing whether to reopen this question as of 11 months ago.
Improve this question
Hy,I am newbie in python programming.I am trying to improve my programming skills.I recently joined a code learning platform called code wars for improving my coding skills. The platform is great. I am having trouble reading some code there as I am not a experienced programmer.
Write a function that adds the digits of an integer. For example, the input receives a number: 10023. The result should be - 6 (1 + 0 + 0 + 2 + 3)
For example I found the answer that is rated higher for the above question.
def sum_digits_of(n:int) -> int:
return sum(map(int, str(n)))
SumDigitsOf = sum_digits_of
For the above solution I did not understand '(n:int) -> int' and 'map(int, str(n))'
It's not that I don't know programming but I can't understand the code like above.I know simpler methods for solving this. But how to write and understand much more efficient code. It would be great help if any of you guys suggest how will I get better or is it wise to post the code which I don't understand here [ already tried googling :) ], Cheers!
The code you show “casts” an int to a str, then takes it digit by digit (map applies a function to something iterable, simply put), “casts” each digit back to int and finally sums the digits. (And it is indented incorrectly.)
The final assignment merely creates an alias name for the function, it doens’t “do” anything.
In any case, strings (str) do not have to be necessarily involved:
def sum_digits_of(n, base=10):
result = 0
while n:
result += n % base
n //= base
return result
print(sum_digits_of(123456))

cuda in python issue [closed]

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 written the code below in order to discover the number of threads and blocks and send them to train_kernel function.
rows = df.shape[0]
thread_ct = (gpu.WARP_SIZE, gpu.WARP_SIZE)
block_ct = map(lambda x: int(math.ceil(float(x) / thread_ct[0])),[rows,ndims])
train_kernel[block_ct, thread_ct](Xg, yg, syn0g, syn1g, iterations)
but after execution, I face the error below:
griddim must be a sequence of integers
Although you have not stated it, you are clearly running this code in Python 3.
The semantics of map changed between Python 2 and Python 3. In Python 2 map returns a list. In Python 3 it returns an iterator. See here.
To fix this you need to do something like:
block_ct = list(map(lambda x: int(math.ceil(float(x) / thread_ct[0])),[rows,ndims]))
Alternatively you could just use a list comprehension without the lambda expression and map call:
block_ct = [ int(math.ceil(float(x) / thread_ct[0])) for x in [rows,ndims] ]
Either will yield a list with the necessary elements which should work in the CUDA kernel launch call.

Pythonic v. Unpythonic [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In a code review challenge, I recently had the below code called unpythonic:
def word_count(string):
wc_dict = {}
word = ""
index = 0
while index < len(string):
if string[index].isalnum():
word = word + string[index]
index += 1
else:
if word:
if word.lower() in wc_dict:
wc_dict[word.lower()] += 1
else:
wc_dict[word.lower()] = 1
word = ""
index += 1
if word:
if word.lower() in wc_dict:
wc_dict[word.lower()] += 1
else:
wc_dict[word.lower()] = 1
return wc_dict
I also submitted different code for a challenge I wrote in Ruby, and had that solution called "Pythonic".
What does code mean to be Pythonic/Unpythonic?
I would say that "pythonic" means "conforming to usual idioms for python in order to write easy to read code". Your example is not pythonic as it could (probably) be written much more easily.
e.g. using regular expressions + collections.Counter turns this into a pretty obvious 2-liner:
words = re.findall(r'\w+', string)
wc_dict = collections.Counter(words)
If you only expect to be splitting on whitespace, that makes it even easier:
wc_dict = collections.Counter(string.split())
95% of the time, if you're working with single characters from a string, there's a better way.
I very much agree with #mgilson's definition of (un-)Pythonic above, but will expand on this case a little more.
I would say that one of the reasons this code was probably described as "un-Pythonic" is because it appears to be a fairly literal translation of C code to do the same thing. I've also seen many cases of Python code that appeared to be based on familiarity with Java or C#, and their respective data structures, standard libraries, and stylistic conventions.
Other than dict, the OP's code doesn't appear to use any of Python's advanced data structures or iteration capabilities.
Even where dict is used, it's in kind of a less-than-fluent way. This code:
if word.lower() in wc_dict:
wc_dict[word.lower()] += 1
else:
wc_dict[word.lower()] = 1
... could be replaced trivially with a more succinct version (this could also be shortened into a one-liner with defaultdict):
wc_dict.setdefault(word.lower(), 0)
wc_dict[word.lower()] += 1
None of this is meant as a criticism of the OP as a thoughtful programmer, by the way: this is a seemingly reasonable and correct algorithm to solve the problem. It just doesn't take advantage of many Python features which experienced users will be familiar with.

Matching two comma seperated strings in Python and correct position counts [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
Hope get assistance on the below problem.
Python having more in-built sequence matcher functions. Whether the following requirement can be done through any built-in function without looping.
x = 'hu1_X','hu2_Y','hu3_H','hu4_H','hu5_H','hu7_H'
y = 'hu1_H','hu2_X','hu3_H','hu4_H','hu5_H','hu7_X'
for comparing the above string the final match count is 3.
Matches are: 'hu3_H','hu4_H','hu5_H'.
Any idea, which in-built function can use? Can we go with ZIP() in Python.
Thanks in advance.
You can use a generator expression and the builtin sum function along with zip, like this
x = 'hu1_X', 'hu2_Y', 'hu3_H', 'hu4_H', 'hu5_H', 'hu7_H'
y = 'hu1_H', 'hu2_X', 'hu3_H', 'hu4_H', 'hu5_H', 'hu7_X'
print(sum(item1 == item2 for item1, item2 in zip(x, y)))
# 3
This works because, in Python, True and False can be treated as 1 and 0 respectively. So, we can simply compare the corresponding elements and the result of that evaluation can be added together to get the total match count.

For loop in python programming? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am just learning Python with ebook of A Byte in Python and some youtube tutorial. I have reached up to For loop statement. Its not that I don't understand it, but the beginner examples only show: " for i in range..." My question is why only 'in range' option is given. I know how this statement, both for and range, works. But are there other options instead of range?
Can you give me a simple Syntax for usage of for loop? They don't have it in this ebook. Thanks and sorry if I was irritating and confusing. I am just learning by myself.
Of course, there are many ways to use a for-loop. for i in range() is commonly used to loop through something a specific amount of times, or just do something a repeated amount of times with a counter.
Infact, you don't even have to iterate over lists. You can iterate over a string:
>>> for char in 'hello':
... print char
...
h
e
l
l
o
Or even a dictionary:
>>> for key in {'foo':'bar','cabbage':'cake'}:
... print key
...
cabbage
foo
Python does not have the typical for loop construct that the "c-family" languages like java, c, c++, etc have. Python isn't the only scripting language that does this ( I believe bash does it too but don't quote me ). If you want something as true as can be to the "normal" for loop ( and I'm assuming you do ) :
for( int i = 0; i < n; i++ ){ /* do something */ }
I would suggest a while loop in python
i = 0
while ( i < n ) :
// do something
Or use xrange
for i in xrange( 0, n ) :
// do something
xrange is a lot like range, but it doesn't store all the values simultaneously : http://docs.python.org/2/library/functions.html#xrange
I personally would use xrange, I don't know of a better solution. Good luck!

Categories