Misaligned Sting summation - python-3.x

I was trying to find the sum of all the positive numbers in a python string,
b=[1,2,3,4,5,-1,-2,-3,-4,6].
I used While loop and break to stop the loop. The loop is stop as soon the index is getting '-1'.
b=[1,2,3,4,5,-1,-2,-3,-4,6]
total=0
i=0
f=0
while i<len(b) and b[i]>0:
total=total+b[i]
i=i+1
while i<len(b) and b[i]<0:
i+=1
break
print(total)
Can someone provide alternative ideas of how to solve this issue ? I am getting 15 as output but I am expecting 21. Thank you for the help.

how about just that:
sum(n for n in b if n > 0)
the generator expression in the sum selects the positive values only.

Your whole problem is simply the break statement. You don't really need it as the loop will exit alone when the condition is not met.
What happens right now, is that your inner loop skips the first negative number - -1 - but then breaks immediately. So at this point in time i = 6 and we're back in the outer loop. So now b[i] = -2 and the outer loop exits.
So, bottom line, remove the break statement and the inner loop will exit alone, just when you want it to, and you will magically get 21 as athe output.
A side note: This is a messy solution for a simple problem with built-in options to handle, as hiro's answer shows.
Still, going with your line of thought, there is no need to get your hands dirty with maintaining indices with while loops. A for-loop is just what you need - iterate through each element, and just add a check if it is positive:
b=[1, 2, 3, 4, 5, -1, -2, -3, -4, 6]
total = 0
for num in b:
if num > 0:
total += num

Related

How to extract numbers with repeating digits within a range

I need to identify the count of numbers with non-repeating digits in the range of two numbers.
Suppose n1=11 and n2=15.
There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4.
Wrote this code:
n1=int(input())
n2=int(input())
count=0
for i in range(n1,n2+1):
lst=[]
x=i
while (n1>0):
a=x%10
lst.append(a)
x=x//10
for j in range(0,len(lst)-1):
for k in range(j+1,len(lst)):
if (lst[j]==lst[k]):
break
else:
count=count+1
print (count)
While running the code and after inputting the two numbers, it does not run the code but still accepts input. What did I miss?
The reason your code doesn't run is because it gets stuck in your while loop, it can never exit that condition, since n1 > 0 will never have a chance to be evaluated as False, unless the input itself is <= 0.
Anyway, your approach is over complicated, not quite readable and not exactly pythonic. Here's a simpler, and more readable approach:
from collections import Counter
n1 = int(input())
n2 = int(input())
count = 0
for num in range(n1, n2+1):
num = str(num)
digit_count = Counter(num)
has_repeating_digits = any((True for count in digit_count.values() if count > 1))
if not has_repeating_digits:
count += 1
print(count)
When writing code, in general you should try to avoid nesting too much stuff (in your original example you have 4 nested loops, that's readability and debugging nightmare), and try using self-describing variable names (so a, x, j, k, b... are kind of a no-go).
If in a IPython session you run import this you can also read the "Zen of Python", which kind of sums up the concept of writing proper pythonic code.

Estimating value of 1/pi using Ramajunam equation, returning wrong value when comparing with (1/math.pi)

Edited for Updated code
#racraman. Love you man. You not only helped me improve my code but also to understand the Equation. Thanks for your time.
import math
# performing ramanujan's infinite series to
#generate a numerical approximation of 1/pi:
""" 1/pi = (2*sqrt(2))/9801) * (4*k)!*(1103+26390k)/(((k!)**4)*396**(4k)))"""
def factorial_1(k):
if k==0:
return 1
else:
result = k* factorial_1(k-1)
return result
def estimate_pi():
k=0
total=0
n=(2*math.sqrt(2)/9801)
limit=int(input("Enter the ending limit = ")) #k=0 until limit=infinity!!!!
while True:
m=factorial_1(4*k)*(1103+26390*k)
o=((factorial_1(k))**4)*(396**(4*k))
result=n*(m/o)
total+=result #assigning result to a new variable to keep track of changes
if k>limit:
break
k+=1 #updating value of k, to improve result & total for each loop.
return 1/total # Return's pi=3.14 only if k=0
print(estimate_pi())
The statement :
k = result
is the problem - the variable k cannot be both a loop counter and the running total.
Instead of that statement, you will need to simply decrement k, and also add result to a new running total variable that you initialise to 0 outside the loop.
You would also only want to print the result and return only after the loop has finished.
EDIT TO ADD :
Please don't use Answers in that way; that's not what they're for, and would be confusing for other readers to try to follow. The question is for containing all (ongoing) steps of defining the problem (just mark the appended updates with "EDIT TO ADD" as I have done with this comment); the answers are for solutions to that problem, to be accepted if they proved useful.
Ramanujan's formula most certainly works for increasing values of k - but you have to iterate starting at 0.
For example, let's say the user enters 5 for k.
What your code is currently doing is incrementing k - so calculating k = 5, 6, 7, ..... terminating when the step's result is 0. You're missing out k=0, 1, 2, 3, 4 - the major terms !
What you want to do instead is sum the results for k = 0, 1, 2, 3, 4, 5 so how about :
Have the user enter a variable limit instead of k
Start k at 0, and increment at each iteration
Terminate the loop when the step's result < epsilon, or k > limit
Incidentally, the n=(2*math.sqrt(2)/9801) is a constant, so can go outside the loop therefore get calculated only once.
#racraman. I'm Posting the updated code as an answer do that I could keep track of the Error's I've made for future references. Thanks for the Help.
# performing ramanujan's infinite series to
#generate a numerical approximation of 1/pi:
""" 1/pi = (2*sqrt(2))/9801) * (4*k)!*(1103+26390k)/(((k!)**4)*396**(4k)))"""
def factorial_1(k):
if k==0:
return 1
else:
result = k* factorial_1(k-1)
return result
def estimate_pi():
k=int(input("enter the value of k = "))
total=0
while True:
n=(2*math.sqrt(2)/9801)
m=factorial_1(4*k)*(1103+26390*k)
o=((factorial_1(k))**4)*(396**(4*k))
result=n*(m/o)
total+=result #assigning result to a new variable to keep track of changes
epsilon=1e-15
if abs(result)<epsilon:
break
k+=1 #updating value of k, to improve result & total for each loop.
return 1/total # Return's pi=3.14 only if k=0
print(estimate_pi())

"If" statement seems to behave erratically in my code

I'm just learning Python and decided to try a bit of code resembling the old Milton Bradley 'Simon' game. Which is a memory sequence game with four colored buttons. I'm using numbers 1-4. I'm stuck at the moment where the 'if' statement decides if the my answer is correct or not. I've run this through quite a few time and I can't figure out why it jumps to the you LOSE when the answer is correct. For example:
Start game?: Y
[4, 1, 4, 2, 4]
Pick: 4
Pick: 1
Pick: 4
Pick: 2
you LOSE
Pick: 4
Process finished with exit code 0
import random
START=input('Start game?: ')
length_of_game=5
Simon_List=[]
if START == 'Y':
i=0
while i<length_of_game:
i += 1
number=random.randint(1,4)
Simon_List.append (number)
print (Simon_List)
for x in Simon_List:
#print (x)
Your_guess=int(input('Pick: '))
if Your_guess == Simon_List[x]:
break
print('you LOSE')
Simon_List[x] isn't doing what you think its doing, its using the value at each element in the list and then you're using that to look up a value in the list at that given index (so the first iteration would be looking up the value at index 4 in the example), you just need to compare vs x
if Your_guess == x:

not sure why the output is 1 1, instead of 1123?

I took a quiz, the output for this following code is 1 1 instead of 1 1 2 3. And the explanitaion for this answer is that when the code encounter the break(when it reach 2) ,then loops stop.
I understand that the loops stop when it reach 2, but since print() has the same indentation as if() statement, I thought they are excuted seperately,
(but both still under for loop). So when number reaches 2, even if the loop stops, it will still execute the print(), for it is still under for loops. Hence, the result is the 1 1 2 3. And no matter what if() statement is, the result is the same.
numbers = [1, 1, 2, 3]
for number in numbers:
if number % 2 == 0:
break
print(number)
No, the commands are interpreted in order. When the if condition becomes true, the break exits the for loop before the print can execute. The first two loops the break is skipped since 1 % 2 == 0 is false, but 2 % 2 == 0 is true exiting the loop before getting to 3 which would also be true and print... if the loop hadn't already exited.
When the break statement executes the execution pointer goes to the next statement outside the loop, not the statement after the if block containing the break statement, so the print function is not called once break is executed as the execution is then outside the loop.

How does this code work? What tells it to stop printing after the third row? Can someone break it down for me, in the most dumbed down way possible?

import random
def main():
printMatrix(3)
i don't understand how this code stops after the third row
def printMatrix(n):
for i in range(1, n + 1):
for j in range(1, n + 1):
print(random.randint(0, 1), end = " ")
print()
main()
range(1,n+1) is a builtin that returns [1, 2, 3], so iterating over range(1, n+1) is the same as iterating over [1, 2, 3] - each for loop body executes three times before terminating. The inner one prints your entries horizontally and the outer one causes the inner one to execute three times.
Frankly this is a little basic, if you have trouble here I think anybody would suggest that you fetch a drink, get comfortable, open a book and start learning properly.
That said, I'll play:
The first for construct is responsible for (1) iterating the columns and (2) breaking the line. It does all these things once for each value of i in the range 1..4 (where 4 comes from n+1 with n=3). Hence, you already have your answer: it iterates three times and thus (2) happens three times.
To do (1), it uses another for construct, which is completely independent.
To do (2), it uses print().

Resources