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
Related
I'm making an arithmetic progression with python.
After the 10 first terms, I want a question with how many more terms the user wants to see. If it's 0, it will end the program. If it's not the program return the number of terms asked. And repeat until it's 0.
After the first loop, the program works, after that the program returns an empty.
i = int(input('Start of PA: '))
r = int(input('PA Reason: '))
t1 = i
cont = 1
terms = 1
n1 = 0
while cont <= 10:
t1 = t1 + r
cont += 1
print(f'{t1} > ', end='')
while terms != 0 :
terms = int(input('\nHow many terms? '))
if terms!= 0:
while cont <= (10 + terms):
t1 = t1 + r
cont += 1
print(f'{t1} > ', end='')
else:
print('END!')
resolution
Edit: sorry for my english.
while cont <= (10 + terms):
is only the correct condition on the second batch of results. The next batch should be less than 20 + terms, and so on.
Instead of adding to terms, you should just set cont back to 0 before each loop that prints the next batch of terms.
And rather than checking whether terms is zero twice, use while True: and break out of the loop when they enter 0.
while True:
terms = int(input('\nHow many terms? '))
if terms!= 0:
cont = 0
while cont <= terms:
t1 = t1 + r
cont += 1
print(f'{t1} > ', end='')
else:
print('END!')
break
Or instead of using while loops, use for and range()
while True:
terms = int(input('\nHow many terms? '))
if terms != 0:
for _ in range(terms)
t1 = t1 + r
print(f'{t1} > ', end='')
else:
print('END!')
break
In this code there are four test cases. Three test cases are camed successfully but 4th test case was not getting expected output. Please help me.
I got 0x^3 as output in 4th test case but expected output is 0
Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
Output
Print the addition of polynomials A and B.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.Explanation
We need all test cases can be came when code was run. I want exact outputs for all test cases
Here is the question and test case inputs and outputs in the below url link
https://drive.google.com/file/d/1DhE2akiG_pX_Q_EoKaEY9EapSgz3xWhY/view?usp=sharing
def check_polinom(polinom):
checked = []
while polinom:
tmp = polinom.pop(0)
if polinom:
for i in range(len(polinom)-1, -1, -1):
if polinom[i][0] == tmp[0]:
tmp[1] += polinom[i][1]
polinom.pop(i)
checked.append(tmp)
return checked
def add_polinoms(pol_1, pol_2):
added = []
while pol_1 or pol_2:
if pol_1:
tmp = pol_1.pop(0)
for i in range(len(pol_2)):
if pol_2[i][0] == tmp[0]:
tmp[1] += pol_2[i][1]
pol_2.pop(i)
break
else:
tmp = pol_2.pop(0)
added.append(tmp)
added.sort(reverse=True)
return(added)
def print_polinom(polinom):
s = ''
if polinom:
if polinom[0][1] < 0:
s += '-'
polinom[0][1] = -polinom[0][1]
if polinom[0][1] == 1:
if polinom[0][0] == 0:
s += str(polinom[0][1])
elif polinom[0][0] == 1:
s += 'x'
else:
s += 'x^' + str(polinom[0][0])
else:
if polinom[0][0] == 1:
s += str(polinom[0][1]) + 'x'
elif polinom[0][0] == 0:
s += str(polinom[0][1])
else:
s += str(polinom[0][1]) + 'x^' + str(polinom[0][0])
polinom.pop(0)
for el in polinom:
if el[1] == 0:
continue
elif el[1] < 0:
s += ' - '
el[1] = -el[1]
else:
s += ' + '
if el[1] == 1:
if el[0] == 0:
s += str(el[1])
elif el[0] == 1:
s += 'x'
else:
s += 'x^' + str(el[0])
else:
if el[0] == 1:
s += str(el[1]) + 'x'
elif el[0] == 0:
s += str(el[1])
else:
s += str(el[1]) + 'x^' + str(el[0])
print(s)
def input_data():
while True:
try:
n = int(input())
break
except:
print('enter an integer N')
continue
a = list()
i = 1
while n > i-1:
try:
tmp = list(map(int,(input()).split()))
if len(tmp) != 2:
print('enter two space separated integers')
continue
a.append(tmp)
i += 1
except:
print('enter two space separated integers')
return a
a = check_polinom(input_data())
b = check_polinom(input_data())
c = add_polinoms(a,b)
print_polinom(c)
It seems that you code does not clean up 0 coefficients. An additional phase should be added to your processing. Once you have the final coefficients of your polinomial, you should have two adjustments. You have already described one, that turns items with coefficient 1 from the form 1x to simply x. Another one is when you turn 0x to nothing. Then you only have to be careful to output something, so you should not turn every term into nothing. That is why there is a description to represent it as 0.
The easiset way to make this work would thus be:
Add a function to check if a polinomial has all zero coefficients: is_zero_polinom
Do something like this in print_polinom:
if is_zero_polinom(polinom):
print('0')
return
<here comes the current code>
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)
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :
start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))
def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'
def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break
def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after
def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)
print('Biggest Steps is :' + str(biggest_steps))
compute_collatz(how_many, start_num)
this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks
Don't read my code until you have tried it yourself.
Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.
.
def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_
print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(x)
print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
you didn't save your biggest_steps and compared always the last 2 only.
I would suggest following change.
def compute_collatz(n_times, collatz_number):
biggest_steps = 0
for _ in range(n_times):
steps = collatz(collatz_number)
if steps > biggest_steps:
biggest_steps = steps
collatz_number += 1
print('Biggest Steps is :' + str(biggest_steps))
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()