I am really struggling with this program. I would appreciate any kind of help.
For a natural number we say that it is strange if it is completely composed of digits 2 and 3. The user enters a natural number. The program prints the n-th strange number.
Numbers that are considered strange are 2, 3, 22, 23, 33...
n = int(input())
current_number = 1
counter_strange = 0
counter = 0
while counter_strange < n:
x = current_number
while x < n:
k = x % 10
if k != 2 or k != 3:
counter += 1
else:
break
if counter >= 1:
counter_strange += 1
current_number += 1
print(current_number-1)
Strange numbers come in blocks. A block of 2 1-digit numbers, followed by a block of 4 2-digit numbers, then 8 3-digit numbers. You can do the math and determine which block of k-digit numbers a given index n is, and how far into that block it lies. Convert that distance into a base-2 number, zero-filled to k digits, then replace 0 by 2 and 1 by 3. Convert the result back to an int:
from math import log2, ceil
def strange(n):
"""returns the nth strange number"""
#first determine number of digits:
k = ceil(log2(n+2)) - 1
#determine how far is in the block of strange k-digit numbers
d = n - (2**k - 1)
#convert to base 2, zfilling to k digits:
s = bin(d)[2:].zfill(k)
#swap 2,3 for 0,1:
s = s.replace('0','2').replace('1','3')
#finally:
return int(s)
for n in range(1,10): print(n,strange(n))
Output:
1 2
2 3
3 22
4 23
5 32
6 33
7 222
8 223
9 232
You can use a while loop with itertools.product in a generator function. Using a generator will allow you to create a stream from which you can access strange numbers on the fly:
import itertools
def strange():
c = 0
while True:
yield from map(''.join, itertools.product(*([['2', '3']]*(c:=c+1))))
s = strange()
for _ in range(10):
print(int(next(s)))
Output:
2
3
22
23
32
33
222
223
232
233
I am learning Python on my own and I am stuck on a problem from a book I purchased. I can only seem to get the numbers correctly, but I cannot get the title. I was wondering if this has anything to do with the format method to make it look better? This is what I have so far:
number = 0
square = 0
cube = 0
for number in range(0, 6):
square = number * number
cube = number * number * number
print(number, square, cube)
What I am returning:
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
I would like my desired output to be this:
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
Here we can specify the width of the digits using format in paranthesis
print('number square cube')
for x in range(0, 6):
print('{0:6d}\t {1:7d}\t {2:3d}'.format(x, x*x, x*x*x))
This would result in
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
You need to print the header row. I used tabs \t to space the numbers our properly and f-stings because they are awesome (look them up).
number = 0
square = 0
cube = 0
# print the header
print('number\tsquare\tcube')
for number in range(0, 6):
square = number * number
cube = number * number * number
# print the rows using f-strings
print(f'{number}\t{square}\t{cube}')
Output:
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
The only thing this doesn't do is right-align the columns, you'd have to write some custom printing function for that which determines the proper width in spaces of the columns based on each item in that column. To be honest, the output here doesn't make ANY difference and I'd focus on the utility of your code rather than what it looks like when printing to a terminal.
There is a somewhat more terse method you might consider that also uses format, as you guessed. I think this is worth learning because the Format Specification Mini-Language can be useful. Combined with f-stings, you go from eight lines of code to 3.
print('number\tsquare\tcube')
for number in range(0, 6):
print(f'{number:>6}{number**2:>8}{number**3:>6}')
The numbers here (e.g.:>6) aren't special but are just there to get you the output you desired. The > however is, forcing the number to be right-aligned within the space available.
I am trying to fill missing fields in a 3x3 matrix (square) in order to form a magic square (row, columns both diagonals sum are the same, filled with any none repeating positive integers ).
an example of such square will be like :
[_ _ _]
[_ _ 18]
[_ 28 _]
Since it doesn't follow the basic rules of the normal magic square where its integers are limited to 1-9(from 1 to n^2). , the magic constant (sum) is not equal to 15
(n(n^2+1)/2) rather it's unknown and has many possible values.
I tried a very naïve way where I generated random numbers in the empty fields with an arbitrary max of 99 then I took the whole square passed it into a function that checks if it's a valid magic square.
It basically keeps going forever till it finds the combination of numbers in the right places.
Needless to say, this solution was dumb, it keeps going for hours before it finds the answer if ever.
I also thought about doing an exhaustive number generation (basically trying every combination of numbers) till I find the right one but this faces the same issue.
So I need help figuring out an algorithm or some way to limit the range of random number generated
3 by 3 magic squares are a vector space with these three basis elements:
1 1 1 0 1 -1 -1 1 0
1 1 1 -1 0 1 1 0 -1
1 1 1 1 -1 0 0 -1 1
You can introduce 3 variables a, b, c that represent the contribution from each of the 3 basis elements, and write equations for them given your partial solution.
For example, given your example grid you'll have:
a + b - c = 18
a - b - c = 28
Which immediately gives 2b = 10 or b=-5. And a-c = 23, or c=a-23.
The space of solutions looks like this:
23 2a-28 a+5
2a-18 a 18
a-5 28 2a-23
You can see each row/column/diagonal adds up to 3a.
Now you just need to find integer solutions for a and c that satisfy your positive and non-repeating constraints.
For example, a=100, b=-5, c=77 gives:
23 172 105
182 100 18
95 28 177
The minimal sum magic square with positive integer elements occurs for a=15, and the sum is 3a=45.
23 2 20
12 15 18
10 28 7
It happens that there are no repeats here. If there were, we'd simply try the next larger value of a and so on.
A possible approach is translating the given numbers to other values. A simple division is not possible, but you can translate with (N-13)/5. Then you have a partial filled in square:
- - - 2 7 6
- - 1 for which there is a solution 9 5 1
- 3 - 4 3 8
When you translate these numbers back with (N*5)+13, you obtain:
23 48 43
58 38 18 which sums up to 114 in all directions (5 * 15) + (3 * 13)
33 28 53
I'm embarrassed to ask such a simple question. My term does not start for two more weeks so I can't ask a professor, and the suspense would kill me.
Why does 2 mod 4 = 2?
Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.
Modulo is the remainder, not division.
2 / 4 = 0R2
2 % 4 = 2
The sign % is often used for the modulo operator, in lieu of the word mod.
For x % 4, you get the following table (for 1-10)
x x%4
------
1 1
2 2
3 3
4 0
5 1
6 2
7 3
8 0
9 1
10 2
Modulo (mod, %) is the Remainder operator.
2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)
Much easier if u use bananas and a group of people.
Say you have 1 banana and group of 6 people, this you would express: 1 mod 6 / 1 % 6 / 1 modulo 6.
You need 6 bananas for each person in group to be well fed and happy.
So if you then have 1 banana and need to share it with 6 people, but you can only share if you have 1 banana for each group member, that is 6 persons, then you will have 1 banana (remainder, not shared on anyone in group), the same goes for 2 bananas. Then you will have 2 banana as remainder (nothing is shared).
But when you get 6 bananas, then you should be happy, because then there is 1 banana for each member in group of 6 people, and the remainder is 0 or no bananas left when you shared all 6 bananas on 6 people.
Now, for 7 bananas and 6 people in group, you then will have 7 mod 6 = 1, this because you gave 6 people 1 banana each, and 1 banana is the remainder.
For 12 mod 6 or 12 bananas shared on 6 people, each one will have two bananas, and the remainder is then 0.
2 / 4 = 0 with a remainder of 2
I was confused about this, too, only a few minutes ago. Then I did the division long-hand on a piece of paper and it made sense:
4 goes into 2 zero times.
4 times 0 is 0.
You put that zero under the 2 and subtract which leaves 2.
That's as far as the computer is going to take this problem. The computer stops there and returns the 2, which makes sense since that's what "%" (mod) is asking for.
We've been trained to put in the decimal and keep going which is why this can be counterintuitive at first.
Someone contacted me and asked me to explain in more details my answer in the comment of the question. So here is what I replied to that person in case it can help anyone else:
The modulo operation gives you the remainder of the euclidian disivion
(which only works with integer, not real numbers). If you have A such
that A = B * C + D (with D < B), then the quotient of the euclidian division of A
by B is C, and the remainder is D. If you divide 2 by 4, the quotient
is 0 and the remainder is 2.
Suppose you have A objects (that you can't cut). And you want to
distribute the same amount of those objects to B people. As long as
you have more than B objects, you give each of them 1, and repeat.
When you have less than B objects left you stop and keep the remaining
objects. The number of time you have repeated the operation, let's
call that number C, is the quotient. The number of objects you keep at
the end, let's call it D, is the remainder.
If you have 2 objects and 4 people. You already have less than 4
objects. So each person get 0 objects, and you keep 2.
That's why 2 modulo 4 is 2.
The modulo operator evaluates to the remainder of the division of the two integer operands. Here are a few examples:
23 % 10 evaluates to 3 (because 23/10 is 2 with a remainder of 3)
50 % 50 evaluates to 0 (50/50 is 1 with a remainder of 0)
9 % 100 evaluates to 9 (9/100 is 0 with a remainder of 9)
mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.
Modulo is the remainder, expressed as an integer, of a mathematical division expression.
So, lets say you have a pixel on a screen at position 90 where the screen is 100 pixels wide and add 20, it will wrap around to position 10. Why...because 90 + 20 = 110 therefore 110 % 100 = 10.
For me to understand it I consider the modulo is the integer representation of fractional number. Furthermore if you do the expression backwards and process the remainder as a fractional number and then added to the divisor it will give you your original answer.
Examples:
100
(A) --- = 14 mod 2
7
123
(B) --- = 8 mod 3
15
3
(C) --- = 0 mod 3
4
Reversed engineered to:
2 14(7) 2 98 2 100
(A) 14 mod 2 = 14 + --- = ----- + --- = --- + --- = ---
7 7 7 7 7 7
3 8(15) 3 120 3 123
(B) 8 mod 3 = 8 + --- = ----- + --- = --- + --- = ---
15 15 15 15 15 15
3 3
(B) 0 mod 3 = 0 + --- = ---
4 4
When you divide 2 by 4, you get 0 with 2 left over or remaining. Modulo is just the remainder after dividing the number.
I think you are getting confused over how the modulo equation is read.
When we write a division equation such as 2/4 we are dividing 2 by 4.
When a modulo equation is wrote such as 2 % 4 we are dividing 2 by 4 (think 2 over 4) and returning the remainder.
MOD is remainder operator. That is why 2 mod 4 gives 2 as remainder. 4*0=0 and then 2-0=2. To make it more clear try to do same with 6 mod 4 or 8 mod 3.
This is Euclid Algorithm.
e.g
a mod b = k * b + c => a mod b = c, where k is an integer and c is the answer
4 mod 2 = 2 * 2 + 0 => 4 mod 2 = 0
27 mod 5 = 5 * 5 + 2 => 27 mod 5 = 2
so your answer is
2 mod 4 = 0 * 4 + 2 => 2 mod 4 = 2
For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C where C is the answer
K * B - A = |C| where K is how many times B fits in A
2 mod 4 would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)
Mod operation works with reminder.
This is called modular arithmetic.
a==b(mod m)
then m|(a-b)
a-b=km
a=b+km
So, 2=2+0*4
To answer a modulo x % y, you ask two questions:
A- How many times y goes in x without remainder ? For 2%4 that's 0.
B- How much do you need to add to get from that back to x ? To get from 0 back to 2 you'll need 2-0, i.e. 2.
These can be summed up in one question like so:
How much will you need to add to the integer-ish result of the division of x by y, to get back at x?
By integer-ish it is meant only whole numbers and not fractions whatsoever are of interest.
A fractional division remainder (e.g. .283849) is not of interest in modulo because modulo only deals with integer numbers.
For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).
This could be a good time to mention the modr() function. It returns both the whole and the remainder parts of a division.
print("\n 17 // 3 =",17//3," # Does the same thing as int(17/3)")
print(" 17 % 3 =",17%3," # Modulo division gives the remainder.")
whole, remain = divmod(17,3)
print(" divmod(17,3) returns ->",divmod(17,3),end="")
print(" because 3 goes into 17,",whole,"times with a remainder of",remain,end=".\n\n")
The way I go about it is, 2%4 can be interpreted as what is the highest factor of 4 that is less or equal to 2, and that is 0, therefore 2 (the left operand from 2%4) minus(-) 0 is 2
Given a height 1<=h<=15, how do I go about drawing this tree? I'll need to be able to traverse it later to solve some questions.
For h = 1, just the root labeled 1.
For h = 2,
3
1 2
For h = 3,
7
3 6
1 2 4 5
etc.
All that really strikes so far has been trying to find a relation from the top-down (for the left side tree, the left node will be (parent-1)/2 and the right child is parent-1 but this isn't a consistent pattern), but I can't seem to find anything . Since i need to be able to generate the tree, I'm not sure how to use a heap-structure either. I'm not sure where to start on recursion either. Any ideas are welcome.
Your tree could be drawn recursively, but here is non-recursive code.
def ruler(n):
result = 1
while not (n & 1):
n >>= 1
result += 1
return result
def printtree(h):
widthofnum = len(str(2**h - 1))
for row in range(h, 0, -1):
maxcol = 2**(h - row)
width = 2**(row-1) * (widthofnum + 1) - 1
valincr = 2**row - 2
val = valincr + 1
for col in range(1, maxcol + 1):
print(str(val).center(width), end=' ')
val += ruler(col) + valincr
print()
printtree(3)
That prints
7
3 6
1 2 4 5
while printtree(5) gives
31
15 30
7 14 22 29
3 6 10 13 18 21 25 28
1 2 4 5 8 9 11 12 16 17 19 20 23 24 26 27
The spacing may not be ideal for larger numbers, but it works. Note that each line ends in at least one space, for code simplicity. The print statement means this is Python 3.x code. This non-recursive code lets us print from top-to-bottom, left-to-right without any backtracking or storage of strings. However, that complicates the calculations involved.
One key to that code is the discrete ruler function, which can be defined as "the exponent of the largest power of 2 which divides 2n." It is more visually seen as the height of consecutive marks on an inch ruler. This determines the increases in values between numbers in a row. The rest of the code should be straightforward.