I am tasked with using nested loops, an if statement, and a function to reproduce the following table precisely using Python. The X's must be consistent to the example. I am struggling immensely with using functions and other code. I understand that this 9x9 grid has x's in the range 3y-9y, and 4x-9x save for the 9, 9 grid.
My current code is:
for x in range (1, 10): for y in range (1, 10):
print ( ' {:3}' . format(x * y), end = ' ')
print()
Which produces the 9x9 grid. I do not understand how to add a function into this code to create the X's where appropriate.
Table requirements
The guidance "use a function" is pretty vague.
If I were writing this code, I would break it down like this.
Each time through the loop, you're going to print something, either a number or the letter x. So it makes sense (to me at least) to write a function that takes the two arguments x and y, decides what should be printed, and returns the value.
Then your main loop doesn't have to worry about what to print; it just calls that function over and over and prints whatever it said.
def what_should_i_print(x, y):
# this function will use if/else to decide
# whether to return 'x' or return x*y
for x in range (1, 10):
for y in range (1, 10):
thing = what_should_i_print(x, y)
print ( ' {:3}' . format(thing), end = ' ')
print()
for x in range (1, 10):
for y in range (1, 10):
if (x == 9 and y == 9) or (y < 3) or (x < 4):
print ( ' {:3}' . format(x * y), end = ' ')
else:
print (' X', end = ' ')
print()
Output:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 X X X X X X X
5 10 X X X X X X X
6 12 X X X X X X X
7 14 X X X X X X X
8 16 X X X X X X X
9 18 X X X X X X 81
Related
I was studying list comprehension and came across the possibility of adding several conditions. I do not know what behavior I expected, but I cannot explain what I am getting. Why does 1 turn into 3, 2 remains a 2, and 3 turns into 6?
a = [x if x % 2 == 0 else x * 2 if x % 3 == 0 else x * 3 for x in range(1, 11)]
output:
[3, 2, 6, 4, 15, 6, 21, 8, 18, 10]
Re-writing as a loop and converting the conditional expressions to full if/elif/else statements might help explain it:
a = []
for x in range(1, 11):
if x % 2 == 0:
temp = x
elif x % 3 == 0:
temp = x * 2
else:
temp = x * 3
a.append(temp)
For 1 it goes like this:
1 % 2 = 1, so it goes to else clause,
1 % 3 = 1, so it also goes to else clause
and it gets into x*3 which is 1*3 = 3
When you write x if condition else y, you get x only if condition is true. So since the condition is false, you go to the else clause. You can look at it like this:
x if x % 2 == 0 else (x * 2 if x % 3 == 0 else x * 3) for x in range(1, 11)
Junior Python Coder here! Trying to print multiplication table with user input but stuck.
min_num=1
max_num=11
starting_range = int(input ("Enter the minimum number: "))
ending_range = int(input ("Enter the maximum number: "))
print ("The Multiplication Table of: ", starting_range)
for count in range(1, 11):
print (starting_range, 'x', count, '=', ending_range * count)
if max_num - min_num > 10 :
print('invalid range ')
else:
for num in range (min_num,max_num):
print ("The Multiplication Table of: ", ending_range)
for count in range(min_num, max_num):
print (starting_range, 'x', count, '=', ending_range * count)
I'm not sure I really understand what you're trying to do as your code isn't formatted, but for a multiplication table, a nested loop is a solution.
The basic idea is: For every number in the given range, loop over the whole range and multiply it by each element. This will print the whole multiplication table.
start = 1 # You can change these to be inputted by the user.
end = 10
for i in range(start, end + 1): # We add 1 to the end because range() is exclusive on endpoint.
for j in range(start, end + 1):
print(f"{i} x {j} = {i * j}")
If you only need the table as something like:
15 x 1
15 x 2
15 x 3
...
You can do this with one loop:
num = 10
for i in range(1, num + 1):
print(f"{num} x {i} = {num * i}")
I recommend you search up on F-strings in Python if you do not understand the print(f"..") parts. They're very convenient. Good luck!
Minimal change to original code:
min_num = 1
max_num = 11
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
# Removed the error checking, wasn't sure precisely what it was meant to do.
for num in range(starting_range,ending_range):
print ("The Multiplication Table of: ", num)
for count in range(min_num, max_num):
print (num, 'x', count, '=', num * count)
Try it at https://www.mycompiler.io/view/7JVNtxkT53k
This prints:
The Multiplication Table of: 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
The Multiplication Table of: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
The Multiplication Table of: 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Alternative code defining a function:
def print_multiplication_table(n, max_value=11):
if n > max_value or n <= 0:
raise ValueError
print(f"The Multiplication Table of: {n}")
for m in range(1, max_value):
print(f"{n} x {m} = {n*m}")
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
for i in range(starting_range, ending_range):
print_multiplication_table(i)
Try it at https://www.mycompiler.io/view/1uttFLmFEiD
I need to get a 5 digit integer as an input, and convert this integer into a 2D array and print it out as a bar graph.
The result I am trying to get is:
If the input is 19683,
It should return:
x
x x
x x
x x x
x x x
x x x
x x x x
x x x x
x x x x x
----------
This is what I have written already
x = int(input("Enter a 5 digit integer: "))
digits = [int(n) for n in str(x)]
rows = max(digits)
bar_graph = [[0] * len(digits) for i in range(rows)]
But I don't know what I should do from here.
I just need to find a way to replace the 0s with the xs and in the right order.
You started off good. You need to have each digit and to know the maximum digit (you got with rows = max(digits)).
Now all you need to do is loop the rows in decreasing order, and for each digit check if it needs to be marked in this row. This will be true when the digit is greater-than or equal-to the row number:
x = int(input("Enter a 5 digit integer: "))
digits = [int(n) for n in str(x)]
rows = max(digits)
bar_graph = []
for row in range(rows, 0, -1):
bar_graph.append(['x' if digit >= row else ' ' for digit in digits])
for row in bar_graph:
print(' '.join(row))
print('-'*(2*len(digits)+3))
But note that it's not really necessary to store everything in a 2D list and you can print directly by iterating the rows and digits:
for row in range(rows, 0, -1):
print(row, ':', ' '.join(['x' if digit >= row else ' ' for digit in digits]))
print('-'*(2*len(digits)+3))
Will give:
Enter a 5 digit integer: 19683
9 : x
8 : x x
7 : x x
6 : x x x
5 : x x x
4 : x x x
3 : x x x x
2 : x x x x
1 : x x x x x
-------------
Note that this will always "truncate" the graph to the largest digit, for example:
Enter a 5 digit integer: 11132
3 : x
2 : x x
1 : x x x x x
-------------
If you want the graph to always be "complete" (starting with 9), just change this line:
rows = 9
To get:
Enter a 5 digit integer: 11132
9 :
8 :
7 :
6 :
5 :
4 :
3 : x
2 : x x
1 : x x x x x
-------------
Here you go:
number = input("Enter a number: ")
ls = [9-int(x) for x in s]
for i in range(9,0,-1):
print(i, ':', *[' ' if v>0 else '*' for v in ls])
ls = [x-1 for x in ls]
print('-'*(len(s)*2+4))
# input: 19683
# Output:
9 : *
8 : * *
7 : * *
6 : * * *
5 : * * *
4 : * * *
3 : * * * *
2 : * * * *
1 : * * * * *
-------------
try this:
num = input()
print("\n".join([" ".join([" " if 10-line>int(j) else "x" for j in num]) for line in range(1,10)]))
Come on, and I'll put in my five cents.
x = 196594345345345432
digits = [int(n) for n in str(x)]
for i in reversed(range(1, max(digits) + 1)):
this_row = ''
for digit in digits:
if digit >= i:
this_row += 'x'
else:
this_row += ' '
print(this_row)
print('-'.rjust(len(digits), '-'))
x x
x x
x x
xx x
xxxx x x x
xxxxx xx xx xxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
------------------
So while i'm trying to figure out how the get the mean average of an numpy array and to plot it. I got the following error message:
'ValueError: x and y must have same first dimension, but have shapes (1L,) and (10L,)'
My code is as follows:
t = np.arange(0,100, 10)
x = np.arange(10)
print type(t), type(x), len(t), len(x), t, x
average = np.array([])
for x in range(len(t)):
mask = np.ones(len(t), dtype=bool)
if x is not 0:
mask[x-1] = False
mask[x]= False
if x+1 is not len(t):
mask[x+1]= False
b = np.ma.array(t,mask=mask)
average = np.append(average, np.ma.average(b))
plt.plot(x, t)
plt.plot(x, average)
plt.show'
the print returns the following
<type 'numpy.ndarray'> <type 'numpy.ndarray'> 10 10 [ 0 10 20 30 40 50 60 70 80 90] [0 1 2 3 4 5 6 7 8 9]
but then at the plots it throws the error. I don't understand why because x and t are of the same length and type.
I even tried to reproduce it but then it suddenly works:
f = np.arange(10)
g = np.arange(0,100, 10)
print f, g
plt.plot(f, g)
[0 1 2 3 4 5 6 7 8 9] [ 0 10 20 30 40 50 60 70 80 90]
Can anybody tell me why it doesn't work? and why it does work when I try to reproduce it?
The name of your list x gets overwritten by the x in your for loop. Change it to for i in range and it will work, or alternatively change the name of your list:
t = np.arange(0,100, 10)
x = np.arange(10)
average = np.array([])
for i in range(len(t)):
mask = np.ones(len(t), dtype=bool)
if i is not 0:
mask[i-1] = False
mask[i]= False
if i+1 is not len(t):
mask[i+1]= False
b = np.ma.array(t,mask=mask)
average = np.append(average, np.ma.average(b))
plt.plot(x, t)
plt.plot(x, average)
plt.show()
I'm very new to stack overflow and python so please bear with me. I am trying to write a code that will output:
0 x 8 = 0
1 x 8 = 8
2 x 8 = 16
3 x 8 = 24
4 x 8 = 32
5 x 8 = 40
6 x 8 = 48
7 x 8 = 56
8 x 8 = 64
9 x 8 = 72
I have searched the internet and tried the following:
x=(int(z)*8 for z in range(10))
print(str(z) + 'x 8 = ' + str(x))
Which prompts error messages:
"TypeError: can only concatenate list (not "str") to list"
"NameError: name 'z' is not defined"
I have tried this using 'item' instead of 'z', with no luck.
I know this is a very basic task but all solutions I can find online are the same as the invalid code I already have. Thank you for any help you can offer.
Try this:
x=(int(z)*8 for z in range(10))
print("\n".join(str(z) + ' x 8 = ' + str(y) for z, y in zip(range(10), x)))
x is the list of 8 multiplications. You then iterate over the list using a for loop and get every pair using the zip() function. You then join it with \n designating newlines.
The issue is that the variable z is only defined on your first line (within the context of the loop) and is not accessible to the other lines of your code. Instead you will want to loop through the values and perform the operation and printing on each item.
for z in range(10):
print '{0} x 8 = {1}'.format(z, z * 8)
# 0 x 8 = 0
# 1 x 8 = 8
# 2 x 8 = 16
# 3 x 8 = 24
# 4 x 8 = 32
# 5 x 8 = 40
# 6 x 8 = 48
# 7 x 8 = 56
# 8 x 8 = 64
# 9 x 8 = 72
The other alternative is to store the multiplication results in x (as you have already done) and then loop through that to display each of them using enumerate to get the index.
x = [z * 8 for z in range(10)]
for k,value in enumerate(x):
print '{0} x 8 = {1}'.format(k, value)