Creating a grid of numbers in python using a list - python

I am trying to write a program that accepts a number , n. The program will print out the numbers n to n+41 as 6 rows of 7 numbers. The first row will contain the values n to n+6, the second , the values n+7 to n+7+6 and so on.
Sample I/O:
Enter the start number: -2
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
The sample I/O looks a little weird on here but I'm sure you can see it.
I understand how to use nested loops to make a triangle but I cannot understand how to print it in a square with the next line have the previous line's value + 1.
Any help would be much appreciated

The first for loop is the key to your problem. It starts at the number entered and goes to that number plus 40 in steps of 6.
starter = int (input ('Enter a number : '))
for x in range (starter, starter + 40, 6) :
for y in range (6) :
print (x + y, end = ' ')
print ()

Before giving you a possible solution, I suggest you carefully read the lots of information about the Python language that there is both on StackOverflow and, in general, on the internet.
You will probably find answers to your questions simply by reading.
This could be one of the methods, if I understand the question correctly, to get the output you want:
# WITHOUT LIST
n = int(input('Enter the start number: '))
printed_values = 0
row_lenght = 7 # values for row
print('\nOUTPUT:\n')
for i in range(n, n+42, 1):
print(i, end='\t')
printed_values += 1
if not printed_values%row_lenght:
#a row is printed, reset printed_values
printed_values = 0
print('\n')
# WITH LIST
n = int(input('Enter the start number: '))
row_lenght = 7 # values for row
values = list(range(n, n+42, 1))
print('\nOUTPUT:\n')
for i in range(0, len(values), row_lenght):
for value in values[i:i+row_lenght]:
print(value, end='\t')
print('\n')

Related

Table of Squares and Cubes

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.

Trying to print all my items in a list to rows and columns

So im trying to print the items from the list in to a 18x4 matrix or a table. I´ve tried doing it by using format but it hasn't seem to work.
This is the desired output I want to get from the list, but im not sure how to print the first 18 items in one column and then the next 18 items in second column and so forth. I hope the description is well enough explained since english is not my first language. Any help would be greatly appreciated.
Use nested loops for the rows and columns. In the inner loop, use a stride of 18 to get every 18th element starting from the index in the first column.
for i in range(18):
for j in range(i, len(wireless_node_list), 18):
print(wireless_node_list[j], end='\t')
print()
You'll need to layout each row of output. Figuring out how many rows to display requires some basic math if the goal is to have a target number of columns:
# Some sample data
values = [x / 7 for x in range(50)]
cols = 4
# Figure out how many rows are needed
rows, extra = divmod(len(values), cols)
if extra > 0:
# That means we need one final partial row
rows += 1
# And show each row in turn
for row in range(rows):
line = ""
for col in range(cols):
i = col * rows + row
if i < len(values):
line += f"{i:3d} {values[i]:3.9f} "
print(line)
Which outputs:
0 0.000000000 13 1.857142857 26 3.714285714 39 5.571428571
1 0.142857143 14 2.000000000 27 3.857142857 40 5.714285714
2 0.285714286 15 2.142857143 28 4.000000000 41 5.857142857
3 0.428571429 16 2.285714286 29 4.142857143 42 6.000000000
4 0.571428571 17 2.428571429 30 4.285714286 43 6.142857143
5 0.714285714 18 2.571428571 31 4.428571429 44 6.285714286
6 0.857142857 19 2.714285714 32 4.571428571 45 6.428571429
7 1.000000000 20 2.857142857 33 4.714285714 46 6.571428571
8 1.142857143 21 3.000000000 34 4.857142857 47 6.714285714
9 1.285714286 22 3.142857143 35 5.000000000 48 6.857142857
10 1.428571429 23 3.285714286 36 5.142857143 49 7.000000000
11 1.571428571 24 3.428571429 37 5.285714286
12 1.714285714 25 3.571428571 38 5.428571429
This is a bit brute force, but should work. Just build your list and then do a little math with your indexes.
list = ["112312", "12321312", "9809809", "8374973498", "3827498734", "5426547", "08091280398", "ndfahdda", "ppoiudapp", "dafdsf", "huhidhsaf", "nadsjhfdk", "hdajfhk", "jkhjhkh", "hdjhkajhkj"]
build = {}
len = len(list)
rowCount = len//4 + 1
for i in range(rowCount):
build[i] = []
if i < len: build[i].append(list[i])
if i + 4 < len: build[i].append(list[i + 4])
if i + 8 < len: build[i].append(list[i + 8])
if i + 12 < len: build[i].append(list[i + 12])
print(build)
This little sample tested out fine for me.

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.

Check a variable is a multiple of 10

I need my program to check an in putted variable (e_gtin) and then calculate the GTIN from it (times the 1,3,5 and 7th number by three then add the 7 numbers up and divide by the nearest 10 times table) So far, it times the numbers and adds them up but I don't know where to go from there in terms of making it a multiple of ten
In Addition i eventually used this code
calculator = int(e_gtin[0])*3+int(e_gtin[1])+\
int(e_gtin[2])*3+int(e_gtin[3])+\
int(e_gtin[4])*3+int(e_gtin[5])+\
int(e_gtin[6])*3
rounding = round(calculator+4)
The plus 4 is so the variable will always round up rather than rounding down (The GTIN calculation specifies this)
e_gtin being an inputted 7 digit GTIN code.
Thanks go to --->
https://stackoverflow.com/users/906693/roadrunner66
You are presumably asking about calculating the check-digit on a GTIN8 number. An explanation is given here http://www.gs1.org/how-calculate-check-digit-manually
e = input("Enter a 7 digit number - ")
# note: an integer number can not be accessed like a string or list,
# make it a string first
e=str(e)
sum= int(e[0])*3+int(e[1])+\
int(e[2])*3+int(e[3])+\
int(e[4])*3+int(e[5])+\
int(e[6])*3
checkdigit = 9 - (sum-1) % 10
print sum,checkdigit
To understand the working of a the modulo operator, just play with it, make yourself a table etc.
import numpy as np
sums=np.array([50,51,52,53,54,55,56,57,58,59,60,61])
print sums
print sums % 10
print 10 - sums % 10 # all results right except for 10s which should be zeros
print 10 - (sums-1) % 10 -1
output:
[50 51 52 53 54 55 56 57 58 59 60 61]
[0 1 2 3 4 5 6 7 8 9 0 1]
[10 9 8 7 6 5 4 3 2 1 10 9]
[0 9 8 7 6 5 4 3 2 1 0 9]

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.

Categories

Resources