Getting the last number from a FOR loop - python

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)

Related

Python print each iteration of a while loop

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)

How to repeat a function multiple times and sum the output in python?

I want to have a function repeat 12 times and sum up the output over the 12 iterations. Thus far I have tried:
def main():
counter=0
while counter <= 12:
running = function()
counter += 1
x = sum(running)
print(x)
main()
Use sum() function with range():
x = sum(experiment() for _ in range(12))
You want something like this:
import random
def experiment():
return random.randrange(10)
def main():
sum = 0
counter = 0
while counter < 12:
counter += 1
result = experiment()
sum = sum + result
print(sum)
main()
Sample results (1 per run):
66
62
57

How can I convert to while loop

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

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))

codeabbey : list index out of range

Here is the question:
Let us calculate sum of digits, as earlier, but multiplying each digit by its position (counting from the left, starting from 1). For example, given the value 1776 we calculate such weighted sum of digits (let us call it "wsd") as:
wsd(1776) = 1 * 1 + 7 * 2 + 7 * 3 + 6 * 4 = 60
Here is my code:
digitlist = []
numlist = []
def splitdigit(number):
numlist = []
digitlist = []
numlist.append(number)
while number >= 1:
number = number/10
numlist.append(number)
del numlist[-1]
for ele in numlist:
digitlist.append(ele%10)
return digitlist
# digit part
# test if the split digit work here:
# print (splitdigit(1234)) it works
times = int(input())
raw = raw_input()
string = raw.split()
nlist = []
outbox = []
rout = 0
res = 0
n = 0
for item in string:
nlist.append(int(item))
# print (nlist) [it worked]
for element in nlist:
# check for split method : checked
# formula to make the digit work: n = len(out) | while(n>1): n=n-1
# rout=out[-n]*n res=res+rout(res=0)
n = len(splitdigit(element))
print (n)
res = 0
while n >= 1:
rout = (splitdigit(element)[(n*(-1))]) * n # I HAVEN"T CHECK THIS FORMULA OUT !!!
res = res + rout
n = n + 1
outbox.append(res)
print (outbox)
print(" ".join(str(x) for x in outbox))
And here is my running error:
> 3
9 15 1776
1
Traceback (most recent call last):
File "13.py", line 39, in <module>
rout = splitdigit(element)[(n*(-1))] * n # I HAVEN"T CHECK THIS FORMULA OUT !!!
IndexError: list index out of range
and I checked it in interactive python. I think I am not asking for a item out of range but it gives me this error. I hope someone can help me out. Thank you, love you all.
You are thinking way too complicated.
def wsd(number):
digits = [int(i) for i in str(number)]
result = 0
for index, value in enumerate(digits):
result += (index + 1) * value
return result
print(wsd(1776))
Output:
60

Categories