Table of Squares and Cubes - python

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.

Related

3x3 magic square with unknown magic constant (sum)

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

python modulo operation for basic mathematics operation [duplicate]

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

How do I draw this tree pattern in python?

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.

Formatting lists

I need to create a function that takes inputs of lists from the user and returns them as such:
>>> print_table([[0,1,2,3,4,5],[0,1,4,9,16,25],[0,1,8,27,64,125]])
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
>>> print_table(times_table(6,6))
0 0 0 0 0 0 0
0 1 2 3 4 5 6
0 2 4 6 8 10 12
0 3 6 9 12 15 18
0 4 8 12 16 20 24
0 5 10 15 20 25 30
0 6 12 18 24 30 36
The times_table refers to my current code:
def times_table(s):
n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(n+1):
s = ''
for col in range(n+1):
s += '{:3} '.format(row * col)
print(s)
Help me if you can....
To get two values as input from the user, i.e. number of columns and rows, you can do as follows:
in_values = input('Please enter two positive integers between 1 and 15, separated by comma (e.g. 2,3): ')
m,n = map(int, in_values.split(','))
print(m,n)
To print out a formatted list of lists, you may wish to consider using string formatting through the format() method of strings. One thing I notice in your upper example is that you only get to 3 digits, and the space between the numbers seems to be unchanging. For lists with large numbers, this will likely mess up the formatting of the table. By using the format() method, you can take this into account and keep your table nicely spaced.
The easiest way I can think of to accomplish this is to determine what is the single largest number (most digits) in the entire list of lists and then incorporate that in the formatting. I would recommend you read up on string formatting for the python type string (including the mini formatting language).
Assuming s is the argument passed in to print_table:
maxchars = len(str(max(max(s))))
This will provide the largest number of characters in a single entry in the list. You can then utilize this number in the formatting of the rows in a for loop:
for lst in l:
output = ""
for i in lst:
output += "{0:<{1}} ".format(i, maxchars)
print(output)
the line output += "{0:<{1}} ".format(i, maxchars) means to print the number ({0} maps to the i in the call to format) left adjusted (<) in a space of characters "maxchars" wide ({1} maps to maxchars in the call to format).
So given your list of lists above, it will print it as:
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
but if the numbers are much larger (or any of the numbers are much larger, such as the 125 being replaced with 125125, it will unfortunately look like this because it is padding each item with the appropriate number of character spaces to contain a number of 6 characters:
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125125
The above example takes a variable number of characters into account, however you could also format the string using an integer by replacing the {1} with an integer and omitting the maxchars portion (including both setting it and it being passed to format) if that is sufficient.
output += "{0:<4} ".format(i)
Optionally, you could figure out how to determine the largest number in a given column and then just format that column appropriately, however I am not going to put that in this answer.

Can anyone help me figure out the parsing error in this code?

The output of this code is quite similar but not exactly what it's supposed to be.
The code is:
def printMultiples(n):
i = 1
while (i <= 10):
print(n*i, end = ' ')
i += 1
n = 1
while (i<= 3):
printMultiples(n)
n += 1
The output is:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
Whereas it should be like:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
How should this code be modified?
add an empty print at the end of the printMultiples, outside the while (i <= 10): loop.
Your problem is that you are not printing a new line after each list of multiples. You could solve this by putting at the end of your printMultiples function outside of the loop the line
print()
To make the columns line up, you will need to completely change your approach. Currently, printMultiples() cannot know how many spaces to put after each number because it doesn't know how many times it will be called in the outer while loop.
What you might do is:
create a two dimensional array of string representations for each multiple (without printing anything yet) - the str() function will be useful for this
for each column, check the length of the longest number in that column (it will always be the last one) and add one
print each row, adding the appropriate number of spaces after each string to match the number of spaces required for that column
A simpler approach, if you're only interested in columnar output and not the precise spacing, would be to print each number with enough space after it to accommodate the largest number you expect to output. So you might get:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
(Note how there are three spaces after each number in the first three columns even though you don't need all three spaces.)
Changing your existing code to do that would be easier. See Format String Syntax for details.
If you already know you wish to pad numbers to be of width 3, then a suitable (and more pythonic) printMultiples is
def printMultiples(n):
txt = "".join(["{0: <3d}".format(n*i) for i in range(1, 11)])
print(txt)
Better would be to allow the width to change. And you could then pass a width you prefer as, eg, the width of the largest number you expect
def printMultiples(n, width=3):
txt = "".join(["{0: <{1}d}".format(n*i, width) for i in range(1, 11)])
print(txt)
width = len(str(4 * 10)) + 1
for i in range(1, 4):
printMultiples(i, width )

Categories

Resources