Important Updates: Code line 12 changed from "universalTracker + 2" to "universalTracker += 2"
I'm doing the adjacentElementsProduct challenge on CodeSignal, and it's asking me to create a function that shows the highest product from each adjacent pair of numbers in the list. I wrote this, and I can't seem to find what's wrong with it. Once I press run in VSCode, it just hangs. I have to force quit the program.
def adjacentElementsProduct(inputArray):
highestProduct = 0
universalTracker = 0
firstNum = inputArray[universalTracker]
secondNum = inputArray[universalTracker + 1]
arrayLength = len(inputArray)
while universalTracker != (arrayLength - 1):
currentProduct = firstNum * secondNum
if currentProduct > highestProduct:
highestProduct = currentProduct
universalTracker += 2
adjacentElementsProduct([3, 6, -2, -5, 7, 3])
If anyone could give me an explanation as to what I did wrong, a working solution, and why it works, I would greatly appreciate it.
It's simple
Just change while loop condition to
while universalTracker >= (arrayLength - 1):
Because, let's say your array length is 5, and universalTracker is updating by 2, it won't be equal to 5
It will be 2,4,6,8,10,12 ... and so on.
Let me know if this makes sense..
If you notice, you are doing the following inside the while loop.
universalTracker + 2
This isn't really updating the variable that you intended to update.
To make it work, you should do
universalTracker = universalTracker+2
Or equivalently
universalTracker += 2
Related
i = 1
i = i + 1
print(i)
I am pretty confused about the code's logic. Why would i eventually become 2?
Lets begin with the first assignment:
i = 1
This creates the variable i and initialize it to the integer value 1.
Then we get to what you seem to have problem understanding:
i = i + 1
This statement can be split into two parts:
The addition
The assignment
The addition i + 1 will take the current values of the variable i, which is 1, and add the value 1 to that. In essence the expression i + 1 is the same as 1 + 1.
The result of the addition will be 2. And this result is then assigned to the variable i, making the value of i be equal to 2.
You then print the (new) current value of i:
print(i)
This will of course print the value 2.
The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.
Just for completeness:
x += y is not always doing an in-place operation, there are (at least) three exceptions:
If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int
If __iadd__ returns NotImplemented, Python falls back to x = x + y.
The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.
As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of "Emulating Numeric Types".
'i' is a variable which stored 1 if We add 1 again in 'i' that means
i=1;
i+1 means 1+1=2
i=1
i=i+1// i has already 1 and here we are adding 1 again so result will be 2.
hope you understood.
Let's start from i = 1. So you are assigning i to 1. Now your situation is:
i = i + 1
So if i is 1, then the abovementioned code would be "translated" to:
i = 1 + 1
That's why i = i + 1 is equal to 2.
I dont really know if the title makes sense at all but i dont really know how to ask the question in the first place so i'll just show the code and hopefully someone can make sense of it? Thank you!
My concern is the elif statement where it says ((player_input[1] - computer_input[1]) % 3 == 1):
Why is the [1] there for both inputs? I don't understand why they are there at all or even why it has to be 1?
player_score = 0
computer_score = 0
options = [('Rock',0), ('Paper',1), ('Scissors',2)]
tie_score = 0
def clicked(player_input):
global player_score, computer_score, rock_use, paper_use, scissors_use,tie_score
computer_input = get_computer_choice()
player_choice_label.config(text='Your Selected : ' + player_input[0])
computer_choice_label.config(text='Computer Selected : ' + computer_input[0])
if (player_input == computer_input):
tie_score += 1
tie_counter.config(text='Ties: ' + str(tie_score))
winner_label.config(text="Tie")
elif ((player_input[1] - computer_input[1]) % 3 == 1):
player_score += 1
winner_label.config(text="You Won!!!")
player_score_label.config(text='Your Score : ' + str(player_score))
else:
computer_score += 1
winner_label.config(text="Computer Won!!!")
computer_score_label.config(text='Computer Score : ' + str(computer_score))
def get_computer_choice():
return options[randint(0,2)]
#Buttons
rock_butt = Button(root, image=rock_photo,command=lambda:clicked(options[0]))
paper_butt = Button(root, image=paper_photo ,command=lambda:clicked(options[1]))
scissors_butt = Button(root, image=scissor_photo ,command=lambda: clicked(options[2]))
The code in question is tricky. It is a compact test to see if the player won a round of "Rock, Paper, Scissors." To understand the code you need to take it in steps:
The game options were defined as tuples: ("Rock", 0"), ("Paper", 1), ("Scissors", 2).
The fields in a tuple can be indexed using square brackets: the expression ("Rock", 0)[1] resolves as 0.
Here is the tricky part: (0 - 2) % 3, (1 - 0) % 3, and (2 - 1) % 3 all resolve as 1.
Put it all together and you can see the code in question will identify all winning combinations for the user.
elif ((player_input[1] - computer_input[1]) % 3 == 1):
player_score += 1
winner_label.config(text="You Won!!!")
player_score_label.config(text='Your Score : ' + str(player_score))
Whether the []-s are inside an if/else statement or not, they do the same thing. Which is in your case, used as an index for an iterable. Indexing starts at 0 in python, so your case is [1] refers to the second item in player_inupt and in computer_input.
It seems like either of player_input or computer input would be the following:
options[0] or options[1], or options[2] (same brackets as u can see, doing the same indexing). options[0] returns ('Rock', 0), of these two, the main function does not care for 'Rock' but it cares for the number 0 - which is the second of the two - which will be index[1]. (indexing starts at 0.)
options[0][0] is 'Rock', options[2][1] is , to further clarify the point.
Hope this helps, and as a side-note the code itself does look a bit strange, maybe look around for different tutorials if this was copied out from somewhere unreliable.
I am trying to identify how many times values exceed the previous input. the following code works for 1,7,9,0 (two times 7, exceeds 1, 9 exceeds 7), but fails on 1,5,2,4,3,0. I get that this is because I set the maximum to 5 and of course 2 and 4 are less than 5. I cannot figure out what to do to "reset" maximum back to 1
a = int(input())
counter = 0
highest = 1
while a != 0:
if a > highest:
highest = a
counter += 1
a=int(input())
# need to reset highest to next input of 'a'
print(counter)
Grateful for your patience. Still an oldie seeing whether I am brain-dead yet. Sorry if this is a dumb question, I just don't see it. Also the course I am following intimates that I can't use anything but if, else, while, no lists or anything
first_num = int(input())
incremental_count = 0
while first_numv != 0:
second_num = int(input())
if second_num != 0 and first_num < second_num:
incremental_count += 1
first_num = second_num
print(incremental_count)
Once I solved it my way, this was the answer given which is cleverer and simpler!
I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?
This is what I've got so far. the function takes in a list. (updated)
arr = [[1,20],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for c in str(num):
if str(num).count(c) > 1:
# dont know why code is popping off 12 and 13
print(l.pop(num))
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
The best way I can think about is converting the number to a string and doing a Counter on it
from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
print "The number has repeating digits"
#Two-BitAlchemist thanks for the suggestion
looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops
def countNumber(foundDigits,number):
next_number = int(number/10);
reminder = number % 10;
if(next_number < 1):
for num in foundDigits:
if(num == number or num == reminder):
return True
return False;
foundDigits.append(reminder);
return countNumber(foundDigits,next_number)
example in interpreter could be
digitsFound = list()
countNumber(digitsFound, 435229)
Solved this! I didn't know pop executes based on position not value! remove is a better fit here.
arr = [[1,40],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for char in str(num):
if str(num).count(char) < 2: continue
l.remove(num)
break
print(l)
Here is my solution, its simple and works for 2 digit numbers.
nums = list(input().rstrip().split())
def has_doubles(nums):
for number in nums:
if number[0] == number[1]:
print(number)
else:
continue
has_doubles(nums)
I am new to python and I am having some problems with this code that should print all the prime numbers that are smaller than 50 using nested loops.
Here is the code:
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
Its output is:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
So after 3, j should be 2 and i should be 4. Then it's not a prime number, so it goes back to the while loop.
And the process starts over. j and i should be incremented by one. So j should be 3 and i should be 5, 5 is prime, then it increments again to 6.
So j should still be 3 and i should be 6. But (3 <= (6/3)) <-- this is not true, so it goes to if statement and 3 which is j is bigger than 2 which is i/j, which means 6 should be prime.
But it's not. You can tell that by common sense. And I want to know what part I did wrong here. Did I miss any increments here? Thank you.
First of all, I would like to post the correct syntax for the code.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
By writing the code like this, we are able to do several things. The first thing we are able to do is get a nice visual of what is inside of what, instead of assuming anything. The second thing that we are able to do is see what is being incremented where.
Now, let us approach what is going on inside of this code. The first to realize is that we are starting off with i=2. We are then initializing a while loop that is going to stop when i is greater than 50.
So, now we are inside of the first while loop, and the next thing we are doing is calling j. This variable is equal to 2, as we can see. Not only is it equal to 2, but every time we go down to the bottom of this FIRST WHILE LOOP THAT ENDS WHEN i >=50, we go back to the start and reinitialize j to be 2 again.
This means that j is never going to start out to be two, even though we are adding to j in the SECOND (NESTED) while loop.
Everything from here should make sense, if I understood your question right. The only thing that is weird about this code, in my opinion is the:
if not (i%j)
This seems a little odd, for it would be more clerical if it said:
if (i%j == 0):
break
If you have any other questions, please feel free to ask. And if you find this helpful, feel free to accept it as your answer :)
The indented code is as follows.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j) :
print(i, " is prime")
i = i + 1
In your code, j is getting initialized to 2 with every increment of i.
See this snippet if not(i%j): break
If any j divides i, the if not(i%j) becomes true and the loop breaks but j <= (i/j) still holds else control wouldn't have entered this loop. So control skips print(i, " is prime")
So only way if(j > i/j) becomes true is when above loop never breaks. That would mean i didn't get any divisor, hence i is a prime.
I made this infinite prime number generator:
def primes_generator():
n = 1
while True:
for x in range(2, n):
if n % x == 0:
#not prime
break
else:
#prime
yield n
n+=1
you can use it like:
primes = primes_iterator()
for prime in primes:
print(i)