This code takes an array of numbers (only 2 different numbers) and returns the number that repeats itself the most:
def majorityElement(self, nums: List[int]) -> int:
first_num = 0
second_num = 0
target = None
for num in nums:
if num == nums[0]:
first_num += 1
else:
if target is None:
target = num
second_num += 1
if first_num > second_num:
return nums[0]
else:
return target
Then I saw that the if target is None:
was running for every number inside the array, even when I already have a target (I added that code because the first number is easy to catch (nums[0]) but the second one can first appear on index 1, 20, 40000 or anything in between).
I thought it could be cool if you could give "lives" to some pieces of code, like....
def majorityElement(self, nums: List[int]) -> int:
first_num = 0
second_num = 0
target = None
for num in nums:
if num == nums[0]:
first_num += 1
else:
%(while True) if target is None:
# I just created that syntax, it doesn't have to be written like that
target = num
second_num += 1
if first_num > second_num:
return nums[0]
else:
return target
That would mean that piece of code would only be active while that statement is true (I guess it should be true from the beginning, and even if it becomes false and true again, it wouldn't "revive").
Is there any way to accomplish something like that? Would it even work? Because the computer should still check (and therefore, spend time) if it's true, rendering the whole idea useless, right?
Maybe instead of using booleans, just int as lives (%(5) would mean it has 5 lives)
By that I don't mean a for i in range(5)
loop, here's the difference:
Code with for loop:
for i in range(10, 13):
for j in range(2):
try:
print(i)
except:
pass
try:
print(j)
except:
pass
0 1 10 0 1 11 0 1 12
Code with lives:
for i in range(10, 13):
%(3)for j in range(2):
try:
print(j)
except:
pass
try:
print(i)
except:
pass
0 1 10 0 #pass 11 #pass #pass 12