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 5 years ago.
Improve this question
I have a for in c++ and I want to write it in python but I don't Know how to handle the condition in the for. Can anyone help me ?
for (int b = (i - a) / 2; a + b <= i; b++);
The terminating condition a + b <= i is equivalent to b <= i - a which in turn (as Python for uses less than not less than or equal) would be b < i - a + 1.
That means in Python you could write:
for b in range((i - a) / 2, i - a + 1):
...
But very often you don't want to write like for like when converting from C/C++ to Python. You may be better to restructure the code entirely.
use while
a=something
i=something
b=(i-a)/2
while(a+b<=i):
###do whatever you want in the loop###
b+=1
You could use the for loop and range() function. Example:
for i in range(15):
#code to execute 15 times
However, because of your code, I'd recommend using a while loop instead:
i = 1 #your value for i
b = (i-a)/2
while a+b <= i:
# Other code
b+=1
Your confusion stems from the over-generality of C's iteration construct. Python insists that all loop parameters implicitly refer to the loop index. For the terminating condition, solve your inequality in terms of b, and without equality: b < i - a + 1
Now we get the for loop
for b in range((i-a)/2, (i-a)+1):
One interpretation is that you have a range from 0 to i-a, and you want to deal with the upper half of that.
To answer your question directly:
for b in range((i-a)/2,a+b-1):
print (b)
And if, for some reason, you need a terminating value:
terminatingValue = 0
for b in range((i-a)/2,a+b-1):
terminatingValue = b
print (b)
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 1 year ago.
Improve this question
I wanted to dive into Python and I came to a problem when I wanted to make a very primitive calculator.
It asks you to type 2 numbers, and then it would display informations like number1 + number 2 etc.
I was at the point where I was typing in to display a short text and then the amount of the two numbers like print("amount:" number1 + number2) and that one wasn't right, it was just putting the two numbers next to each other, not what they equal.
I don't know how to display it somehow like this (for example):
The two number equals: 100
You probably did:
a = input('number 1')
b = input('number 2')
print(a + b)
Here a and b will be str (strings are words or sentences). So if you do + it'll be like:
a = 'a_word'
b = 'another_word'
print('a_word'+'another_word')
>>> a_wordanother_word
What you want is to make the word into a number. You can do this by 'casting it' to an integer (a whole number) or a float (a number with a decimal):
a = int(input('number_1')) # example: a = 5
b = float(input('number_2')) # example: b = 1.2345
print(a + b)
>>> 6.2345
Instead of number1 = input(), you have to make it number1 = int(input()) (you can also use float() or whatever) , otherwise your number is going to be a string.
I'm not sure of what you are trying to do but i think it should work for your case :
a = 10
b = 5
print(f'A + B = {a+b}')
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 3 years ago.
Improve this question
I am trying to understand how a code works. I saw a variable declaration like the one below in the code, but don't understand how that works.
what is the difference between
m += 1
and
1 += m
So if m = 5, then m becomes 6:
m += 1
means you're incrementing m by 1 (post-increment)
its the same thing as:
m = m + 1
You can't assign:
1 += m
that's an illegal operation, the error you should see is:
SyntaxError: can't assign to literal
1 += m is not a correct syntax. You may get an Error something like: SyntaxError: can't assign to literal.
In general,
m += 1
means
m = m + 1,
therefore,
1 += m
means
1 = 1 + m which is syntactically wrong because you can not assign anything into an integer literal.
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 6 years ago.
Improve this question
I am still sort of new to python, I can do anything with a while loop and I am still having trouble comprehending that.
for i in range(len(s)):
for x in a: <- where a is an empty set
To get items out of a set without a for loop, you can use an iterator. This is probably what your prof. is referring to. Example:
i = iter(s)
while True:
try:
next(i)
except StopIteration:
break
You can do everything in a while loop but sometimes it can be awkward. The thing about a for loop is that it consumes a sequence.
For your first example, the loop is pretty straight forward because all we really wanted was in index in s
for i in range(len(s)):
print(i)
i = 0
while i < len(s):
print(i)
i += 1
Your second example is more problematic because you can't index sets. Likely, the best way to handle it is to convert the set to a list and index that. Or you could mimic for by creating your own iterator for the set and handling the end-of-iteration exception yourself.
a = set()
for x in a:
print(x)
# this would be illegal because you can't index the set
i = 0
while i < len(a):
print(a[i]) # ERROR
i += 1
# so we make a list
i = 0
_a = list(a)
while i < len(_a):
print(_a[i])
i += 1
# or use an iterator for the set
a_iter = iter(a)
while True:
try:
print(next(a_iter))
except StopIteration:
break
In some languages like C, while is just an abreviated form of for...
while(x < 5)) {...}
for(;x < 5;) {...}
but as you can see, such is not the case with python.
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 9 years ago.
Improve this question
Write the definition of a function, is_reverse , whose two parameters are arrays of integers of equal size. The function returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.)
This is what I have so far:
def is_reverse(a,b):
c = b.reverse()
for i in len(a):
if a[i] == c[i]:
return True
if a[i] != c[i]:
return False
It can be written on one line with
def is_reverse(a, b): return a == b[::-1]
Your code unconditionally exits after the first time in the loop (either the characters are the same, or they're different and you have a return statement for both cases). You only want to return True after you've checked all the string elements.
There's also another slight catch -- list.reverse() reverses the list in place. This means that c = b.reverse() changes b and sets c to None. I've modified that in my code below.
def is_reverse(a,b):
# copy b -- Not strictly necessary if you don't care about changing the inputs...
c = b[:]
c.reverse()
for i in range(len(a)):
if a[i] != c[i]:
return False
return True
Others have pointed out that there are more idiomatic ways to go about doing this:
a == b[::-1]
is the classic example (it does the loop for you!). But I left the structure of the original code as much intact as I could to hopefully make it more clear how python works.
If you want to avoid making a copy of either list:
len(a) == len(b) and all(itertools.imap(operator.eq, a, reversed(b)))
If you're using Python3 then there's no itertools.imap, because the builtin map no longer copies.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a way to get the "cumulative" values in a Python for-loop? In Java there is the way of += to a variable during each loop iteration and it would continue to add it on. Is there an option like this available in Python?
So many ways. Python calls these the "in-place" operators.
You've also got functional approaches like sum and more general accumulators like reduce, which in Python 3 moved to functools.
acc = 0
for i in range(10):
acc += i
or
acc = sum(range(10))
or
from operator import add
from functools import reduce
acc = reduce(add, range(10))
Yes, there is a += operator in Python.
x = 0
for i in range(10):
x += 1
print x
foo = 0
for i in range(0, 12):
foo += 1
print(foo)
for i in range(0, 5):
print i
Output:
0
1
2
3
4
Or, if you want to go by more than one:
for i in range(0, 10, 2):
print i
Output:
0
2
4
6
8