Python3 sorted function checking the same conditions twice - python

I want to sort an array of numbers and return the largest number in string format.
For example:
Array = [5,1,9,30]
should return
'95301'
I have the following code that accomplishes it
class LargestKey(str):
def __lt__(x, y):
print("x",x,"y",y, x+y > y+x)
return x+y > y+x
class Largest():
def largestNumber(self, nums):
mapResult = map(str, nums)
num = ''.join(sorted(mapResult, key=LargestKey))
testNum = Largest()
print(testNum.largestNumber([5,1,9,30]))
According to the print in the LargestKey function, the output is:
x 1 y 5 False
x 9 y 1 True
x 9 y 1 True
x 9 y 5 True
x 30 y 5 False
x 30 y 1 True
95301
I don't understand why the checking with x = 9 and y = 1 is happening twice

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

Sum of numbers from 1 to 5 in loop

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.

Recursive addition/subtraction in python with negative integers

I am trying to make a program that adds and subtracts two arguments using recursion. So far my program is working for positive integers but I am completely lost about how I can make this work for negative integers. I would really appreciate your help.
Here is my code so far:
def add(x,y):
"""add takes x and y and adds them together"""
if y == 0:
return x
else:
return add1(add(x, sub1(y)))
def sub(x,y):
"""sub takes x and y and subtracts them"""
if y == 0:
return x
else:
return sub1(sub(x, sub1(y)))
def add1(x):
return x+1
def sub1(x):
return x-1
I'd go with this
def add(x,y):
if y > 0:
return add(x, y-1) + 1
elif y < 0:
return add(x, y+1) - 1
else:
return x
Subtract would be the same idea, but flip the signs
def sub(x,y):
if y > 0:
return sub(x, y-1) - 1
elif y < 0:
return sub(x, y+1) + 1
else:
return x
Testing
>>> add(3,5)
8
>>> add(3,0)
3
>>> add(3,-5)
-2
>>> subtract(8,3)
5
>>> subtract(3,8)
-5
>>> subtract(3,0)
3
In each case you try to get y closer to 0 since y==0 is the base case for your recursion.
If y is positive, you do so by repeatedly subtracting 1.
If y is negative, you repeatedly add 1.
In every case, do "the right thing" to x:
Addition
if x or y is 0, return the other value
if y is positive, add 1 to x, subtract 1 from y: 6 + 2 = 7 + 1 = 8 + 0 = 8
if y is negative, subtract 1 from x, add 1 to y: 6 + (-2) = 5 + (-1) = 4 + 0 = 4
code:
def add(x, y):
if y == 0:
return x
elif x == 0:
return y
elif y > 0:
return add(add1(x), sub1(y))
else:
return add(sub1(x), add1(y))
Subtraction
if y is 0, return x
if y is positive, subtract 1 from x, subtract 1 from y: 6 - 2 = 5 - 1 = 4 - 0 = 4
if y is negative, add 1 to x, add 1 to y: 6 - (-2) = 7 - (-1) = 8 - 0 = 8
code:
def sub(x, y):
if y == 0:
return x
elif y > 0:
return sub(sub1(x), sub1(y))
else:
return sub(add1(x), add1(y))

is counter has certain value inside a class in python

i am learning classes in python and when i was reading the documentation i found this example that i didn't understand :
class MyClass:
"""A simple example class"""
def __init__(self):
self.data = []
i = 12345
def f(self):
return 'hello world'
then if we assign :
x = MyClass()
x.counter = 1
now if we implement while loop :
while x.counter < 10:
x.counter = x.counter * 2
so the value of x.counter will be :
16
while for example if we have a variable y :
y = 1
while y < 1 :
y = y *2
then if we look for the value of y we find it
1
so i don't know how is the value of counter became 16 .
thanks
this doesn't really have anything to do with classes in particular, but here is what is happening...
x == 1 # x is less than 10, so it is doubled
x == 2 # x is less than 10, so it is doubled
x == 4 # x is less than 10, so it is doubled
x == 8 # x is less than 10, so it is doubled
x == 16 # now x is greater than 10, so it is not doubled again
y = 1
while y < 1 :
y = y *2
Always give same input, if you want same output.
You see that you are checking y < 1 which would fail on first run. Make it y < 10, as you are having in your x.counter case.
y = 1
while y < 10:
y = y *2

Categories

Resources