Python. Make asterisk graphic whith integers list - python

I can't print line with any integer from list.
I need result to be: if I have in list [5, 1, 2, 3], then it has to print:
*****
*
**
***
my code:
zv = []
l = 1
xa = 0
xb = 1
eil = int(input("Number of rows: "))
eill = eil
def piesinys(eil, zv):
while eil > 0:
print("*" * zv[xa:xb]) #<---- This is hard to do
xa = xa + 1
xb = xb + 1
eil = eil - 1
while eill > 0:
abc = int(input("Asterisk's in " + str(l) + " row: "))
zv.append(abc)
l = l + 1
eill = eill - 1
piesinys
Prints nothing.

Few issues with your code:
Add a global declaration so that your function can find the variables outside of it:
def piesinys(eil, zv):
global xa, xb
while eil > 0:
print("*" * zv[xa]) # This is hard to do
xa = xa + 1
xb = xb + 1
eil = eil - 1
And call the function at the end:
piesinys(eil, zv)

Completed working code:
zv = []
l = 1
xa = 0
xb = 1
eil = int(input("Įveskite eilučių skaičių: "))
eill = eil
def piesinys(eil, zv):
global xa, xb
while eil > 0:
print("*" * zv[xa])
xa = xa + 1
xb = xb + 1
eil = eil - 1
while eill > 0:
abc = int(input("Įveskite žvaigždučių skaičių " + str(l) + " eilutėje: "))
zv.append(abc)
l = l + 1
eill = eill - 1
piesinys(eil, zv)
And again, thanks everyone who helped me!

Problems I see:
piesinys is the name of the function; to actually call the function you need to do piesinys(eil, zv)
zv[xa:xb] returns a one-element list, ie [5], when you wanted the number 5. Try zv[xa] instead.
I would rewrite it as
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
pass
def get_row_values(num_rows):
values = []
for i in range(1, num_rows + 1):
prompt = "Asterisks in row {}: ".format(i)
value = get_int(prompt)
values.append(value)
return values
def draw_histogram(values):
for value in values:
print('*' * value)
def main():
num_rows = get_int("Number of rows: ")
values = get_row_values(num_rows)
draw_histogram(values)
if __name__ == "__main__":
main()

Simplest solution will be:
>>> num_list = [5, 1, 2, 3]
>>> for x in num_list:
... print '*' * x
...
*****
*
**
***

Related

How to divide code using functions Python 3.x

I got my code to work but now I need to divide it into functions input(), processing() and output().
lista=[]
lista = [int(clan) for clan in input("Unesi članove niza : ").split(',')]
lista.reverse()
rezultat=[]
c=0
for i in lista:
if i < 0:
i = i * -1
t = i
rev = 0
rev = rev * 10 + t % 10
t = t // 10
i = i * -1
rezultat.append(str(i))
else:
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t // 10
if rev == i:
c=c+1
rezultat.append(str(i))
if c == 0:
print("")
print(','.join(rezultat))
I do not really know how to do it so it would be nice if someone can help me
Something like this...
def input(clan):
lista = [int(clan) for clan in input("Unesi članove niza : ").split(',')]
lista.reverse()
return lista
def processing(lista):
rezultat = []
c = 0
for i in lista:
if i < 0:
i = i * -1
t = i
rev = 0
rev = rev * 10 + t % 10
t = t // 10
i = i * -1
rezultat.append(str(i))
else:
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t // 10
if rev == i:
c=c+1
rezultat.append(str(i))
if c == 0:
print("")
return(','.join(rezultat))
def output(result):
print(result)
if __name__ == '__main__':
result_list = input(clan)
result = processing(result_list)
output(result)
Try using the def command,
like this
def inp(): #declare a function
#your commands
inp() #run the commands
Don't forget to declare global variables a.k.a. those variable that you might alter in many functions by using the global command.
try this
def get_input():
lista = [int(clan) for clan in input("Unesi članove niza : ").split(',')]
lista.reverse()
return lista
def process_input(input):
rezultat=[]
c=0
for i in input:
if i < 0:
i = i * -1
t = i
rev = 0
rev = rev * 10 + t % 10
t = t // 10
i = i * -1
rezultat.append(str(i))
else:
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t // 10
if rev == i:
c=c+1
rezultat.append(str(i))
if c == 0:
print("")
return rezultat
def main():
lista = get_input()
result = process_input(lista)
def output(xlist):
return ','.join(xlist)
output(result)
if __name__ == "__main__":
main()
that should work, but I don't see the need to divide it into functions, since the code might even work well as one function.

IndexError: list index out of range error while enter value like 1 2 3 in Python

I am generating a graph/drawing using pyhton.
When I am entering value from backward like 6 5 4 3 it's working fine but When I am giving input like 1 2 3 it's throwing list index out of range error.
I am new to python. Please help me to fix this.
**EDIT : ** it's only accepting when first value is greater than second value for example it's working with 7 6 but not with 6 7.
here is my python code:
HUMAN_HEIGHT = 3
HUMAN_WIDTH = 3
HUMAN_LEG_OFFSET = 1
def print_2d_array(arr):
"""Print the 2D Array"""
print(f"Height = {len(arr)}, Width = {len(arr[0])}")
for row in arr:
for item in row:
print(f"{item}", end="")
print()
def increasing_slope(index):
"""Returns if the slope is increasing which is the even number"""
return index % 2 == 0
def get_indicator(index):
"""Returns the indicator for increasing or decreasing slope"""
return "/" if increasing_slope(index) else "\\"
def add_human_at(new_arr, human_location, height):
"""Adds Human to the Array"""
human_x = human_location[0]
human_y = human_location[1]
new_arr[height - human_y - 1][human_x - 1] = " "
new_arr[height - human_y - 1][human_x] = "○"
new_arr[height - human_y - 1][human_x + 1] = " "
new_arr[height - human_y][human_x - 1] = "/"
new_arr[height - human_y][human_x] = "|"
new_arr[height - human_y][human_x + 1] = "\\"
new_arr[height - human_y + 1][human_x - 1] = "<"
new_arr[height - human_y + 1][human_x] = " "
new_arr[height - human_y + 1][human_x + 1] = ">"
def create_line(y0, x0, y1, x1, index):
"""Generator that Returns the diagonal line from x,y to x1,y1"""
yield y0, x0
while y0 != y1 and x0 != x1:
y0 = y0 + (-1 if increasing_slope(index) else 1)
x0 += 1
yield y0, x0
def get_2d_mountains_from_1d_sum(arr, height, width, human_location):
new_arr = []
for i in range(height + HUMAN_HEIGHT):
mountain_row = []
for j in range(width + HUMAN_LEG_OFFSET):
mountain_row.append(" ")
new_arr.append(mountain_row)
ground = height + HUMAN_HEIGHT
prev_x, prev_y = 0, 0
for index, [x, y] in enumerate(arr):
indicator = get_indicator(index)
if prev_x >= human_location[0]:
start_x, start_y = ground - prev_y - 1, prev_x + HUMAN_LEG_OFFSET
end_x, end_y = ground - y - 1, x - 1 + HUMAN_LEG_OFFSET
else:
start_x, start_y = ground - prev_y - 1, prev_x
end_x, end_y = ground - y - 1, x - 1
for (point_y, point_x) in create_line(start_x, start_y, end_x, end_y, index):
new_arr[point_y][point_x] = indicator
prev_y = y
prev_x = x
add_human_at(new_arr, human_location, height)
print_2d_array(new_arr)
def generate_mountains(nums):
sum_nums = []
sum_at_position = 0
previous_sum = 0
total_width = 0
max_height = 0
human_location = []
for index, item in enumerate(nums):
# + or - numbers to get prefix list
if index % 2 == 0:
sum_at_position += (item - 1)
else:
sum_at_position -= (item - 1)
total_width += abs(sum_at_position - previous_sum) + 1
if sum_at_position > max_height:
max_height = sum_at_position
human_location = [total_width, max_height]
previous_sum = sum_at_position
sum_nums.append([total_width, sum_at_position])
get_2d_mountains_from_1d_sum(sum_nums, max_height + 1, total_width, human_location)
def print_mountains_human_from_input(nums):
generate_mountains(nums)
print("Enter the inputs")
a = [int(x) for x in input().split()]
print_mountains_human_from_input(a)
I added the screenshot of error..
thanks in advance.
You can add a sorting to your function to avoid a wrong input error but it will not fix the actual error:
def print_mountains_human_from_input(nums):
nums.sort(reverse=True)
generate_mountains(nums)

quadratic equations solving function on python

def quadSolve(a,b,c,r):
r = list()
if a != 0:
if b**2 - 4*a*c > 0:
k1 = (-b + (b**2-4*a*c)**(1/2))/2*a
k2 = (-b - (b**2-4*a*c)**(1/2))/2*a
r.append(k1)
r.append(k2)
if b**2 - 4*a*c == 0:
k0 = -b / 2*a
r.append(k0)
if b**2 - 4*a*c < 0:
r.clear()
if a == 0 and b != 0:
k3 = -c/b
r.append(k3)
if a==0 and b == 0:
r.clear()
return r
main():
print("ax^2 + bx + c = 0")
a = input("a is?: ")
b = input("b is?: ")
c = input("c is?: ")
r = list()
answer = quadSolve(a,b,c,r)
if len(answer) == 0:
print("no roots")
else:
print("answer is", answer)
print()
Can someone point out what's wrong here??
I'm trying to make a function that solves quadratic equations using list r
I don't know what is wrong with the main code.
Look, IDK how to use the "def something ():", but this is the way that it ran for me:
My code is:
## The rules:
# function == ax2 + bx + c
# delta == b2 - 4ac
# if delta == 0: one answer
# if delta < 0: don't exist answer E R
# if delta > 0: two answers
# result is: (+/- r/delta - b)/2a
answer = 'answer ='
print('ax^2 + bx^2 + c = 0')
a = int(input('a is: '))
b = int(input('b is: '))
c = int(input('c is: '))
delta = b**2 - 4*a*c
if delta > 0:
x = (delta**(1/2) - b)/(2*a)
x2 = (-delta**(1/2) - b)/(2*a)
print(answer, x, x2)
if delta == 0:
x = (-b)/(2*a)
print(answer, x)
if delta < 0:
print("Doesn't exist Real solution.")
PyShell example:
ax^2 + bx^2 + c = 0
a is: 1
b is: -4
c is: -12
answer = 6.0 -2.0
Another way to do, based in your code is:
Look the int(input())was added and the main(): was deleted
def quadSolve(a,b,c,r):
r = list()
if a != 0:
if b**2 - 4*a*c > 0:
k1 = (-b + (b**2-4*a*c)**(1/2))/2*a
k2 = (-b - (b**2-4*a*c)**(1/2))/2*a
r.append(k1)
r.append(k2)
if b**2 - 4*a*c == 0:
k0 = -b / 2*a
r.append(k0)
if b**2 - 4*a*c < 0:
r.clear()
if a == 0 and b != 0:
k3 = -c/b
r.append(k3)
if a==0 and b == 0:
r.clear()
return r
print("ax^2 + bx + c = 0")
a = int(input("a is?: "))
b = int(input("b is?: "))
c = int(input("c is?: "))
r = list()
answer = quadSolve(a,b,c,r)
if len(answer) == 0:
print("no roots")
else:
print("answer is", answer)
print()

Recursive function that remembers its path in global list python

I have problem with function:
tested_zeros = [(-1, -1)]
def reveal_zeros(x, y):
board_visible[y*row+x] = board[y*row+x]
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
for zero in tested_zeros:
if zero != (p, o):
tested_zeros.append((p, o)) <--broke part in my 'super' idea xD
if board[o*row+p] == " ":
return reveal_zeros(p, o)
so what is doing is checking if in array 'board[(x, y)]' is zero and its neighbors, when it is, its copying it to 'board_visible', the problem is that it bugs in (0, 0),[and calling it endlessly] so my idea was adding list tested_zeros so he remembers which points it tested but recursive function does not works that way :), and i know i can check last by(x, y) but it will loop somewhere else.
My question is how to handle this?
Here is my whole code:
import random
import numpy as np
row = 10
col = row
mine_list = list()
board = list()
board_visible = list()
num = 0
is_over = False
def get_num_of_mines():
global num
while True:
print("Podaj liczbe min: \n(z zakresu od 1 do ", (row * col) - 1, ")")
num = int(input())
if 1 <= num <= (row * col) - 1:
return num
else:
print("Błędna liczba. Podaj poprawną z zakresu")
def deploy_mines():
global mine_list
mine_x = random.randint(0, row - 1)
mine_y = random.randint(0, col - 1)
par = mine_x, mine_y
for l in mine_list:
if par == l:
return deploy_mines()
return mine_x, mine_y
def number_of_neighboring_mines(x, y):
global mine_list
num_of_neighbors = 0
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
par = p, o
for l in mine_list:
if par == l:
num_of_neighbors += 1
if num_of_neighbors == 0:
return " "
else:
return num_of_neighbors
def add_bomb(x, y):
for l in mine_list:
if (x, y) == l:
board.append("*")
return False
return True
def create_board():
global mine_list, num, board_visible
for k in range(0, num):
mine_list.append(deploy_mines())
for i in range(0, col):
for j in range(0, row):
if add_bomb(i, j):
board.append(number_of_neighboring_mines(i, j))
for i in range(0, col):
for j in range(0, row):
board_visible.append(chr(9552))
def show_board():
for l in range(0, col+1):
print('{0:2d}'.format(l), end="\t")
print()
for l in range(0, col):
print('{0:2d}'.format(l+1), end=" ")
print(np.split(np.asarray(board), row)[l])
def print_board():
for l in range(0, col+1):
print('{0:2d}'.format(l), end="\t")
print()
for l in range(0, col):
print('{0:2d}'.format(l+1), end=" ")
print(np.split(np.asarray(board_visible), row)[l])
tested_zeros = [(-1, -1)]
def reveal_zeros(x, y):
board_visible[y*row+x] = board[y*row+x]
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
for zero in tested_zeros:
if zero != (p, o) or zero is None:
print(p, o)
tested_zeros.append((p, o))
if board[o*row+p] == " ":
return reveal_zeros(p, o)
def reveal_squares(x, y):
global is_over
if board[y*row+x] == "*":
show_board()
print("Koniec gry!")
is_over = True
elif board[y*row+x] == " ":
reveal_zeros(x, y)
else:
board_visible[y*row+x] = board[y*row+x]
def sapper():
get_num_of_mines()
create_board()
while not is_over:
print_board()
reveal_squares(int(input("Podaj współrzędną x: "))-1, int(input("Podaj
współrzędną y: "))-1)
sapper()
I came up with a working function:
def reveal_zeros(x, y, steps):
board_visible[y*row+x] = board[y*row+x]
can_return = True
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o < row and p < col:
for i in steps:
if (p, o) == i:
can_return = False
if board[o*row+p] == " " and can_return:
return reveal_zeros(p, o, steps + [(p, o)])
if p == x or o == y or o < 0 or p < 0 or not can_return:
can_return = True
continue
return
Here is a sapper simulation with no winning.

how can I use a function I define in a new function I define?

My first function I defined that works
def chainPoints(aa,DIS,SEG,H):
#xtuple
n=0
xterms = []
xterm = -DIS
while n<=SEG:
xterms.append(xterm)
n+=1
xterm = -DIS + n*SEGL
#
#ytuple
k=0
yterms = []
while k<=SEG:
yterm = H + aa*m.cosh(xterms[k]/aa) - aa*m.cosh(DIS/aa)
yterms.append(yterm)
k+=1
But now I need a second function that depends on my first function, speciffically the lists xterms and yterms.
def chainLength(aa,DIS,SEG,H):
chainPoints(aa,DIS,SEG,H)
#length of chain
ff=1
Lterm=0.
totallength=0.
while ff<=SEG:
Lterm = m.sqrt((xterms[ff]-xterms[ff-1])**2 + (yterms[ff]-yterms[ff-1])**2)
totallength += Lterm
ff+=1
return(totallength)
I had it all done without defined functions, but now I need to have defined functions for each part.
You need to return results from your chainPoints() function, then assign the return value to local name(s) in your chainLength() function:
def chainPoints(aa, DIS, SEG, H):
#xtuple
n = 0
xterms = []
xterm = -DIS
while n <= SEG:
xterms.append(xterm)
n += 1
xterm = -DIS + n * SEGL
#
#ytuple
k = 0
yterms = []
while k <= SEG:
yterm = H + aa * m.cosh(xterms[k] / aa) - aa * m.cosh(DIS / aa)
yterms.append(yterm)
k += 1
return xterms, yterms
def chainLength(aa, DIS, SEG, H):
xterms, yterms = chainPoints(aa, DIS, SEG, H)
ff = 1
Lterm = 0.
totallength = 0.
while ff <= SEG:
Lterm = m.sqrt((xterms[ff] - xterms[ff-1]) ** 2 +
(yterms[ff] - yterms[ff - 1]) ** 2)
totallength += Lterm
ff += 1
return totallength
I used the same names in chainLength here, but that is not a requirement.

Categories