Create a bar graph without using matplotlib - python

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
------------------

Related

I want to create a squares with 5 by 5 squares with a space but I am not sure how to?This is what I tried

y = topLeft.getY()
for i in range(5):
x = topLeft.getX()
for c in range(5):
cellButton = CellButton(window,x,y,size,cellID=(i,c))
self._buttons.append(cellButton)
x= x + (size+padding)
y = y + (size + padding)
#padding being space between each squares
I was expecting a 25 cell which is 5 by 5 with a space between them

Why does this factorization program fail for numbers greated than 102030405060708001?

Following is a factorization program in Python. It works fine till 102030405060708001 but produces incorrect results for greater integers. Why is this so?
import math
a = []
def prime(n):
isPrime = True
for r in range(2,int(n**(1/2)+1)):
if n%r == 0:
isPrime = False
return isPrime
def factor(number):
if prime(number):
a.append(int(number))
for r in range(2, 1 + int(number**(1/2))):
if number%r == 0:
a.append(r)
number = number/r
factor(number)
break
return a
number = int(input("Enter a number whose factors you want:"))
factor(number)
print(f"Factor of {number} are ", end = ": ")
print(*a, sep = ' X ')
print(math.prod(a))
Example
Factor of 102030405060708001 are : 1867601 X 54631800401.
And the product of these factors is 102030405060708001
Factor of 102030405060708002 are : 2 X 2 X 2 X 2 X 2 X 3 X 3 X 5 X 5 X 5 X 6133 X 462119341.
But the product of these factors is 102030405060708000
Factor of 102030405060708003 are : 3 X 2 X 2 X 2 X 2 X 2 X 3 X 5 X 5 X 5 X 6133 X 462119341.
But the product of these factors is 102030405060708000

Python Nested Loops, If statement, and Function

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

Python while loop not breaking

I'm a new programmer and I'm trying to make a rudimentary password generator. But I keep getting this problem where my while loop never breaks.
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
x = 0 if x == 0:
password = ''
if n < 100:
while n > x:
password = password + random.choice(l2)
x + 1
print(password)
else:
print 'Sorry, too long'
Can someone tell me what I'm doign wrong? Thanks.
You never change n or x here:
while n > x:
password = password + random.choice(l2)
x + 1
So if the condition was True initially it will always stay True and loop infinitely. Need to do x = x + 1
Incidentally this is the exact sort of bug that Pylint would catch for you.
Please consider the following:
1) Obvious condition
x = 0
if x == 0:
password = ''
You define x = 0, and then checks if x equals 0. It is invariably True.
Hence, you can change it this way:
x = 0
password = ''
2) While loop never ends
Before you had:
while n > x:
[some code]
x + 1 # here was your mistake
Consider these two ways you can add 1 to the variable x:
x = x + 1
or
x += 1
Both mean the same thing.
For further enlightment:
https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements
Can this help? :p
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = list(l1.split())
def genpass(n):
x = 0
password=[]
if n < 100:
while n > x:
password.append(random.choice(l2))
x+=1
return ''.join(password)
else:
return('Sorry, too long')
#example with 14 char
print(genpass(14))
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
password = ''
x = 0
if n < 100:
while n > x:
password = password + random.choice(l2)
x = x + 1
print(password)
else:
print 'Sorry, too long'
genpass(10)
You made quite a few errors in your code. What is x+1? It will be x=x+1. Please go through the basics first. Why are you checking if x==0, right after assigning x=0? Don't you think the if will always be yes? Your code in a cleaned format. Hope this works.
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
x = 0
password = ''
if n < 100:
while n > x:
password = password + random.choice(l2)
x=x + 1
print(password)
else:
print ('Sorry, too long')
print("Enter how long you want your password to be")
genpass(int(input()))
You can try this, I've upgraded a little to generate more complex password.
import random
lower = 'q w e r t y u i o p a s d f g h j k l z x c v b n m'
nums = '1 2 3 4 5 6 7 8 9 0'.split()
upper = lower.upper().split()
spcl = '; ! # # & $ '.split()
all = lower.split() + nums + upper + spcl
def genpass(n):
x = 0
if x == 0:
password = ''
if n < 100:
while n > x:
password = password + random.choice(all)
x=x + 1
print(password)
else:
print('Sorry, too long')
# generates a sample password
genpass(10)

Loop does not print out correct output

x = int(input('Enter x: '))
y = int(input('Enter y: '))
product = 0
## 50 in border
border = str('-------------------------------------------------------')
print(border)
print('%15s' % 'x', '%15s' % 'y', '%23s' % 'product')
print(border)
if y < x:
temp = x
x = y
y = temp
xTwo = x
yTwo = y
productTwo = x*y
while not x <= 0:
if x % 2 == 0:
x = x / 2
y = y*2
else:
x = x - 1
product = product + y
print('%15d' % x, '%15d' % y, '%23d' % int(product))
else:
print(border)
print(xTwo, '*', yTwo, '=', productTwo)
**Below is what it produces. In the loop I want the first number line to read ' 12 14 0 ' but i am not sure where I need to place the print line for that to happen or if i can change the loop slightly to produce that result ****
Enter x: 12
Enter y: 14
-------------------------------------------------------
x y product
-------------------------------------------------------
6 28 168
3 56 168
2 56 224
1 112 224
0 112 336
-------------------------------------------------------
12 * 14 = 168
The issue is with the location of the print statement. You need to place it on the first line of the while loop. If you do not do this then the x%2=0 condition becomes true and x value is changed.
x = int(input('Enter x: '))
y = int(input('Enter y: '))
product = 0
## 50 in border
border = str('-------------------------------------------------------')
print(border)
print('%15s' % 'x', '%15s' % 'y', '%23s' % 'product')
print(border)
if y < x:
temp = x
x = y
y = temp
xTwo = x
yTwo = y
productTwo = x*y
while not x <= 0:
print('%15d' % x, '%15d' % y, '%23d' % int(product))
if x % 2 == 0:
x = x / 2
y = y*2
else:
x = x - 1
product = product + y
else:
print(border)
print(xTwo, '*', yTwo, '=', productTwo)

Categories

Resources