I've created a summation function that takes in a start number and an end number and returns a summed answer between those two points
def print_sum_equations(start_number,end_number):
mySum = 0
num = start_number
while num <= end_number:
mySum += num
num += 1
print (mySum)
print_sum_equations(3,5)
It returns 12 which is correct, however, I want my output to look like the following
3 + 4 + 5 = 12
rather than just returning the answer. Im still new to python and learning how to iterate while loops so any help is appreciated
def print_sum_equations(start_number,end_number):
vals = [i for i in range(start_number,end_number+1)]
s = sum(vals)
for ind,i in enumerate(vals):
print(f'{i}',end='')
if ind != end_number-start_number:
print(' + ',end='')
else:
print(f' = {s}')
print_sum_equations(3,5)
Use the join method to get the series from a list of values.
val_list = list(range(start_number, end_number+1))
lhs = ' + '.join(val_list)
print ( lhs + ' = ' + str(sum(val_list)) )
You could also use a list comprehension to get val_list:
val_list = [ n for n in range(start_number, end_number+1) ]
... but list(range(... is more direct.
Pretty new to programming in python, my solution, is pretty simple and easy to read.
def print_sum_equations(start_number,end_number):
mySum = 0
num = start_number
num_list = []
num_list.append(num)
while num <= end_number:
mySum += num
num += 1
num_list.append(num)
print (mySum)
num_list.pop()
print(*num_list, sep="+",end="")
print("="+str(mySum))
print_sum_equations(2,5)
Related
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
The code intends to print a frequency table for a random input discrete data. Here's the code :
from math import log10
from random import randint
N = int(input("Enter number of observations:\n"))
l = [ randint(1,100) for var in range (N) ]
print(l)
l.sort()
print(l)
k = 1 + (3.332*log10(N))
k1 = round(k)
print ("Number of intervals should be = ",k1)
x = N//k1 + 1
print("S.No\t\tIntervals\t\tFrequency")
c = 1 #count
while c <= k:
a = (c-1)*x
b = c*x
count = 0
for v in range(a,b) in l:
count += 1
print(c,"\t\t","{}-{}".format(a,b),"\t\t",count)
c += 1
This shows the above cited error, how to resolve this?
The issue is that range(a,b) sets up a list of integers from a to b-1. What you are asking for is for the code to go through l and pick out numbers matching those criteria, which looks instead like:
for v in l:
if ((v>=a) and (v<b)):
count += 1
If you really want to use range, and your data are going to stay integers, then it would look like:
for v in l:
if v in range(int(a),int(b)):
count += 1
Also
x = N//k1 + 1
should be
x = 100//k1 + 1
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
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))
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))]