Division & Modulo Operator - python

I just started learning how to code, and I've been assigned a problem that I've been stuck on for many hours now and was hoping I could receive some hints at the very least to solve the problem. The main point of this exercise is to practice division and modulus. We can use basic statements, but nothing fancy like conditionals or anything since we haven't gotten to that point.
I need a user to input a # from 1 - 25, and then my program will let them know which unit and row that number is in. I've managed to get the code working for the rows, but I cannot figure out how to get the unit number.
Here's my code:
shelfNumber = int(raw_input('What is the shelf number? '))
row = int(shelfNumber / 5.1) + 1
unit =
I've tried a lot of things for unit, but none of them worked out, so I left it blank. I would appreciate any hints that anyone can give me. Thank you for any help.
Edit: I realized that I should try and at least show which ideas I've tried. If I do a regular modulo with # % 5, that works for everything but the multiples of 5 all the way on the right. I've also tried implementing the row #'s each # has but haven't gotten anywhere with that either. I've also tried something similar by dividing by a decimal, casting it as an int, then using modulo but failed, etc., etc.\
Edit: Sorry, I realized I uploaded the wrong image.

This problem would be easier if everything were countrd from 0 instead of from 1. That is, if the row and unit numbers were 0 to 4 instead of 1 to 5 and if the input value were 0 to 24 instead of 1 to 25.
In that case, we'd just write:
row = shelfNumber / 5
unit = shelfNumber % 5
Since everything starts ftom 1 ("is one-indexed" in the usual jargon), shelfNumber is one bigger than what that formula needs, and we need to make row and unit one bigger than what we computed.
But there's no trouble fixing that:
row = (shelfNumber - 1) / 5 + 1
unit = (shelfNumber - 1) % 5 + 1
In Python 3, you'd need to write // insted of /, and that will work with a reasonably recent Python 2.

Related

Quick Python Script to see if float x ∈ range without very small steps

I have float/decimal values like 2,4378472348237483274 etc.
and for some instructions there must be a condition for these numbers.
Condition must be: ∈ (range)
But for Python, 2 is in (1,3,1) but 2,1231837 is not in (1,3,1) because of the step. I don't know how to set range without steps...
So my idea is to code a little custom range that only looks at the unit.
For example: 2,47234723278
So it looks at "2" (unit) and confirm that it is in a range (1,3).
For now, I have a very slow script that has a very little step... not performant as you guess.
So either you help me building a range without any steps (but computationally not possible, I guess) or you help me building a custom range with a script that makes it only look at the integer part.
Example:
213,4
Only look at 213.
Thanks a lot
Well you could just check the borders of your range
low = 1.0
high = 3.0
def inrange(x):
if x<=high and x >= low:
return true
else:
return false
Or you could cast into an integer, which will always give you the lower whole number of your float:
int(213.4) = 213

Solving recursive sequence

Lately I've been solving some challenges from Google Foobar for fun, and now I've been stuck in one of them for more than 4 days. It is about a recursive function defined as follows:
R(0) = 1
R(1) = 1
R(2) = 2
R(2n) = R(n) + R(n + 1) + n (for n > 1)
R(2n + 1) = R(n - 1) + R(n) + 1 (for n >= 1)
The challenge is writing a function answer(str_S) where str_S is a base-10 string representation of an integer S, which returns the largest n such that R(n) = S. If there is no such n, return "None". Also, S will be a positive integer no greater than 10^25.
I have investigated a lot about recursive functions and about solving recurrence relations, but with no luck. I outputted the first 500 numbers and I found no relation with each one whatsoever. I used the following code, which uses recursion, so it gets really slow when numbers start getting big.
def getNumberOfZombits(time):
if time == 0 or time == 1:
return 1
elif time == 2:
return 2
else:
if time % 2 == 0:
newTime = time/2
return getNumberOfZombits(newTime) + getNumberOfZombits(newTime+1) + newTime
else:
newTime = time/2 # integer, so rounds down
return getNumberOfZombits(newTime-1) + getNumberOfZombits(newTime) + 1
The challenge also included some test cases so, here they are:
Test cases
==========
Inputs:
(string) str_S = "7"
Output:
(string) "4"
Inputs:
(string) str_S = "100"
Output:
(string) "None"
I don't know if I need to solve the recurrence relation to anything simpler, but as there is one for even and one for odd numbers, I find it really hard to do (I haven't learned about it in school yet, so everything I know about this subject is from internet articles).
So, any help at all guiding me to finish this challenge will be welcome :)
Instead of trying to simplify this function mathematically, I simplified the algorithm in Python. As suggested by #LambdaFairy, I implemented memoization in the getNumberOfZombits(time) function. This optimization sped up the function a lot.
Then, I passed to the next step, of trying to see what was the input to that number of rabbits. I had analyzed the function before, by watching its plot, and I knew the even numbers got higher outputs first and only after some time the odd numbers got to the same level. As we want the highest input for that output, I first needed to search in the even numbers and then in the odd numbers.
As you can see, the odd numbers take always more time than the even to reach the same output.
The problem is that we could not search for the numbers increasing 1 each time (it was too slow). What I did to solve that was to implement a binary search-like algorithm. First, I would search the even numbers (with the binary search like algorithm) until I found one answer or I had no more numbers to search. Then, I did the same to the odd numbers (again, with the binary search like algorithm) and if an answer was found, I replaced whatever I had before with it (as it was necessarily bigger than the previous answer).
I have the source code I used to solve this, so if anyone needs it I don't mind sharing it :)
The key to solving this puzzle was using a binary search.
As you can see from the sequence generators, they rely on a roughly n/2 recursion, so calculating R(N) takes about 2*log2(N) recursive calls; and of course you need to do it for both the odd and the even.
Thats not too bad, but you need to figure out where to search for the N which will give you the input. To do this, I first implemented a search for upper and lower bounds for N. I walked up N by powers of 2, until I had N and 2N that formed the lower and upper bounds respectively for each sequence (odd and even).
With these bounds, I could then do a binary search between them to quickly find the value of N, or its non-existence.

Python 3, context based division

I'm trying to find out if numbers divide cleanly by seeing if they divide into a float or an int, for example:
10/2 = 5
10/3 = 3.333
The problem is, as I understand it, you can either use / and get ONLY float results or use // and get ONLY int results. I'm trying to figure out a way to see if some number n is prime.
The idea I had was to see if all numbers between 1 and n-1 divide into floats, as that would mean none of them divide cleanly.
This is an exercise gauging my ability for an introductory course, I realize there may be some library I can import but I'm supposed to solve this problem using methods that are at my level and importing libraries isn't.
So I was wondering if theres a way to use a divison which will return the true type of the answer, if such a question even makes sense.
To see if a number "divides cleanly", you want to use the %1 operator:
10 % 3 # 1
11 % 3 # 2
12 % 3 # 0
Clearly if a divides b "cleanly", then the result is of b % a is 0.
1Modulus operator

Python find smallest multiple of numbers from 1-20. What is the issue in my code?

Yes, it's Euler problem 5. I'm new to python and I'm trying to solve a couple of problems to get used to the syntax. And yes I know that there are other question regarding the same problem, but I have to know why my code is not working:
import sys
def IsEvDivBy1to20(n):
for i in range(1,21):
if n%i!=0:
return 0
return 1
SmallMultiple = 0
for i in range(sys.maxsize**10):
if IsEvDivBy1to20(i) == 1:
SmallMultiple = i
break
print(SmallMultiple)
It returns 0.
range() by default starts at 0. The first time through your loop, then, i is 0: and so the first time through your (horribly-named) function, the values being compared against are 0.
Your code fails because,
range(sys.maxsize**10)
The first value returned by range is 0 and every number between 1 and 21 divides 0 without leaving any remainder. So, 0 is considered as the solution.
Also: Euler problems are not about brute forcing, it's also about finding an efficient solution.
For example, if a number is evenly divisible by the numbers 1 - 20 you can simply multiply 1 * 2 * ... * 20 = ... to find an upper bound. This number would clearly satisfy the conditions but it's likely not the smallest number.
You can then reason as follows: if the number can be divided by 6 then it can also be divided by 2 and 3. So I don't really need to include 6 in the 1 * 2 * ... * 20 multiplication. You can repeatedly apply this reasoning to find a much smaller upper bound and work your way towards the final answer.

NameError: name 'z' is not defined

I am trying to make a binary to decimal coverter for a project in my computing class and I get this error with my code: "NameError: name 'z' is not defined" I've looked up answers and they fix one error but give another. Here is the code:
bd = input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""")
if bd == 'a':
answer = input("""
Please enter a Binary number. Up to, and including, 8 digits of 1 and 0
""")
z += 2
for i in range(8):
if answer [ i ] == '1':
answer += 1*z**i
Any help would very much be appreciated!
Is this your first programming language? If so, let me introduce you to the concept of Variable Initialization.
When a computer is running code, it is processing bytes between the memory and the CPU. You probably know this already, but what you may not realize is that in your code, you are asking the computer to perform an operation on z, a variable that does not exist yet.
Keep something else in mind. Python does not need to initialize a variable in order to assign to it. So, why do you need to initialize z then before the program will run? The answer is simple: your first reference to z is an operation. Even though Python can automatically (without initialization) assign variables on the fly (different from other programming languages, usually), it still needs said variable to exist before math can be done with it.
The simple solution is to add z = 0 at any point before if bd == 'a': (because if you put it after, every time it goes into the if statement, it will over-write z with 0, ruining the logic for it.
Happy coding!
EDIT: In addition to this issue, the problem you will face with the error:
File "C:/Users/<USERNAME>/Desktop/Task 1.py", line 15, in <module> answer += 1*z**i TypeError: Can't convert 'int' object to str implicitly
Comes from the line:
if answer [ i ] == '1':
You see, when you type '1', you are saying that 1 is a string because you surround it with quotes, just the same as if you had written:
if answer [i] == "1":
What you need, instead, is the line
if answer [i] == 1:
Because that tells it to assign the number 1. Then, in the operation
answer += 1*z**i
You will be telling it to multiply three numbers instead of two numbers and the string "1".
In other languages like C, you must declare variables so that the computer knows the variable type. You would have to write string variable_name = "string text" in order to tell the computer that the variable is a string. In Python, the type casting happens automatically. Python sees variable = "string text" and it knows that because you used "", it is a string-type variable. Unfortunately, this means that you mistakenly made 1 a string.
Understand?
EDIT 2: The Happening
Okay, so you kept running into errors. And when I ran your code, I kept running into different errors. Because the of the tricky syntax and changing in types implicitly, I decided a much easier route to go was to rewrite the code and explain to you how and why it works. So, here is the new code:
bd = raw_input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""").lower()
## ORIGINAL CODE
##
##if bd == 'a':
## answer = input("""
##Please enter a Binary number. Up to, and including, 8 digits of 1 and/or 0
##""")
##
## print answer
## for i in range(8):
## z += 2
## if answer[i] == '1':
## answer += 1*z**i
##NEW CODE
if bd == 'a':
number_original = raw_input("Please enter a Binary number (a string of 1's and 0's)")
j = 0
number_converted = 0
for i in reversed(number):
if i == '1':
number_converted += 2**j
j+=1
print number_converted
From top to bottom, I'll go over what I wrote (I'll skip over your code) and I'll explain what it does and how it does it. Hopefully, this will help you in the decimal->binary conversion, as I assume you still have that to do.
So we begin with a few changes to your opening question. Where before you had bd=input(""), you now have bd=raw_input("").lower().
bd will still be a or b. But there was some shaky type handling in that statement, at least on my end. So, I made use of raw_input() which turns your answer into a string regardless of what it is. If you answer with 101010011 for instance, it will store the variable "101010011" and not the number 101010011 (though this would be wrong anyway-- it would be base 10, so it would actually be 101,010,011)... I also added .lower(), which as you may guess, turns your answer from whAtevErYouWritE to whateveryouwrite. This is an example of data sanitation and is vital in a good program, because people can be stupid and expect a computer to know what they mean. Computers, of course, have no idea what you mean, so you have to be very careful, know what mistakes a user can make, and plan ahead for it (BONUS: Here's a comic on the subject, which you will now definitely get).
So onto the meat of the program. We start by testing the condition for answer a with:
if bd == 'a':
Now, if you put in A, this would still work because of .lower(). If you put b, if wouldn't work (you have yet to put in your decimal->binary code!), and always remember that some day, someone will put in C, just to troll you, so include an elif for b and an else for anything else.
After this we encounter the first signs of it just being my code.
number_original = raw_input("Please enter a bin...
I've named it number_original because in code, it's always best practice to be clear and concise. Remember, the variable name this_is_the_variable_i_use_to_calculate_my_circumference is better than x so long as it explains clearly what it is, and helps other people understand your work. More advanced coders like to be ambiguous in this case, but a lot of the time it's just showing off.
I used raw_input() again because I actually want my number to be stored as a string. Remember when I said that 101010011 would be 101,010,011 to the computer? This would be very difficult to check, because the computer will assume a base 10 number. Thus, I just had it stored as a string, "101010011", and avoided that whole issue. There is also the added bonus to this that strings have manipulating methods that make it easier to work with, easier than the logic you were trying to introduce with range(8). That manipulator can be seen shortly.
Next, we declare our variables:
j = 0 #This 'j' accomplishes the same work done by your 'z' variable.
number_converted = 0 #this will be correctly converted by the end, as we add to it.
As mentioned in my original version of this post, these are initialized because the first time you operate on them inside the loop, you do math to them, and they need to exist as a number before you can do that. Even if they start at 0.
So now we look at the most interesting part, the for loop. Based on your original work, you kind of get how for loops work, but I'll go over them in a lot of detail so that hopefully, it helps you as much as possible when you need to see the big picture.
In a for loop, you are meant to iterate over a range of numbers. In your original code, you generated the range [0,1,2,3,4,5,6,7] to iterate over. I think you did this so you could keep track of which position in the binary number you were at, and I'm doing that as well, but in a different way, and one that I devised slowly in order to help you make the best decimal-to-binary system I could.
First, remember that number is a string now, so `"101010011". Next, realize that strings have indexes that can be accessed like so.
demo_string = "super mario brothers"
print demo_string[0]
print demo_string[1]
print demo_string[2]
print demo_string[3]
print demo_string[4:10]
print demo_string[:10] #if you leave out the first number, it starts at the beginning
print demo_string[10:] #if you leave out the last number, it ends at the end.
The above code will give you the following result:
s
u
p
e
r mari
super mari
o brothers
Take special notice that an index starts at 0, which is why demo_string[1] is u and not s.
Knowing this, you may begin to realize why we left number_original as a string: now we can use its index and iterate over that instead of making our own range with range()! This is why we can type for i in reverse(number_original); because that makes it loop from reverse(number_original)[0] to reverse(number_original)[i], as far as i is able to go. **Note:***We will go over why we are using* reverse() shortly.
It's time for number/computer science and math!
Have you learned yet about expressing every binary digit in the form of a power of two? I know you understand the concept underlying conversion in a binary number. Well, here's another cool trick you may or may not be aware of:
... # # # # # # <--The binary number, eg "101010"
...32 16 8 4 2 1 <--What each digit stands for in decimal form
... 5 4 3 2 1 0 <--The power of two that it stands for (2^5=32, 2^4=16...)
Another thing you'll realize is that typically (not always, but usually, binary numbers are read from right to left. This will come in handy in a moment).
So we're at the for loop. We know now that we can iterate through a string. But binary digits are read right-to-left. So, the binary number 10 = 2, not 10 = 1. This is why we wrote:
for i in reversed(string):
Because now, the for loop will iterate backwards! It will read the string right-to-left for us.
We also know that 2^x = (digit value in decimal).
So what we'll do in each iteration of the for loop is:
Check if i == '1' Note, this time we want it to be a string.
If i == '1', as in, the digit we're highlighting is a '1', then...
Take number_converted and add number_converted + 2^j
Then accumulate once to j, so it's one higher for the next trip.
To put this visually, I'll do two loops on the number 101010011.
Loop 4
j = 4
number_converted = 3 (still being converted)
is reversed(number_original)[3] == '1'? ( 1 1 0 0 1 0 1 0 1, so no)
then add 1 to j (j = 5)
Loop 5
j = 5
number_converted = 3 (still being converted)
is reversed(number_original)[4] == '1'? (1 1 0 0 1 0 1 0 1, so yes!)
then take number_converted (3) and add 2^j (2^5 = 16) to it (number_converted = 25)
then add 1 to j (j = 6)
Loop 6
j = 6
number_converted = 35 (still being converted)
this will continue until end!
So there you have it. Binary to decimal, in python.
If you have any questions about this, please ask. I remember being confused about this stuff when I first started!
And again, Happy Coding.
You need to assign z to a value becore you can use +=
Add z = 0 to the top of your script.
You never initialized z, so if you put z = 0 on the line above the if statement, you'll no longer have the issue
bd = input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""")
z = 0
if bd == 'a':
answer = input("""
Please enter a Binary number. Up to, and including, 8 digits of 1 and 0
""")
z += 2
for i in range(8):
if answer [ i ] == '1':
answer += 1*z**i
You never defined z.Try this code:
z = 0
bd = raw_input("Would you like to convert a number into:\n a) Binary to Decimal\n b) Decimal to Binary")
if bd == 'a':
answer = raw_input("Please enter a Binary number. Up to, and including, 8 digits of 1 and 0")
z += 2
ex = 0
for i in xrange(8):
if answer[i] == '1':
ex += 1*z**i

Categories

Resources