Sum of numbers from 1 to 5 in loop - python

To simplify my scenario, I am redefining my question here.
I want to add numbers from 1 to 5 in loop. X should be 1,2,3,4,5. and start with Y as 0. Y = X + Y should give the sum of 1 through 5.
Requirement: I want to start y as 0 and want y to hold latest add_sum value.
Expected output:
1st iteration: y = 1 (x = 1, y = 0)
2st iteration: y = 3 (x = 2, y = 1)
3st iteration: y = 6 (x = 3, y = 3)
...
...
so on
I am new to python coding, Can anyone help me for this?

Use reduce
reduce(lambda x, y: x + y, range(6))

As mentioned in the comments, fixing your syntax and running your code seems to work just fine.
def read_num():
for num in range (1,5):
x = num
add_sum(x)
def add_sum(x):
global y
y = x + y
print ("y =", y)
y = 0
read_num()
If you want x to be 1 thru 5 inclusive, you have to use range(1,6) instead

y = 0 # Assign value 0 to variable 'y'
for x in xrange(1, 6): # Cycle from 1 to 5 and assign it to variable x using iterator as we need just 1 value at a time
print '(x=%s, y=%s)' % (x, y) # Display value of 'x' & 'y' variables to user for debug & learning purpose
y += x # Adding x to the y.
print 'y=%s' % y # Display result of sum accumulated in variable 'y'
Edit: added comments to the code as requested in comments.

Related

2 counter variables in for loop are not working for equal to condition

Problem Description:
Given an array arr[] of size N and two elements x and y, use counter
variables to find which element appears most in the array, x or y. If
both elements have the same frequency, then return the smaller
element.
Note: We need to return the element, not its count.
My solution:
def MajorityWins(arr, n, x, y):
countX = 0
countY = 0
for i in arr:
if i==x:
countX+=1
if i==y:
countY+=1
if countX>countY:
return x
if countY>countX:
return y
if countX==countY:
if x>y:
return x
else:
return y
n=11
arr=[1,1,2,2,3,3,4,4,4,4,5]
x=4
y=5
print(MajorityWins(arr, n, x, y))
The correct output is 4.
But the output of my program is 5.
When I don't use the condition countX==countY, the outputs are correct.
When I add if countX==countY, all the other conditions are ignored.
Can someone tell me the solution to this please?
What #Sayse said was absolutely correct. You need to flip the > around. But another problem you have it you return while iterating through your list. This can cause problems later on, so please indent it backward so it no on the same indentation level as your loop.
for i in arr:
if i==x:
countX+=1
if i==y:
countY+=1
if countX>countY:
return x
if countY>countX:
return y
if countX==countY:
if x<y:
return x
else:
return y
If both elements have the same frequency, then return the smaller element.
Your code does the exact opposite of this. If x is greater than y, then you need to return y and vice versa
if countX==countY:
if x>y:
return y
else:
return x
If you put a print statement in the loop and you will see what is happening. At the end of the loop countX has a value of 4, countY has a value of 1. 4 is larger than 1 so the value of x is returned.
def MajorityWins(arr, n, x, y):
countX = 0
countY = 0
for i in arr:
if i==x:
countX+=1
if i==y:
countY+=1
print(i, countX, countY)
if countX>countY:
result = x
elif countY>countX:
result = y
elif countX==countY:
if x<y:
result = x
else:
result = y
return result
n=11
arr=[1,1,2,2,3,3,4,4,4,4,5]
x=4
y=5
print(f"Result: {MajorityWins(arr, n, x, y)}")
Output:
1 0 0
2 0 0
2 0 0
3 0 0
3 0 0
4 1 0
4 2 0
4 3 0
4 4 0
5 4 1
Result: 4

tranform a for into a while but keep the same properties? [duplicate]

This question already has answers here:
Converting for loops to while loops in python
(3 answers)
Closed 2 years ago.
def p(l):
x = True
y = len(l)
for z in range(y):
if (sum(l[z+1:]) == sum(l[:z])):
x = False
return z
if x:
return -1
So I would like to transform the for in my code into a while but keep all the same properties is there any way to do it without disturbing the code it self?
If you just want to convert a for loop to a while loop, these two loops are equivalent:
for x in range(y):
# do stuff
x = 0
while x < y:
# do stuff
x += 1
You'll need to instantiate the z variable to 0 and then you can use a while loop to break once all elements of l have been checked.
Though in your case, I guess that it'll throw an indexError when it tries to do l[z+1], so you'll need y - 1 as the termination condition.
z = 0
while z < y:
if (sum(l[z+1:]) == sum(l[:z])):
x = False
return z
z += 1
Your code doesn't have any indents, but it seems, it should be like this.
range(y) means from 0 to y-1, so we start from 0: z = 0, and increase z by 1 every iteration: z += 1. The last value is y-1, so it must stop when z = y, so while conditions is z < y
x = True
y = len(l)
# for z in range(y):
z = 0
while z < y:
if (sum(l[z+1:]) == sum(l[:z])):
x = False
return z
z += 1 # increase z value
if x:
return -1

why is a for loop not appending a list

In the below code, the loops don't seem to be working.
powers = []
x = 0
y = 0
z = 1
for x in powers:
powers.append([])
for y in powers[x]:
powers[x].append(z ** y)
z = z + 1
if z < 1001:
continue
else:
break
x = x + 1
y = y + 1
z = 1
print(powers)
However, when I run this in the terminal, it simply returns an empty list for powers. It doesn't show an error message.
Please help.
your code is badly formatted, so please consider formatting, anyway some of your errors are code-comments.
powers = []
x = 0
y = 0
z = 1
for x in powers: #here you're overriding former declaration of x, also powers is empty so for doesn't have a single run
powers.append([]) ##code is not indented so this istruction execute only once
for y in powers[x]: ##powers[x] is an empty list
powers[x].append(z ** y)
z = z + 1
if z < 1001:
continue
else:
break
z = 1 ## this is outside the cycle
x = x + 1
y = y + 1
print(powers)

how to use information given in a python while loop?

I made a program that looks like:
n = eval(input("enter a whole number: "))
x = 1
print (x)
while x != n:
x = x + 1
print (x)
This code produces a list from 1 to the given whole number n.
What would i do to be able to interact with this list making a second column that gave the square of the adjacent number?
something like
1 1
2 4
3 9
If you want to be able to show the square of 1, you need to initialize x as 0 and delete print(x) from your third line
this should do it:
n = eval(input("enter a whole number: "))
x = 0
while x != n:
x = x + 1
print (x, " ", x**2)
This code prints x and x**2 (the value of 'x ^ 2') separated by a space.
Here is what you are looking for:
n = eval(input("enter a whole number: "))
x = 1
print (x)
while x != n:
x = x + 1
p = x * x
print (x, p)
I would urge caution on using eval() so lightly though, you can use the int() function to run a string as an integer. Here is how I would write that code:
n = int(input("enter a whole number: "))
x = 0
while x != n:
x = x + 1
p = x * x
print (x, p)
EDIT: Updated code
Well, you could use a list of lists. Using a generator expression,
nums = [[n, n**2] for n in range(1,int(input("Enter a number"))]
So if you input 10, nums[1,1] will be 2.
So to print this out,
for i in nums:
print(i[0] + " " + i[1])
This is by far the simplest way to go.

Generating Perfect Squares python

I am trying to write the simplest code possible that will continuously print out Perfect Squares. My code so far reads this
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
When I run it, I get a syntax error. The red bit is on the "final" in "print final"
Apologies if it is a really basic error, but I'm stumped.
Thanks for taking the time to read this
I assume you're using Python 3. print is now a function in Python 3.
Do print(final) instead of print final.
Also, it seems like your x and y values are holding the same thing. Why not discard one of them and use just one?
x = 1
while True:
final = x * x
print(final)
x = x + 1
Or better yet, use the builtin exponentiation operator **.
x = 1
while True:
final = x **2
print(final)
x += 1
Also, your code seems to be going into an infinite loop. You may need a condition to break it.
For example, if you want to break when x reaches 10, just add a condition in the while loop, like follows:
x = 1
while True:
final = x **2
print(final)
x += 1
if x == 10:
break
OR Specify a condition in the whilestatement, like follows:
x = 1
while x < 10:
final = x **2
print(final)
x += 1
OR Use a for loop.
for i in range(10):
print(i**2)
In Python 3, print is no longer a statement but a function, so you must enclose what you want to print in parentheses:
print(final)
Here's a link about the function.
You also have an IndentationError, y = y + 1 should be given a space.
And you can simplify that to y += 1 (which is the same thing, in regards to integers)
You can also add a condition to the while-loop:
x = 0
while x < 5:
print x ** 2
x += 1
Prints:
0
1
4
9
16
I would reccomend using Python 3 if you're not already. Also, as x and y are the same value at all times you only need one of them. So instead of reading:
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
You should write:
x = 1
while True:
final = x * x
print(final)
x = x + 1
Hope this helped!
Jake.

Categories

Resources