Console print a scaling square with roatated square in the middle - python

I really am not sure how to explain my question in a title; a graphic will be best.
I've been given this problem as something to play around with in class, so far only one person has managed to achieve a solution, and it's a very complex one.
While I've spoken to him (The best we can manage, his english isn't great), I'd like to come up with my own solution, but I need some pointers, or at least new ideas..
The problem is this:
n=5
0 3 5 5 3 0
3 5 5 3
5 5
5 5
3 5 5 3
0 3 5 5 3 0
With 'n' being an input value.
So far I've got this;
#!/usr/bin/env python3
while True:
n = int(input("Enter a size : "))
z = "+"
for i in range(n*2): # ROWS
for j in range(n*2): # COLUMNS
if i == 0 or j == 0 or i == n*2 - 1 or j == n*2 - 1: # OUTLINE
print(z, end=" ")
elif j < n-i: # TOP LEFT
print(z, end=" ")
elif j >= n+i or i >= n+j: # TOP RIGHT + BOTTOM LEFT
print(z, end=" ")
elif j >= n*2-i+n-1 and i >= n*2-j+n-1: # BOTTOM RIGHT
print(z, end=" ")
else:
print(" ", end=" ")
print()
Whitch outputs this;
Enter a size : 5
+ + + + + + + + + +
+ + + + + + + +
+ + + + + +
+ + + +
+ +
+ +
+ + + +
+ + + + + +
+ + + + + + + +
+ + + + + + + + + +
The next step is to replace "z" with an equation for the places in the box I guess. But I've no idea where to start (And my math is a little rusty)

Taking a guess, I suppose this is what you mean:
def square(n):
def row(i, n):
l = [str(x) if x <= n else ' ' for x in range(i, i+n)]
return l + l[::-1]
top = [row(i, n) for i in range(1, n+1)]
return '\n'.join(' '.join(r) for r in (top + top[::-1]))
while True:
n = int(input("> "))
print(square(n))

I solved it, and not in a way I was expecting, tbh. I'd call it a dirty hack.
#!/usr/bin/env python
__author__ = "Luke Jones"
__copyright__ = "Copyleft, do what you want with it"
__license__ = "GPL"
__version__ = "0.0.1"
while True:
startV = int(input("Enter a size : "))
array1=[]
array2=[]
for i in range(1,startV+1,2):
array1.append(i)
array2 = list(array1)
array2.reverse()
n = len(array1)
for i in range(n*2): # ROWS
for j in range(n*2): # COLUMNS
if j < n-i: # TOP LEFT
print(array1[j+i], end=" ")
elif j >= n+i: # TOP RIGHT
print(array2[j-n-i], end=" ")
elif i >= n+j: # BOTTOM LEFT
print(array2[i-n-j], end=" ")
elif i >= n*2-j+n-1 and not i >= n*2-j+n:
#print("X",end=" ")
for q in range(n*2-j):
print(array2[q], end=" ")
else:
print(" ", end=" ")
print()

Related

I want to Remove the addition symbol from in-between the numbers using python and please find the below my code

limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
This is my output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
I want the + symbol only in between the numbers.Not to be in the last or the first.
A likely solution is using " + ".join(), which uses the string method on the " + " to collect the values together
>>> values = "1 2 3 4 5".split()
>>> " + ".join(values)
'1 + 2 + 3 + 4 + 5'
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
if count != limit:
allvalue += str(number) + " + "
else:
allvalue += str(number)
print(allvalue)
Hope this help.
I would like to share with you a sure shot mathematical solution to this problem.
This problem is a typical variation of Sum of n numbers problem, where the sum depicting limit here is already given as input, instead of n.
import math
limit = int(input("Limit: ")) # n * (n + 1) / 2 >= limit
n = math.ceil( ((1 + 4*2*limit)**0.5 - 1) / 2 ) # ((b^2 - 4ac)^(1/2) - b) / 2a where a = b = 1, c = 2*limit
allValue = " + ".join([str(i) for i in range(1, n+1)])
print(allValue)
You don't need both the number and count variables, and by starting from initial value you can add the + before the number.
limit = int(input("Limit: "))
count = 1
allvalue = str(count)
while count < limit:
count += 1
allvalue += " + " + str(count)
print(allvalue)
You could also try using a for loop.
limit = int(input("Limit: "))
allvalue = ""
for i in range(0, limit):
if i+1 == limit:
allvalue += str(i+1)
else:
allvalue += str(i+1) + "+"
print(allvalue)
Here is simple and easy approach, you can try slice in the result string
print(allvalue[:-2])
code:
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
print(allvalue[:-2])
output:
result shared : https://onlinegdb.com/HFC2Hv4wq
Limit: 9
1 + 2 + 3 + 4 +
1 + 2 + 3 + 4

fictitious variable in bool function

I have a task to make a program that find the fictitious variables in bool function(the bool function has a form like 010101010..).
import itertools
a = 0
fict =0
print("How many variables:")
args = int(input())
while True:
print('The function:')
func = input()
if 2**args == len(func):
break
for i in itertools.product('01', repeat=args):
print(' '.join(i) + ' ' + func[a])
print('-----------')
fict += int(func[a])
a+=1
matr = list(func)
b = None
iter = 2
check = 0
if fict % 2 != 0:
print("There is no fictitious variables")
if fict % 2 == 0:
for k in range(args):
for s in range(2**check):
if matr[:] == matr[:]:
check+=1
Algorithm for recognizing a fictitious variable from a truth table.
For the variable x1, the halves of the column of the function values ​​are compared: the upper and lower ones, since it is in the upper half that x1 = 0, and in the lower half, x1 = 1, if they coincide, then the variable x1 is fictitious;
for the variable x2, the column quarters in each half are compared, since it is in the upper quarters that x2 = 0, and in the lower quarters x2 = 1, if the quarters in each half coincide, then the variable x2 is fictitious;
and so on (quarters are followed by 1/8, 1/16, ...).
And I dont understand how to do this algorithm in python or maybe there is a lot easier algorithms.
import itertools
a = 0
fict =0
print("How many variables:")
args = int(input())
while True:
print('The function:')
func = input()
if 2**args == len(func):
break
for i in itertools.product('01', repeat=args):
print(' '.join(i) + ' ' + func[a])
print('-----------')
fict += int(func[a])
a+=1
matr = list(func)
b = None
iter = 1
check = 0
if fict % 2 != 0:
print("There is no fictitious variables")
if fict % 2 == 0:
for k in range(args):
for s in range(2**check):
if matr[:int((2**args) / 2**iter)] == matr[int((2**args) / 2**iter ) : int(((2**args) / 2**iter) + (2**args) / 2**iter)]:
del matr[:int(((2**args) / 2**iter) + (2**args) / 2**iter)]
if len(matr) == 0:
print('Fictitious' + ' ' + str(k+1))
check += 1
iter += 1
matr = list(func)
It works

How to take the cube root of floats using python

x = -37
epsilon = 0.01
num_guess = 0
low = 0.0
high = abs(x)
ans = ((low + high)/2.0)
while abs(ans**3-abs(x)) >= epsilon:
#print("low = " + str(low) + " high " + str(high) + " ans = " + str(ans))
if ans**3 < abs(x):
low = ans
else :
high = ans
ans = ((low + high)/2.0)
num_guess += 1
if x < 0:
ans = -ans
print("Steps taken during bisecction search: ",num_guess)
print("The cube root of " + str(x) + " is " + str(ans))
this is the code sample. I couldn't find a way to find the cube root of floats. Dont know where to insert the command and somehow the site needs more details , so this is why I am writing so much
You could simply write the root as a power.
For instance, x ** (1/3) gives you the cubic root of x.

Creating a triangle of characters from a users input

For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string.
Example of what the triangle is suppose to look like
The problem is I can't figure out how to divide my triangle in half without hard coding it or how to properly display the white space without a loop (were not allowed to in the assignment). Right now if I were to put in "ab" it would return:
aabb
aabbaabb
aabbaabbaabb
aabbaabbaabbaabb
aabbaabbaabbaabbaabb
Instead of:
aabb
aaaabbbb
aaaaaabbbbbb
aaaaaaaabbbbbbbb
aaaaaaaaaabbbbbbbbbb
Here's my code:
#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")
#CALCULATE IF userString is less than or equal to 7 and is even
if len(userString) <= 7 and len(userString) % 2 == 0:
print (" " * 5 + userString)
print(" " * 4 + userString * 2)
print(" " * 3 + userString * 3)
print(" " * 2 + userString * 4)
print(" " + userString * 5)
#CALCULATE IF userString is less than 7 but and off
elif len(userString) <=7 and len(userString) % 2 == 1:
print("You are odd")
#CALCULATE IF userString is over 7 characters
else:
print ('The string is too long. \nGood-bye!')
Here's how you can do this:
def print_next(st, index):
if index < 6: # have not reached 5 - print offset and string
offset = 6-index
print ' '*offset+st
index=index+1 # increase counter
print_next((st[0:2]+st[-2:len(st)])*index,index) # recursively go next
print_next('aabb',1) # initial call with index set to 1
I think you can use a stack to save each line so you can easily get a triangle-like output. Also because you can't use loop so my suggestion would be recursive.
public_stack = []
def my_func(original_str, line_count, space_num):
if(line_count == 0):
return
times = line_count * 2
half_length = len(original_str) / 2
left_str = original_str[:half_length] * times
right_str = original_str[half_length:] * times
space_str = ' ' * space_num
complete_str = space_str + left_str + right_str
global public_stack
public_stack.append(complete_str)
space_num += len(original_str)
line_count -= 1
return my_func(original_str,line_count,space_num)
if __name__ == '__main__':
original_str = 'ab'
line_count = 5
space_num = 0
my_func(original_str,line_count,space_num)
global public_stack
for i in range(len(public_stack)):
line = public_stack.pop()
print line

Simpler way to test a list using an incrementing value (Python 2.5.X)

I'm working out of a book that teaches the principles of computer programming through Python. One of the finger exercises asks that I: Write a program that asks a user to input an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root^pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print a message to that effect. I wrote a program that does what this asks. I just have one question about testing the equation with the numbers of a list. Here's my code:
x = int(raw_input('Enter an integer: '))
root = 0
pwr = [1,2,3,4,5]
listnum = 0
for root in range(0, x + 1):
while pow(root, pwr[listnum]) < x:
root += 1
if pow(root, pwr[listnum]) == x:
print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
break
listnum += 1
if pow(root, pwr[listnum]) == x:
print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
break
listnum += 1
if pow(root, pwr[listnum]) == x:
print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
break
listnum += 1
if pow(root, pwr[listnum]) == x:
print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
break
listnum += 1
if pow(root, pwr[listnum]) == x:
print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
break
listnum = 0
if pow(root, pwr[listnum]) == x:
break
else:
print 'No combinations within parameters exist'
I'd like to know how to test if pow(root, pwr[listnum]) < x for all 5 increments without having to repeat listnum += 1...if...break repeatedly. If the question is unclear I can try to elaborate more. I've seen a question regarding this exact problem, but none of them clearly answer the specific question I have, so I have no intention of reposting a question. If any other suggestions are to be made, they are much appreciated. Thanks!
Here's one way to do what you're after:
def find(x):
for root in range(x + 1):
for pwr in range(1, 6):
y = pow(root, pwr)
if y > x:
break
if y == x:
return root, pwr
return None
x = int(raw_input('Enter an integer: '))
result = find(x)
if result is None:
print 'No combinations within parameters exist'
else:
root, pwr = result
print root, "**", pwr, "=", x
I'm not sure that's what you do want, though. ^ in Python is bitwise exclusive-or, not exponentiation. So it's peculiar that the problem statement used ^.
Another peculiarity is that "No combinations ..." will never be printed, because no matter what you enter for x, pow(x, 1) == x will be found as a solution.

Categories