'0' before a number in sum_of_digits gives wrong answer - python-2.7

this is the function that returns sum of digits of a given no.
ex: 345 gives 12 (3+4+5)
def digit_sum(n):
s=0
while(n>0):
r=n%10
n=n/10
s=s+r
return s
print digit_sum(0123)
output: 11 instead of 6

Prior to Python 3, 0123 is an octal literal as it starts with a leading 0.
(Its decimal value is 83, and those digits sum to 11.)

Related

Reverse number -first digit 0 [duplicate]

When an integer is initialized as int a = 010, a is actually set to 8, but for int a = 10, a is set to 10.
Can anyone tell me why a is not set to 10 for int a = 010?
Because it's interpreting 010 as a number in octal format. And in a base-8 system, the number 10 is equal to the number 8 in base-10 (our standard counting system).
More generally, in the world of C++, prefixing an integer literal with 0 specifies an octal literal, so the compiler is behaving exactly as expected.
0 before the number means it's in octal notation. So since octal uses a base of 8, 010 would equal 8.
In the same way 0x is used for hexadecimal notation which uses the base of 16. So 0x10 would equal 16 in decimal.
In C, C++, Objective C and related languages a 0 prefix signifies an octal literal constant, so 010 = 8 in decimal.
Leading 0 in 010 means that this number is in octal form. So 010 means 8 in decimal.

Counting ways of breaking up a string of digits into numbers under 26

Given a string of digits, I wish to find the number of ways of breaking up the string into individual numbers so that each number is under 26.
For example, "8888888" can only be broken up as "8 8 8 8 8 8 8". Whereas "1234567" can be broken up as "1 2 3 4 5 6 7", "12 3 4 5 6 7" and "1 23 4 5 6 7".
I'd like both a recurrence relation for the solution, and some code that uses dynamic programming.
This is what I've got so far. It only covers the base cases which are a empty string should return 1 a string of one digit should return 1 and a string of all numbers larger than 2 should return 1.
int countPerms(vector<int> number, int currentPermCount)
{
vector< vector<int> > permsOfNumber;
vector<int> working;
int totalPerms=0, size=number.size();
bool areAllOverTwo=true, forLoop = true;
if (number.size() <=1)
{
//TODO: print out permetations
return 1;
}
for (int i = 0; i < number.size()-1; i++) //minus one here because we dont care what the last digit is if all of them before it are over 2 then there is only one way to decode them
{
if (number.at(i) <= 2)
{
areAllOverTwo = false;
}
}
if (areAllOverTwo) //if all the nubmers are over 2 then there is only one possable combination 3456676546 has only one combination.
{
permsOfNumber.push_back(number);
//TODO: write function to print out the permetions
return 1;
}
do
{
//TODO find all the peremtions here
} while (forLoop);
return totalPerms;
}
Assuming you either don't have zeros, or you disallow numbers with leading zeros), the recurrence relations are:
N(1aS) = N(S) + N(aS)
N(2aS) = N(S) + N(aS) if a < 6.
N(a) = 1
N(aS) = N(S) otherwise
Here, a refers to a single digit, and S to a number. The first line of the recurrence relation says that if your string starts with a 1, then you can either have it on its own, or join it with the next digit. The second line says that if you start with a 2 you can either have it on its own, or join it with the next digit assuming that gives a number less than 26. The third line is the termination condition: when you're down to 1 digit, the result is 1. The final line says if you haven't been able to match one of the previous rules, then the first digit can't be joined to the second, so it must stand on its own.
The recurrence relations can be implemented fairly directly as an iterative dynamic programming solution. Here's code in Python, but it's easy to translate into other languages.
def N(S):
a1, a2 = 1, 1
for i in xrange(len(S) - 2, -1, -1):
if S[i] == '1' or S[i] == '2' and S[i+1] < '6':
a1, a2 = a1 + a2, a1
else:
a1, a2 = a1, a1
return a1
print N('88888888')
print N('12345678')
Output:
1
3
An interesting observation is that N('1' * n) is the n+1'st fibonacci number:
for i in xrange(1, 20):
print i, N('1' * i)
Output:
1 1
2 2
3 3
4 5
5 8
6 13
7 21
8 34
9 55
If I understand correctly, there are only 25 possibilities. My first crack at this would be to initialize an array of 25 ints all to zero and when I find a number less than 25, set that index to 1. Then I would count up all the 1's in the array when I was finished looking at the string.
What do you mean by recurrence? If you're looking for a recursive function, you would need to find a good way to break the string of numbers down recursively. I'm not sure that's the best approach here. I would just go through digit by digit and as you said if the digit is 2 or less, then store it and test appending the next digit... i.e. 10*digit + next. I hope that helped! Good luck.
Another way to think about it is that, after the initial single digit possibility, for every sequence of contiguous possible pairs of digits (e.g., 111 or 12223) of length n we multiply the result by:
1 + sum, i=1 to floor (n/2), of (n-i) choose i
For example, with a sequence of 11111, we can have
i=1, 1 1 1 11 => 5 - 1 = 4 choose 1 (possibilities with one pair)
i=2, 1 11 11 => 5 - 2 = 3 choose 2 (possibilities with two pairs)
This seems directly related to Wikipedia's description of Fibonacci numbers' "Use in Mathematics," for example, in counting "the number of compositions of 1s and 2s that sum to a given total n" (http://en.wikipedia.org/wiki/Fibonacci_number).
Using the combinatorial method (or other fast Fibonacci's) could be suitable for strings with very long sequences.

Why are integers converted to octal numbers here? [duplicate]

This question already has answers here:
What does it mean when a numeric constant in C/C++ is prefixed with a 0?
(7 answers)
Closed 7 years ago.
I am unable to understand output of below mentioned program-
#include <stdio.h>
int main()
{
int i, a[8]={000, 001, 010, 011, 100, 101, 110, 111};
for(i=0;i<8;i++)
{
printf("%d\t",a[i]);
}
system("pause");
return 0;
}
OUTPUT -
0 1 8 9 100 101 110 111
Why are the initial four values getting converted here???
Any integer literal that starts with a 0 followed by other digits is octal, just like any integer literal starting with 0x or 0X, followed by digits, is hexadecimal. C++14 will add 0b or 0B as a prefix for binary integer literals.
See more on integer literals in C++ here.
If you start a number with a 0 it gets converted to an octal number
0xNumber is hex

Octal to binary conversion confusion

I have a code in C++ which convert 2 digits octal number to binary number. For testing validity of the code I used several online conversion site like
this and
this
When I enter 58 or 59 in as an octal value it says invalid octal values but when I enter 58 in my code it gives binary number as - 101000. Again for testing I enter 101000 as binary number in above website's calculator then they gives me result 50 as octal value.
I need some explanation why this is so.
Here is the C++ code -
#include <iostream.h>
#include <conio.h>
void octobin(int);
void main()
{
clrscr();
int a;
cout << "Enter a 2-digit octal number : ";
cin>>a;
octobin(a);
getch();
}
void octobin(int oct)
{
long bnum=0;
int A[6];
//Each octal digit is converted into 3 bits, 2 octal digits = 6 bits.
int a1,a2,quo,rem;
a2=oct/10;
a1=oct-a2*10;
for(int x=0;x<6;x++)
{
A[x]=0;
}
//Storing the remainders of the one's octal digit in the array.
for (x=0;x<3;x++)
{
quo=a1/2;
rem=a1%2;
A[x]=rem;
a1=quo;
}
//Storing the remainders of the ten's octal digit in the array.
for(x=3;x<6;x++)
{
quo=a2/2;
rem=a2%2;
A[x]=rem;
a2=quo;
}
//Obtaining the binary number from the remainders.
for(x=x-1;x>=0;x--)
{
bnum*=10;
bnum+=A[x];
}
cout << "The binary number for the octal number " << oct << " is " << bnum << "." << endl;
}
Octal numbers have digits that are all in the range [0,7]. Thus, 58 and 59 are not octal numbers, and your method should be expected to give erroneous results.
The reason that 58 evaluates to 101000 is because the first digit of the octal number expands to the first three digits of the binary number. 5 = 101_2. Same story for the second part, but 8 = 1000_2, so you only get the 000 part.
An alternate explanation is that 8 = 0 (mod 8) (I am using the = sign for congruency here), so both 8 and 0 will evaluate to 000 in binary using your code.
The best solution would be to do some input validation. For example, while converting you could check to make sure the digit is in the range [0,7]
You cannot use 58 or 59 as an input value. It's octal, for Christ's sake.
Valid digits are from 0 to 7 inclusive.
If you're encoding a number in base 8, none of the octets can be 8 or greater. If you're going to do the code octet by octet, there needs to be a test to see whether the octet is 8 or 9, and to throw an error. Right now your code isn't checking this so the 8 and 9 are overflowing to 10.
58 and 59 aren't valid octal values indeed ... the maximum digit you can use is yourbase-1 :
decimal => base = 10 => Digits from 0 t 9
hexadécimal => base = 16 => Digits from 0 to 15 (well, 0 to F)
Octal => base = 8 => Digits from 0 to 7

Ternary Numbers, regex

I'm looking for some regex/automata help. I'm limited to + or the Kleene Star. Parsing through a string representing a ternary number (like binary, just 3), I need to be able to know if the result is 1-less than a multiple of 4.
So, for example 120 = 0*1+2*3+1*9 = 9+6 = 15 = 16-1 = 4(n)-1.
Even a pointer to the pattern would be really helpful!
You can generate a series of values to do some observation with bc in bash:
for n in {1..40}; do v=$((4*n-1)); echo -en $v"\t"; echo "ibase=10;obase=3;$v" | bc ; done
3 10
7 21
11 102
15 120
19 201
23 212
27 1000
31 1011
...
Notice that each digit's value (in decimal) is either 1 more or 1 less than something divisible by 4, alternately. So the 1 (lsb) digit is one more than 0, the 3 (2nd) digit is one less than 4, the 9 (3rd) digit is 1 more than 8, the 27 (4th) digit is one less than 28, etc.
If you sum up all the even-placed digits and all the odd-placed digits, then add 1 to the odd-placed ones (if counting from 1), you should get equality.
In your example: odd: (0+1)+1, even: (2). So they are equal, and so the number is of the form 4n-1.