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.
Related
#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.
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.
I'm stuck in Codewars Kata, I hope someone could help me out (without spoiling the solution).
In fact the problem is that I didn't fully understand how it should work, I got the idea of the exercise but things are a bit confusing especially in Sample tests.
Here are the instructions:
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details.
8 + 1 = 9 and 9^2 = 81
512 = 5 + 1 + 2 = 8 and 8^3 = 512
We need to make a function, power_sumDigTerm(), that receives a number n and may output the nth term of this sequence of numbers. The cases we presented above means that:
power_sumDigTerm(1) == 81
power_sumDigTerm(2) == 512
And here are the sample tests:
test.describe("Example Tests")
test.it("n = " + str(1))
test.assert_equals(power_sumDigTerm(1), 81)
test.it("n = " + str(2))
test.assert_equals(power_sumDigTerm(2), 512)
test.it("n = " + str(3))
test.assert_equals(power_sumDigTerm(3), 2401)
test.it("n = " + str(4))
test.assert_equals(power_sumDigTerm(4), 4913)
test.it("n = " + str(5))
test.assert_equals(power_sumDigTerm(5), 5832)
My main problem is how did they get the results for the sample tests.
A good speed up trick is to not check all numbers, Any such number must be of the form a^b for integers a and b. If you find a way to enumerate those and check them you will have a fairly efficient solution.
On f(5), the sum of the numbers is 5+8+3+2 = 18. And 18^3=5832.
Brute force method would look like this for the next one:
Start at 5833, add the digits, check the powers of the sum to see if you get number. This would actually be very fast as you can see that last one only got to ^3. As soon as the power is larger than the number you are seeking, move on to the next number: 5834. When you find one, insert into a table to remember it.
The number theory experts may be able to find a more efficient method but this brute force method is likely to be pretty fast.
Grab a prime generator; you need only prime powers to generate the sequence (although you will have all integers >= 2 in the test for inclusion). This is because if a number is a composite power, it's also a prime power.
Maintain a list of current powers, indexed by the base integer. For instance, once you've made it to a limit of 100, you'll have the list
[0, 0, 64, 81, 64, 25, 36, 49, 64, 81, 100]
// Highest power no greater than the current limit
... and the current list of target numbers has only one element: [81]
Extending the limit:
Pick the lowest number in the list (25 = 5^2, in this case)
Multiply by its base: 25 => 125
Check: is 1+2+5 a root of 125? (There are minor ways to speed this up)
If so, add 125 to the list
Now, go back to all lower integers (the range [2, 5-1] ), and add any smaller prime powers of those integers. (I haven't worked out whether there can ever be more than one power to add for a given integer; that's an interesting prime-based problem.)
Whenever you add a new target number, make sure you insert in numerical order; the step in the previous paragraph may introduce a "hit" lower than the one that triggered the iteration. For instance, this could append 5832 before in finds 4913 (I haven't coded and executed this algorithm). You could collect all the added target numbers, sort that list, and append them as a block.
Although complicated, I believe that this will be notably faster than the brute-force methods given elsewhere.
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.
While solving some progrmaming problems, I've noticed that the dialogue says:
Input:
Integer N denoting size of array
Next line contains N space separated integers denoting elements in
array
How am I supposed to use the variable N so that it is functioning as supposed to and not just a useless-floating-around input-variable...
I mean, it could just be one input denoting the elements of the array, no need for the length of its elements...
PS: I know that I can just add it there just to pass the problem, I am just asking about if that N variable could be useful using Python (Without the way of a for loop, to ask N number of times for input cause it won't pass the problem).
In Python it usually is, since usually you fetch the entire line at once and process it.
Some programming languages like C++ and Java however tend to benefit from this approach since some parser tools (like Java's Scanner) work by parsing one integer at a time.
You can simply parse your input like:
input() # ignore the 'N'
arr = [int(x) for x in input().split()]
x=list(map(int,input().split())
print(x)
Try this
you will get an array of integers
If I understood you correctly, you want space-separated numbers with the length defined as the input. You can achieve that by:
N = input("Integer N denoting size of array: ")
print(" ".join(str(i + 1) for i in range(int(N))))
e.g.:
Integer N denoting size of array: 12
1 2 3 4 5 6 7 8 9 10 11 12