How can I convert to while loop - python

I wrote this code. It's like len() function.
def length_itr_for(list):
total = 0
for i in list:
total += 1
return total
print length_itr_for([1,2,3,4,5,6,7,8])
output is; 8. because in this list, there are 8 value. so len is of this list is 8.
but I don't know how can I write this code with while loop?
while list[i]: etc... I though a few things but I don't know what should I write it here.
edit:
actually I tried this code too. but It's not good code. just tried and it didn't work.
def length_itr_whl(list):
total = 0
i = 0
while list[i]:
total = total + 1
i = i + 1
return total
print length_itr_whl([1,2,3,4,5])

You can write a function that tests whether an index is in range for a list:
def validIndex(l, i):
try:
_ = l[i]
except IndexError:
return False
return True
I got this code from If list index exists, do X
Then you can use this in your loop:
def length_itr_whl(list):
total = 0
index = 0
while validIndex(list, index):
total += 1
index += 1
return total
You could also use while True: and catch the index error in the loop.
def length_itr_whl(list):
total = 0
index = 0
try:
while True:
_ = list[index]
total += 1
index += 1
except IndexError:
pass
return total

If you really want to convert this code to a while-loop, you could always do something like this:
def length_itr_whl(list):
total = 0
i = 0
while list[i:i+1]:
total = total + 1
i = i + 1
return total
print length_itr_whl([1,2,3,4,5]) # prints 5
print length_itr_whl([]) # prints 0
This uses the list-slicing mechanism in Python and it does not require any try-block. When the indices are out of range the result will be [] (an empty list), which evaluates to False in Python.
However, why don't you just use the built-in len-function in Python?

def length(items) :
idx = 0
try:
while True:
_ = items[idx]
idx += 1
except IndexError:
return idx

Try this:
list=[1,2,3,4,5]
total = 0
while total != len(list):
total +=1

Related

Trouble trying to find length of longest substring

I wrote the following code. It should return to me the length of the longest subscript in a string without a repeat in letters.
def lengthOfLongestSubstring(s):
lst = []
y = 0
final = 0
count = len(s)
while len(s) > 0:
s = s[y:]
for i in range(len(s)):
if s[i] in lst:
y += 1
count = len(lst)
lst =[]
break
else:
lst.append(s[i])
if count > final:
final=count
return(final)
when entering the string "tmmzuxt" i expect to get an output of 5 (length of "mzuxt") but instead get 4. I have debugged to figure out the problem seems to be that my function skips over the second 'm' when indexing but I can't figure out why. Any suggestions?
Realized I somehow missed a line. Hope this makes more sense.
Your issue here is that you are modifying s while you are running your code.
Consider that in the first iteration, you are getting s = s[0:], so s will now be 'tmmzuxt'. In your next iteration, you are getting s = s[1:], from the modified s. This is still not a problem, because you just get 'mmzuxt'. However, in your third iteration, you are getting s = s[2:], which is now 'zuxt'.
So you need a different variable than s to hold the substring of s that you are actually testing.
here, in your code(line 7) you are updating your string value inside function, everytime your for loop iterates.
for e.g., after every break inside for loop. you string(which is "tmmzuxt") is becoming short and short.
i created a new variable which contains your original string.
def lengthOfLongestSubstring(s):
lst = []
y = 0
final = 0
count = len(s)
main_string = s;#change done here
while len(s) > 0:
s = main_string[y:] #change done here
for i in range(len(s)):
if s[i] in lst:
y += 1
count = len(lst)
lst =[]
break
else:
lst.append(s[i])
if count > final:
final =count
print(final)
return(final)
lengthOfLongestSubstring("tmmzuxt")
The main problem with your code is that you incremented y, even though it should only ever remove the first character. There is no need for a variable y. Try this:
def lengthOfLongestSubstring(s):
final = 0
while len(s) > 0:
count = len(s)
lst = []
for i in range(len(s)):
if s[i] in lst:
count = i - 1
break
lst.append(s[i])
if count > final:
final = count
s = s[1:]
return final
print(lengthOfLongestSubstring("tmmzuxt"))
Here is an edited code. removing #lst =[] and #break lines.
[Code]
def lengthOfLongestSubstring(s):
lst = []
y = 0
final = 0
count = len(s)
while len(s) > 0:
s = s[y:]
for i in range(len(s)):
if s[i] in lst:
y += 1
count = len(lst)
#lst =[]
#break
else:
lst.append(s[i])
if count > final:
final=count
return(final)
s="tmmzuxt"
print(lengthOfLongestSubstring(s))
[Output]
5
I'm not sure if I understand your code, or if the while loop is needed here, actually. Try this instead:
def lengthOfLongestSubstring(s):
max_length = 0
length = 0
previous = ''
for thisCharacter in s:
if thisCharacter != previous:
length += 1
else:
max_length = max(length, max_length)
length = 1
return max_length

Getting the last number from a FOR loop

I have this code:
def LCM(minN,maxN):
count = 1
for i in range(count,(maxN*count)+1):
print(minN*count)
count = count + 1
And if I call it like so: LCM(5,7) its gonna give me the numbers:
5
10
15
20
25
30
35
How could I make the program output (instead of all the numbers) just the last one, in this example: 35
I tried looking it up in the other topics but none were of any help.
Move the print statement outside the for loop?
def LCM(minN,maxN):
count = 1
for i in range(count,(maxN*count)):
count = count + 1
print(minN*count)
LCM(5,7)
# 35
you can simplify your LCM method:
def LCM(minN, maxN):
print(minN * maxN)
LCM(5,7)
output:
35
You can use a list:
def LCM(minN,maxN):
count = 1
results = []
for i in range(count,(maxN*count)+1):
results.append(minN*count)
count = count + 1
print(results[-1]) # print the last elements of the list.
So, when You call LCM(5, 7), You will get 35.
def LCM(minN,maxN):
count = 1
for i in range(count,(maxN*count)+1):
count = count + 1
else:
print(minN*(count-1))
Let's do some simplification. Here's your original code:
def LCM(minN,maxN):
count = 1
for i in range(count,(maxN*count)+1):
print(minN*count)
count = count + 1
count could be removed from this:
def LCM(minN,maxN):
for i in range(1, maxN+1):
print(minN*i)
Now, you want to print just the last value of this sequence. The last value of i will be maxN:
def LCM(minN,maxN):
for i in range(1, maxN+1):
pass
print(minN * maxN)
Or simply:
def LCM(minN,maxN):
print(minN * maxN)

Trying to print the factorial of natural numbers using generators .Getting the output as 1 1 1 1 1 instead of 1 1 2 6 24 120 ......?

def my_gen():
number = 1
fact = 1
fact = fact * number //Trying to calculate factorial
yield fact
number = number + 1
a = my_gen()
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
Trying to print the output for the first five natural numbers.
Expected output: 1 1 2 6 24
obtained output: 1 1 1 1 1
How can i do this??.Any help is appreciated
If you want to write this as a generator, you might want to look up how that works. The generator somehow has to to repeatedly yield a value, your function just provides a single yield, i.e. there is no "next". A fix, working for arbitrarily sized factorials, could involve itertools.count like so:
from itertools import count
def factorial():
res = 1
for x in count(1):
res = x*res
yield res
This starts with the value 1, after each iteration multiplying with the next higher number, and yielding that result.
Should you want to get the first value, 1, twice, then insert another yield res before entering the for-loop.
This may help you to solve your problem.
def my_gen(num):
if num < 0:
return 0
elif num == 0:
return 1
else:
for i in range(1,num + 1):
factorial = factorial*i
return factorial
a = 1
print(my_gen(a))
a = a+1
print(my_gen(a))
a = a+1
print(my_gen(a))
a = a+1
print(my_gen(a))
a = a+1
print(my_gen(a))
Here is the tested code
from itertools import count
def factorial():
res = 1
for x in count(1):
yield res
res = x*res
fs = factorial()
for item in range(10):
print(next(fs))
def factorial(x):
start = 0
fact = 1
while start <= x:
yield fact
start = start + 1
fact = fact * start
fact = factorial(5)
print(next(fact))
print(next(fact))
print(next(fact))
print(next(fact))

Python: while loop inside else

def is_prime(x):
count = 1
my_list = []
while count > 0 and count < x:
if x % count == 0:
my_list.append(x/count)
count += 1
return my_list
my_list = is_prime(18)
def prime(x):
my_list2 = []
for number in my_list:
if number <= 2:
my_list2.append(number)
else:
count = 2
while count < number:
if number % count == 0:
break
else:
my_list2.append(number)
count += 1
return my_list2
print prime(18)
Just started out with Python. I have a very simple question.
This prints: [9, 3, 2].
Can someone please tell me why the loop inside my else stops at count = 2? In other words, the loop inside my loop doesn't seem to loop. If I can get my loop to work, hopefully this should print [2, 3]. Any insight is appreciated!
Assuming that my_list2 (not a very nice name for a list) is supposed to contain only the primes from my_list, you need to change your logic a little bit. At the moment, 9 is being added to the list because 9 % 2 != 0. Then 9 % 3 is tested and the loop breaks but 9 has already been added to the list.
You need to ensure that each number has no factors before adding it to the list.
There are much neater ways to do this but they involve things that you may potentially find confusing if you're new to python. This way is pretty close to your original attempt. Note that I've changed your variable names! I have also made use of the x that you are passing to get_prime_factors (in your question you were passing it to the function but not using it). Instead of using the global my_list I have called the function get_factors from within get_prime_factors. Alternatively you could pass in a list - I have shown the changes this would require in comments.
def get_factors(x):
count = 1
my_list = []
while count > 0 and count < x:
if x % count == 0:
my_list.append(x/count)
count += 1
return my_list
# Passing in the number # Passing in a list instead
def get_prime_factors(x): # get_prime_factors(factors):
prime_factors = []
for number in get_factors(x): # for number in factors:
if number <= 2:
prime_factors.append(number)
else:
count = 2
prime = True
while count < number:
if number % count == 0:
prime = False
count += 1
if prime:
prime_factors.append(number)
return prime_factors
print get_prime_factors(18)
output:
[3, 2]
Just to give you a taste of some of the more advanced ways you could go about doing this, get_prime_factors could be reduced to something like this:
def get_prime_factors(x):
prime_factors = []
for n in get_factors(x):
if n <= 2 or all(n % count != 0 for count in xrange(2, n)):
prime_factors.append(n)
return prime_factors
all is a built-in function which would be very useful here. It returns true if everything it iterates through is true. xrange (range on python 3) allows you to iterate through a list of values without manually specifying a counter. You could go further than this too:
def get_prime_factors(x):
return [n for n in get_factors(x) if n <= 2 or all(n % c != 0 for c in xrange(2, n))]

How does the max() function work in Jython?

I need this function to tell me the longest sequence of positive numbers in a list.
def longestSequencePos(nums):
index = 0
list = []
integ = 0
for obj in nums:
if obj > 0:
index = index +1
else:
list.append(index)
index = 0
return max(list)
list should contain all of the lengths of the sequences of positives, but the max function is not working.
you are not appending anything to your list when you are exiting the loop and nums only has positive integers, you will need to do something like:
def longestSequencePos(nums):
index = 0
list = []
integ = 0
for obj in nums:
if obj > 0:
index = index +1
else:
list.append(index)
index = 0
list.append(index)
return max(list)
which will append the last count of index if the list is empty at the end of the loop.
also, you have called your list, well, list, which is actually a constructor for a list, although this is not the problem it is something to watch out for as a do not do
You don't need a list to do this:
count = maxc = 0
for obj in nums:
if obj > 0:
count += 1
else:
maxc = max(count, maxc)
count = 0
maxc = max(count, maxc)
The problem might be that you aren't adding index to the list when nums is exhausted, so if the list ends in the longest sequence, it won't return the correct value:
def longestSequencePos(nums):
index = 0
list = []
integ = 0
for obj in nums:
if obj > 0:
index = index +1
else:
list.append(index)
index = 0
list.append(index)
return max(list)
This fixed version works for me in the normal python interpreter. I haven't tried it on jython.

Categories