How to change for loops into while loops in python [closed] - 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 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.

Related

how can I plan this sequence-1,2,2,3,4,4,5 [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 2 months ago.
Improve this question
I am fairly new to programming and I try to create the above mentioned sequence.
this problem is about having a strict length of elements which always progresses, this progression is inside the list by moving on the indexes. this strict length shifts from a set of indexes to the next one once all the indexes inside the strict length (not passing it's limits) are finished being scanned, and they are scanned in a format of "one after the other".
after all of that we come to the root of the problem:
once the strict length moves to another set, it starts from the last index that was previously, inside of the strict length but in the previous strict length.
the output of the root problem is the title of this post. I don't know how to solve the root problem.
this problem, involves "k" as an exponent of the strict length.
this is the script:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
the output I got is:
1,2,3,3,4,5,5,6,7,7,8,9,9,10
and I don't know why I got such output, it doesn't seem logical.
As I can understand what you are looking for is to print the even numbers twice.
You can do the following without using a for loop by this way.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while (n<10):
if(int(strarr[n])%2 == 0):
print(strarr[n])
print(strarr[n])
elif(int(strarr[n])%2 != 0):
print(strarr[n])
n = n+1
The reason why your code gives that output is because,
for the 1st iteration it would print 1, 2, 3
2nd iteration it would print out 3 again as there is another print(stararr[n]) outside the for loop. That's the reason why you are getting the output you are getting.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
The error that I think you're seeing has to do with the order that you print your output and update the index n. In the current, buggy code, you're printing first, then updating the value. This means that the second print outside of the inner loop prints using the next value of n, not the one you just used in the inner loop. The same index gets used a second time in the first pass of the inner loop the next time, but that's not the value you wanted to see repeated.
The solution to this issue is pretty simple. Rather than updating after you print, update before. You'll need to adjust the starting value of n, but that's no problem:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = -1 # change starting index
while True:
for i in range(k):
n = n+1 # and reorder the lines in the inner loop
print(strarr[n])
print(strarr[n])
That said, the two loop thing is a lot more awkward than anything I'd really recommend. If you just want to repeat the odd-indexed values in the loop, you can do that much more simply:
for index in range(len(strarr)):
print(strarr[index])
if index % 2 == 1:
print(strarr[index])
Or you can avoid directly needing to index at all, using enumerate to get the index and value of each element in the for statement itself. This is probably a more "Pythonic" way to solve the problem.
for index, value in enumerate(strarr):
print(value)
if index % 2 == 1:
print(value)

How to write a for loop in python [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 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)

Hackerrank Code not working [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 7 years ago.
Improve this question
The problem is given here
I am coding in python and my code is given below:
num =raw_input()
li=list()
count=150*[0]
ans=0
while num>0:
li.append(raw_input())
num=int(num)-1
for i in range (0, len(li)):
for j in range(0, len(li[i])):
count.insert (ord(li[i][j]), count[ord(li[i][j])]+1)
for i in range(0, len(count)):
if count[i]==len(li):
ans=ans+1
print ans
On running the sample test case the output is 3 instead of 2.
Where am I going wrong?
There are several things wrong with your program.
First the insert method doesn't do what you seem to think it does.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Second, you're attempting to count every time a letter appears at all, not just the first instance in a line.
This also looks like a low effort question, which is why you're getting downvoted. What have you tried?
Here's a solution that uses your method correctly, but it's still not a very pythonic approach. Have you considered using a dict to keep track of this information instead?
num = raw_input()
li = list()
count = 150*[0]
seen = 150*[False]
ans = 0
while num > 0:
li.append(raw_input())
num = int(num)-1
for i in range(0, len(li)):
for j in range(0, len(li[i])):
if (not seen[ord(li[i][j])]):
count[ord(li[i][j])] += 1
seen[ord(li[i][j])] = True
seen = 150*[False]
print count
for i in range(0, len(count)):
if count[i] == len(li):
ans = ans+1
print chr(i)
print ans
Here's the same approach using more pythonic language, isn't this much easier to understand?
num = raw_input()
lines = []
seen = set()
count = {}
while num > 0:
lines.append(raw_input())
num = int(num)-1
for line in lines:
for char in line:
if (char not in seen):
count[char] = count.get(char, 0) + 1
seen.add(char)
seen = set()
print count
print list(count.values()).count(len(lines))
There are, of course even better ways to do this.
The website states: Required Knowledge: Implementation, Sets: Time Complexity: O(n)
So using set.intersection would be a better way to go:
num = raw_input()
sets = [set(raw_input()) for x in range(int(num))] ]# make set from each line
print len(set.intersection(*sets)) # find letters that are common in all sets and print the length
You are counting c as a gem-element. It occurs 3 times, but not in 3 different lines. Thus count[i]==len(li) is not a sufficient criterion for a gem-element.

Python reverse function [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 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.

how to reset pointer of list in for loop after a condition becomes true 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 9 years ago.
Improve this question
for r in right:
if stack.endswith(r):
stack=stack.replace(r,left[right.index(r)])
when the if part gets true i want r to point to starting index of right.
suppose r is pointing to 3rd element of right when if gets true and updates stack, then the for loop continues from 3rd element of right. i want to start the for loop from first element of right whenever stack is updated.
how to do it?
One cool way is to use an explicit iterator
iterator = iter(right)
try:
while True:
r = next(iterator)
if stack.endswith(r):
stack = stack.replace(r, left[right.index(r)])
iterator = iter(right)
except StopIteration:
pass
Which in this case looks pretty horrible as there is no "has_next" method for iterators, and the only way to know when to stop is to catch the exception; and for loop would not work here because it stores the reference to its iterator
But really the most idiomatic python in this very exact case is to use the else clause of for loop to break out the while:
# loop forever
while True:
for r in right:
if stack.endswith(r):
stack = stack.replace(r, left[right.index(r)])
# now break out of the for-loop rerunning while
break
# the else is run when all r in right are consumed
else:
# this break is not in a for loop; it breaks the while
break
Maybe nest this in a while loop?
keepLooping = True
while keepLooping:
doBreak = False
for r in right:
if stack.endswith(r):
stack=stack.replace(r,left[right.index(r)])
doBreak = True
break
if doBreak:
break
keepLooping = False
So the process will terminate when right has been searched completely without stack.endswith(r) evaluating as True.
The main task here is to identify true return and false return. Why not make it sample:
While len(right) > 0:
removedIdx = None
for r in right:
if stack.endswith(r):
removedIdx = right.index[r]
stack.stack.replace(r, left[removedIdx])
break
if removed is not None:
right.pop(removedIdx)
else:
break

Categories

Resources