How to get the middle 5 digits of a number - python

I'm doing a little project and I essentially need to figure out the middle 5 digits of a number (e.g. 123454321 would return 34543). If the number is 4 digits (e.g. 1234) it will return the middle two (in the case of 1234 this would be 23). If the number is 3 digits, it will return the middle number (e.g. 123 would return 2), and if the number is 1 or 2 digits the code won't accept the input.
I've tried doing some research about this online, but haven't really managed to find anything other than the "Middle-square method" but the implementation for python they have doesn't seem to work.
num = 730945296 #Random number for testing
num_len = len(str(num))
print(num*num) #debug
print(str(num*num).zfill(num_len)) #debug
num = int(str(num*num).zfill(num_len)[round(num_len/4):round((num_len/4)*3)])
print(num)
is my representation of the implementation for python but as I stated above, this doesn't seem to work.
In this case the output was 9452 but I expected 09452.
I'm aware I'm not doing extra checks like whether output is more than 5 digits or how long input is but I figured I should concentrate on getting the middle digits first.

Hint: The reason you are not getting 0 at the beginning of the answer, is that you are storing the value as int. Try using string as a number and the problem will be a piece of cake.

Related

How can I fix this code so that inputs that start and end with 0 will show the zeros

My code runs fine, for example, if i input 123, i will get 321. However there is a problem when I try the input 01230, it would output 321. I can't seem to figure it out.
edit: it has to be done using integers as data type.
while True:
reverse=0
num=str(input("Enter an integer of at least 2 digits or -1 to quit: "))
if num == str(-1):
break
elif len(num)< 2 or len(num)>11:
print("error")
else:
num=int(num)
while(num>0):
lastDigit=num%10
reverse=(reverse*10)+lastDigit
num=num//10
print(reverse)
I have tried using if statements to check for the zeros but i felt like that was too inefficient and couldn't figure out a better way.
You could just keep your variables as strings. Following is a snippet of code that tweaks your current program.
while True:
reverse=0
num=str(input("Enter an integer of at least 2 digits or -1 to quit: "))
if num == str(-1):
break
elif len(num)< 2 or len(num)>11:
print("error")
else:
reverse = num[::-1]
print(reverse)
Testing this results in the following terminal output.
#Dev:~/Python_Programs/Palindrome$ python3 Reverse.py
Enter an integer of at least 2 digits or -1 to quit: 01230
03210
Enter an integer of at least 2 digits or -1 to quit: -1
Give that a try and see if it meets the spirit of your project.
First of all, you don't need to use str() function to convert the value you get from user, because input() function always returns string as return type. See https://docs.python.org/3/library/functions.html#input for more information.
This part will try to convert string num into integer but it will ignore the leading zeros because 0123 does not make any sense as an integer if you think about it.
num=int(num)
This part also won't work for the numbers that are multiplies of 10, you can either use a condition to check if that is the case and use that information at the end or you can use some other method like adding 1 to number at the beginnig and deal with it at the end (ie. 5670 -> 5671 -> 1765 -> 0765 but again leading zeros does not make any sense if you don't work with strings)
lastDigit=num%10
reverse=(reverse*10)+lastDigit
num=num//10
What you can do is, you can count the 0s at the beginning and at the end, use the same logic you already did while ignoring them and simply add when you finish reversing the number. For counting the 0s at the beginning, you should either use string format or input user again until he/she inputs a number that has no leading zeros and for the 0s at the end, use modulo operator.
You can take a look at Display number with leading zeros, this might help. You may also want to add some error handling since you directly convert user input into integer.

Why am I getting a different output when the multiplication of the digit is above 10?

#card number
card = input('Number: ')
j = int(card[::2]) # this will jump character by 1
# multiplying each other number by 2
j *= 2
print(j)
So whenever I run this code and input e.g. 1230404
The output would be correct which is 2688
But when I input for example 1230909 the output is 2798, I expected 261818
Let's look at what your code is doing.
You slice every second character from your input string, so '1230909' becomes '1399'.
You convert that to a single int, 1399.
You multiply that number by 2, producing 2798. I assure you that the computer did the math correctly.
It appears what you expected was for each digit to be doubled individually. To do that, you need to convert each digit, double it, and combine them back. Python has great facilities for this, I'd suggest a generator expression inside a join call.

Converting Binary to Decimal in python (without built in binary function)

Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.

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

Computing persistence number of an integer

I am trying to make a code that does the following:
Multiplying the digits of an integer and continuing the process gives
the surprising result that the sequence of products always arrives at
a single-digit number.
For example:
715 -> 35 -> 15 -> 5
88 -> 64 -> 24 -> 8
27 -> 14 -> 4
The number of products necessary to reach the single-digit
number is called the persistence number of that integer. Thus 715
and 88 have a persistence number of 3, while 27 has persistence 2.
Make a program to find the only two-digit number with persistence
greater than 3?
I was able to come up with a rough idea and the code is below but it doesn't seem to work:
num2=0
num3=0
num4=0
num=input("what is your number?")
while num in range(10,100):
print 'step1'
num1=num%10*num/10
if num1-10>10:
print 'step2'
num2=num1%10*num1/10
elif num2-num1>10:
print 'step3'
num3=num2%10*num2/10
elif num3-num2>10:
print 'step4'
num4=num3%10*num3/10
elif num4-num3>10:
print 'step5'
print num4
else:
break
The program is Python and I simply can't figure this out. If someone could possibly help me I would appreciate it greatly!
You should use a while or for loop to multiply the digits instead of hardcoding what to do with the first, second and so on digits.
In pseudocode...
productSoFar = 1
digitsLeftToMultipy = #the number
while there are digits left to multiply:
get the next digit and
update produtsSoFar and digitsLeftToMultiply
Also, use
10 <= n < 100
instead of
n in range(10, 100)
So you only do a couple of comparisons instead of a sequential lookup that takes time proportional to the length of the range.
Functions are friends.
Consider a function, getEnds(x), which when passed an integer, x will extract the first digit and the last digit (as integers) and return the result as a tuple in the form (first_digit, last_digit). If x is a single-digit number the tuple will contain one element and be in the form (x), otherwise it will be two. (A simple way to do this is to turn the number into a string, extract the first/last digit as a string, and then convert said strings back into numbers... however, there are many ways: just make sure to honor the function contract, as stated above and -- hopefully -- in the function documentation.)
Then, where n is the current number we are finding the persistence for:
ends = getEnds(n)
while ends contains two elements
n = first element of ends times second element of ends
ends = getEnds(n)
# while terminates when ends contained only one element
# now it's only a matter of "counting" the persistence
For added points, make sure this is in a -- [an] appropriately named/documented -- function as well and consider the use of a recursive function instead of a while-loop.
Happy coding.
If you're trying to get the digits of a number, convert it into a string first and reference them with array notation.

Categories

Resources