Loop does not print out correct output - python

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)

Related

Print nxn grid clockwise and print the sum of the diagonal elements

Example if n = 5 it should print
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Sum = 21+7+1+3+13+17+5+9+25
= 101
Here is my code
dim=5
result= n = 1
for in range(2,dim,2):
for i in range(4):
n+=k
result+=n
print(result)
Here is what I made
def spiral(n):
# Initialize the values
m = [[0]*n for _ in" "*n] # Define a list of list of n dim
d = n
v = n*n # values
y = 0 # cord of y
x = n # cord of x
while d > 0:
for _ in" "*d: # Equivalent to <=> for i in range(d)
x -= 1
m[y][x] = v
v-=1
d -= 1
for _ in" "*d:
y += 1
m[y][x] = v
v-=1
for _ in" "*d:
x += 1
m[y][x] = v
v-=1
d -= 1
for _ in" "*d:
y -= 1
m[y][x] = v
v-=1
return m # return the list of list
n = 5
matrix = spiral(n)
# Print lines of the matrix
print("Matrix:")
for e in matrix:
print(*e)
# Print the sum
print(f"Sum: {sum(matrix[i][i]for i in range(n)) + sum(matrix[i][n - i - 1]for i in range(n)) - 1}") # There is a - 1 at the end, because the value of the middle is 1
You can rewrite the while loop like this:
while d > 0:
for i in range(4):
for _ in" "*d:
if i%2:
y -= 2 * (i==3) - 1
else:
x -= 2 * (i==0) - 1
m[y][x] = v
v-=1
if i%2 == 0:
d -= 1
It's shorter but less easy to understand
You can compute The Sum this way
def Spiral(size: int):
if(size<=1):
return 1
else:
Sum = 4*(size)**2 - 6(size-1)
return (Sum+Spiral(size-2))
Spiral(5)

Appending a list in this situation

This is the question,
Write a Python program to find numbers in between 100 and 400 (both inclusive) where each digit of
the numbers is an even number. The numbers obtained should be printed in a comma-separated
sequence. I'm only allowed to use while loops so I'm not sure how.
Edited: It has to in a single line
My current code:
x = 100
while x < 400:
x += 2
str_x = str(x)
if int (str_x[0]) % 2 == 0 and int(str_x[1]) % 2 == 0 and int(str_x[2]) % 2 == 0:
l = [str_x]
print(l)
You need to collect the values in a list, and at the end print them comma-separated
x = 100
keep = []
while x <= 400:
strx = str(x)
if all(int(digit) % 2 == 0 for digit in strx):
keep.append(strx)
x += 2
print(",".join(keep))
# 200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,280,282,284,286,288,400
Here is a solution with only while loops and without converting to string:
i = 100
while i <= 400:
d = i
flag = True
while d > 0:
d,r = divmod(d,10)
if r%2:
flag = False
if flag:
print(i)
i += 2 # optimization as only even numbers are valid
output (as single line):
200 202 204 206 208 220 222 224 226 228 240 242 244 246 248 260 262 264 266 268 280 282 284 286 288 400
This is just some correction to have a list with all the values at the end. With only using a while loop.
x = 100
l = []
while x < 400:
x += 2
str_x = str(x)
if int(str_x[0]) % 2 == 0 and int(str_x[1]) % 2 == 0 and int(str_x[2]) % 2 == 0:
l.append(x)
print(l)
A more pythonic way in doing this:
l = lambda a, b : [
x for x in range(a, b+1)
if all(int(digit) % 2 == 0 for digit in str(x))
]
print(l(200, 401))
Cant you just do :
x= 100 # start number
while x <= 400:
odds = ['1','3','5','7','9'] # odds
t = len(str(x)) # how long string is
v = 0 # a variable
for i in list(str(x)): # a for loop
if i not in odds:# checking if its even or not
v += 1 # adds 1 to v
else:
v += 0
if v == t: #if its all even,
print(x, end = ',') #print it out.
x += 1 # move on to next one
#200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,280,282,284,286,288,400,

Create a bar graph without using matplotlib

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

How to find the largest sequence in binary array?

I'm trying to find the largest 1's secuence inside a random array.
I'm trying to find the longest connection of numbers 1 inside a binary array.
I tried to compare each value of the array with its previous values (i+-1 and j+-1), but I failed.
rows = 5
cols = 5
matrix = np.random.randint(2, size=(rows, cols))
print(matrix)
count = 0
result = 0
for i in matrix:
for j in i:
if j <= cols and j <= len(i):
if j == 1:
count += 1
result = max(result, count)
else:
count = 0
print(result)
This is an example of a random array given in my code
matrix =
[[1 1 0 1 1]
[1 0 0 0 1]
[1 1 1 1 1]
[0 0 1 0 0]
[1 0 1 0 0]]
Once we have found the largest conection of numbers 1, the result will be like that:
matrix =
[[(1) (1) 0 (1) (1)]
[(1) 0 0 0 (1)]
[(1) (1) (1) (1) (1)]
[ 0 0 (1) 0 0]
[ 1 0 (1) 0 0]]
The numbers inside the parentheses, those are the largest conection and the result would be like this:
result = 13
Complete Code
import numpy as np
rows = 200
cols = 200
arr = np.random.rand(rows, cols)
for i in range(len(arr)):
for j in range(len(arr[i])):
if arr[i][j] > 0.4:
arr[i][j] = 1
else:
arr[i][j] = 0
for ii in range(len(arr)):
for jj in range(len(arr[ii])):
if arr[ii][jj] == 1.0 or arr[ii][jj] == 1:
arr[ii][jj] = 1
else:
arr[ii][jj] = 0
arr = arr.astype(int)
print(arr)
dimension = rows * cols
danger = eval("dimension * .0002")
def find_largest(arr):
max_count = 0
visited = set() # coordinates visited by DFS
for y in range(0, len(arr)):
for x in range(0, len(arr[y])):
if arr[y][x] == 1 and (y, x) not in visited:
# Runs DFS search on (y,x) and marks cell as visited
max_count = max(max_count, explore(arr, y, x, visited))
probable_danger = suma(max_count)
print("Quantity of connections: " + str(max_count) +
" ,probability of danger: " + str(probable_danger) + " ,comparing to the total; " +
str(danger))
return max_count
def explore(arr, y, x, visited):
if arr[y][x] == 1 and (y, x) not in visited:
count = 1
visited.add((y, x))
for i, j in adj(arr, y, x):
count += explore(arr, i, j, visited)
return count
else:
return 0
def adj(arr, y, x):
# Generates valid adjacent coordinates for (y, x)
if y - 1 > 0 and arr[y - 1][x] == 1:
yield y - 1, x
if y + 1 < len(arr) and arr[y + 1][x] == 1:
yield y + 1, x
if x - 1 > 0 and arr[y][x - 1] == 1:
yield y, x - 1
if x + 1 < len(arr[y]) and arr[y][x + 1] == 1:
yield y, x + 1
def suma(max_count):
dimension = rows * cols
danger = eval("dimension * .0002")
total_ones = 0
total_zeros = 0
for i in arr:
for j in i:
if j % 2 != 0:
total_ones += 1
else:
total_zeros += 1
found = max_count / total_ones
ones = total_ones/dimension
zeros = total_zeros/dimension
print("Total of 1's "+str(ones) +
" , total of 0's: "+str(zeros))
if (found >= danger):
return found
else:
return 0
find_largest(arr)
You can look at groups of 1s in your matrix as strongly connected components in a graph. You can solve this problem using DFS.
def find_largest(arr):
max_count = 0
visited = set() # coordinates visited by DFS
for y in range(0, len(arr)):
for x in range(0, len(arr[y])):
if arr[y][x] == 1 and (y, x) not in visited:
# Runs DFS search on (y,x) and marks cell as visited
max_count = max(max_count, explore(arr, y, x, visited))
return max_count
Now on DFS itself:
def explore(arr, y, x, visited):
if arr[y][x] == 1 and (y, x) not in visited:
count = 1
visited.add((y, x))
for i, j in adj(arr, y, x):
count += explore(arr, i, j, visited)
return count
else:
return 0
def adj(arr, y, x):
# Generates valid adjacent coordinates for (y, x)
if y - 1 > 0 and arr[y - 1][x] == 1:
yield y - 1, x
if y + 1 < len(arr) and arr[y + 1][x] == 1:
yield y + 1, x
if x - 1 > 0 and arr[y][x - 1] == 1:
yield y, x - 1
if x + 1 < len(arr[y]) and arr[y][x + 1] == 1:
yield y, x + 1

What is wrong with my program? Amicable program

Question 3: Amicable
Implement a function amicable that takes a positive integer n. It returns the smallest amicable number greater than n.
Two different numbers are both amicable if the sum of the proper divisors of each is equal to the other. Any number that's part of such a pair is an amicable number.
def abundant(n):
while n > 0:
a = n
k = n
y = 0
total = 0
while k > y or n == 0:
if n % k == 0:
y = n // k
if k != n:
total = total + k + y
if k == y:
total = total - y
k -=1
total = total + 1
print(total)
def abundant2(n):
b = n
x = n
y = 0
total2 = 0
while x > y or n == 0:
if n % x == 0:
y = n // x
if x != n:
total2 = total2 + x + y
if x == y:
total2 = total2 - y
x -=1
total2 = total2 + 1
print(total2)
if total == b and total2 == a:
print('Amicable!')
amicable_numbers2 = int(total2)
amicable_numbers = int(total)
else:
print('Nope')
return abundant2
n += 1
def amicable(n):
"""Return the smallest amicable number greater than positive integer n.
Every amicable number x has a buddy y different from x, such that
the sum of the proper divisors of x equals y, and
the sum of the proper divisors of y equals x.
For example, 220 and 284 are both amicable because
1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
1 + 2 + 4 + 71 + 142 is 220
>>> amicable(5)
220
>>> amicable(220)
284
>>> amicable(284)
1184
>>> r = amicable(5000)
>>> r
5020
"""
nums = [amicable_numbers2, amicable_numbers]
nums2 = [n for n in nums if n >= amicable_numbers2 and n <= amicable_numbers]
return nums2
# return a value that is less than amicable_numbers2 and less than amicable_numbers???

Categories

Resources