concentric square number using python - python

i try to make square number but i stuck to print * in middle of square, the program should not using list cause this simple basic. i use looping with if else. i have try my best, maybe someone want's help me to fixed it.
sample
input:
5
a
8
output:
88888
8aaa8
8a*a8
8aaa8
8aaa8
my code:
a = int(input("Enter number: "))
b = input("Enter string: ")
c = int(input("Enter number: "))
row = 1
while(row <= a):
column = 1
while(column <= a ):
if(row == 1 or row == a or column == 1 or column == a):
print(c, end = ' ')
elif(row == a / 2 or column == a / 2)://this for * in middle
print("*" - 2, end=" ")
else:
print(b, end = ' ')
column = column + 1
row = row + 1
print()
My code that I have commented in line does not print right results, which should print *.

elif(row == a / 2 or column == a / 2) change your code to elif(row == a // 2+1 and column == a // 2+1) and remove -2 from print('*' - 2)
while(row <= a):
column = 1
while(column <= a ):
if(row == 1 or row == a or column == 1 or column == a):
print(c, end = ' ')
elif(row == a // 2+1 and column == a // 2+1):
print("*", end=" ")
else:
print(b, end = ' ')
column = column + 1
row += 1
print()

You should use Integer Division feature of Python.
You wrote a/2 which gives floating value 2.5.
But, a//2 gives integer 2
Try this for line: 11, 12:
elif((row == 1 + (a // 2)) and (column == 1 + (a // 2))): # this for * in middle
print("*", end=" ")

Related

Write a program that prompts the user to enter an integer number from 1 to 9 and displays two pyramids

I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
`
`
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
`
You just need to run the second loop after the first loop. Also your code for the second pyramid is incorrect so I changed that.
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
for k in range(i,0,-1):
print(k, end=' ')
for k in range(2,i+1):
print(k, end=' ')
count = 0
print()
Since the algorithm for constructing both pyramids is similar, it is better to make a function
def pyramid(n_rows, s_type='*'):
max_width = n_rows * 2 - 1
for i in range(0, n_rows):
stars = i * 2 + 1
side = (max_width - stars) // 2
if s_type == '*':
print(f"{' ' * side}{'* ' * stars}")
else:
side_nums = ' '.join(f'{x+1}' for x in range(0,i+1))
print(f"{' ' * side}{side_nums[1:][::-1]}{side_nums}")
rows = int(input("Enter number of rows: "))
pyramid(rows)
pyramid(rows, s_type='0')
You only need to input the row count once. You may also find using str.rjust easier for formatting.
rows = int(input('Enter a number from 1 to 9: '))
assert rows > 0 and rows < 10
output = [None] * (rows*2)
stars = '*' * (rows * 2 - 1)
for i in range(rows):
output[i] = stars[:i*2+1].rjust(rows+i)
s = ''.join(map(str, range(1, i+2))) + ''.join(map(str, range(i, 0, -1)))
output[i+rows] = s.rjust(rows+i)
print(*output, sep='\n')
Output:
Enter a number from 1 to 9: 6
*
***
*****
*******
*********
***********
1
121
12321
1234321
123454321
12345654321

Factorization: What went wrong with d? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

how to print all the output at the end of the while loop in python

I already solved this with list.append() function however my instructor told me to just use the basic python functions. Here is my code:
a = 0
b = 0
s = 0
x = str(s)
print ('Enter the first number: ', end = '')
c = input()
a = int(c)
finished = False
while not finished:
print ('Enter the next number (0 to finish): ', end ='')
n = input()
b = int(n)
if b != 0:
if b == a:
x = ('Same')
elif b > a:
x = ('Up')
elif b < a:
x = ('Down')
a = b
s = x
else:
finished = True
print (str(x))
I am aiming to print (e.g. Up Down Up Down Same in comparing the input integers) in one line at the end of the while loop. Let me know how can I improve my code. Thank you very much
Use string concatenation to get the result you want without using a list:
http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
I'll give you two hints on how to do this for your program:
Initialize x as an empty string by replacing
x=str(s)
with
x=""
There is no need for it to begin as the string "0", which str(s) does since s is 0.
Instead of saying
x=('SAME')
x=('UP')
x=('DOWN')
try saying
x=x+'SAME'
x=x+'UP'
x=x+'DOWN'
I removed the parentheses because they are not necessary.
As for style, it is good practice to name your variables as useful things instead of just letters. Last staement in an if/else chain that covers all bases should just be else. Best of luck to you sir
Not sure what result you're looking for, but perhaps this works:
a = 0
b = 99
result = ""
a = int(input('Enter the first number: '))
while b != 0:
b = int(input('Enter the next number (0 to finish): '))
if b == a:
result += ' Same'
elif b > a:
result += ' Up'
elif b < a:
result += ' Down'
a = b
print(result.strip())
Output:
Enter the first number: 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 5
Enter the next number (0 to finish): 0
Same Same Down Same Up Down
You can simply initialize x with an empty string and keep concatenating to it.
a = 0
b = 0
s = 0
x = ''
print('Enter the first number: ', end='')
c = input()
a = int(c)
finished = False
while not finished:
print('Enter the next number (0 to finish): ', end='')
n = input()
b = int(n)
if b != 0:
if b == a:
x += 'Same\n'
elif b > a:
x += 'Up\n'
elif b < a:
x += 'Down\n'
a = b
s = x
else:
finished = True
print(str(x))

matching chips in Connect Four Printing the match function (python)

I have a Connect Four program which runs appropriately but i would like to print my match_in_direction() method onto the screen...My code is as follows
class ConnectFour(object):
This initializes the board:
def __init__(self):
self.board = [[None for i in range(7)] for j in range(8)]
This gets a position of each play spot:
def get_position(self, row, column):
assert row >= 0 and row < 6 and column >= 0 and column < 7
return self.board[row][column]
This is supposed to check if the chips played are matching:
def match_in_direction(self, row, column, step_row, step_col):
assert row >= 0 and row < 6 and column >= 0 and column < 7
assert step_row != 0 or step_col != 0 # (0,0) gives an infinite loop
match = 1
while True:
nrow = row + step_row
ncolumn = column + step_col
if nrow >=0 and nrow <6 and ncolumn >=0 and ncolumn <7:
if self.board[row][column] == self.board[nrow][ncolumn]:
match == match+1
row = nrow
column = ncolumn
else:
return match
else:
return match
print match
This will be a play based on user input
def play_turn(self, player, column):
""" Updates the board so that player plays in the given column.
player: either 1 or 2
column: an integer between 0 and 6
"""
assert player == 1 or player == 2
assert column >= 0 and column < 7
for row in xrange(6):
if self.board[row][column] == None:
self.board[row][column] = player
return
Prints the Board:
def print_board(self):
print "-" * 29
print "| 0 | 1 | 2 | 3 | 4 | 5 | 6 |"
print "-" * 29
for row in range(5,-1,-1):
s = "|"
for col in range(7):
p = self.get_position(row, col)
if p == None:
s += " |"
elif p == 1:
s += " x |"
elif p == 2:
s += " o |"
else:
# This is impossible if the code is correct, should never occur.
s += " ! |"
print s
print "-" * 29
And my usage:
b = ConnectFour()
b.play_turn(1, 3)
b.play_turn(1, 3)
b.play_turn(1, 4)
b.match_in_direction(0,3,0,2)
b.print_board()
My current Output gives me the positions just fine...However it doesn't print the match_in_direction(0,3,0,2) which should be 2 because that is how many chips are matching....Any Help will be greatly appreciated.
From a quick glance in match_in_direction it looks like you have match == match+1 instead of match = match + 1 (or "better" yet match += 1)
add this to your test code:
f = b.match_in_direction(0,3,0,2)
print(m)
you don't need "print match" in the match_in_direction function because of the return statements, and print board doesn't utilize (for lack of a better word) the match in direction function so you have to print it out separately.
The formatting of your match_in_direction function is a little confusing, but I think it is because of the typo here:
if self.board[row][column] == self.board[nrow][ncolumn]:
match == match+1
It should be
match += 1

Categories