I'm writing this code for something called 'Project Euler' which is basically a maths/computer science thing online, the link of which can be found here:
So anyway, when I run my code which is in Python 3.5, it doesn't do anything in the shell except the cursor bit blinks.
Here is the code in question:
`mylist=[]
a=1
b=2
c=a+b
def fib():
a=1
b=2
c=a+b
a=b
b=c
c=a+b
if a%2==0:
mylist.append(a) and print(a)
elif b%2==0:
mylist.append(b) and print(b)
elif c%2==0:
mylist.append(c) and print(c)
else:
print(end='')
while a and b and c<4000000:
fib()
print(sum(mylist))'
The question I'm trying to answer is
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
The code is meant to add even Fibonacci numbers up to 4 million to a list and then print the sum of them which would perfectly answer the question but it doesn't seem to work.
You have created an infinite loop here:
while a and b and c < 4000000:
This translates to "while a is truthy and b is truthy and c is less than 4000000", and this will always be True so your while loop will never terminate. What I mean by "truthy" is: does bool(value) return True? If so, then value is "truthy". So 1, 'hello', [], etc., are truthy, and 0, False, [], etc., are not (they are "falsey"). I will not comment on all of your logic because you will benefit more from solving the problem on your own. However, here are a few tips that should get you unstuck:
if you want to check that a, b, and c are all less than 4000000, than you can do this:
while a < 4000000 and b < 4000000 and c < 4000000:
or more succinctly:
while all(i < 4000000 for i in [a, b, c]):
In order to not create an infinite loop, you will need to make sure that either a, b, or c will be greater than 4000000 at some point in your program by incriminating their values. The math you do on a, b, and c inside your fib() function only manipulates three variables called a, b, and c that are local to that function; it does not change the values of the a, b, and c outside of that function.
Related
If I take a boolean expression and number of input variables from user, then how can I evaluate the expression (to create its truth table) by using dynamic nested loops instead of doing it like this:
expression= "a and (b or a)"
inputs=2
if inputs==2:
for a in range(0,2):
for b in range(0,2):
x = eval(expression)
print(a,b,x)
if inputs==3:
for a in range(0,2):
for b in range(0,2):
for c in range(0,2):
x = eval(expression)
print(a,b,x)
It limits the number of variables user can evaluate expression on, as I can not write loops manually. I tried using itertools.product() for this, but I don't know how to give values to the iterating variables.
from itertools import product
variables=['a','b','c']
for items in product(*variables):
rows=(eval(expression))
print(rows)
As you can see, it obviously gives error that a,b,c are undefined in eval(expression). How can I iterate each one of them over [0,1] ?
You could do it using itertools.product() simply
import itertools
inputs = int(input())
temp = [[0, 1]] * inputs
for combination in itertools.product(*temp):
print(combination)
I think you were on the right path here and itertools.product() is what you are looking for. The following is a one-liner, but you could expand it if you want. Note that I am not using eval, but rather a list comprehension paired with the already mentioned itertools.product(). Note also that you can use and, or and () in normal code.
import itertools
rows = [a and (b or c) for a, c, b in itertools.product([True, False], [True, False], [True, False])]
print(rows)
If you are using user input, it might make sense to define truthy values.
Also if you want the inputs for the truth-table, you can also do this first:
import itertools
inputs = [[a, b, c] for a, b, c in itertools.product([True, False], [True, False], [True, False])]
rows = [a and (b or c) for a, c, b in inputs]
print(rows)
Edit: If you have a lot of inputs, the logical expression would likely include any() and all().
Edit2: Now I understand what you mean. Here is a full version with a dynamic number of inputs using the above-mentioned any() and all(). In this example of a logical condition, the first half of the array (rounded down if it is an uneven length) needs to be true and at least one of the second half. Feel free to adapt the expression as you see fit. Note that your original expression does not make much sense. If the first part a is Truthy then the second part where you check for a or b is necessarily also Truthy because we already checked for a. That is why I picked a slightly modified version.
import itertools
input_num = int(input())
arrs = [[False, True]] * input_num
inputs = [x for x in itertools.product(*arrs)]
rows = [all(x[:int(len(x)/2)]) and any(x[int(len(x)/2):]) if len(x) > 1 else bool(x) for x in inputs ]
print(rows)
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
I am trying to implement Euclid's algorithm for computing the greatest common divisor using recursion. Below is the code for the same.
def euclid(a,b):
if a>b:
r=a%b
if (r == 0):
return b
else:
a=b
b=r
euclid(a,b)
print(euclid(20,4)) # Returns 4
print(euclid(20,8)) # Returns None
For the first data set, I get the correct result. But for euclid(20,8) I get a return of None.
While checking in the debugger, I did see the return value of b become 4 but then for some reason, my code jumps to euclid(a,b) and returns None.
The major takeaway here would be to understand why the code does not return 4 but jumps to the euclid(a,b) and return None.
Please refrain from giving alternative code solutions but you are very much encouraged to point out the reason for the current behaviour of the code.
The reason for that code to return None at some point is that in your control flow you eventually end up in a situation where there is no return statement, e.g. for a <= b in your first if or when r != 0 in your second if. The default behavior of Python in that case is to return None, as you seems to have discovered the hard way.
def euclid(a,b):
if a>b:
r=a%b
if (r == 0):
return b
else: # <--- no `return` in this branch!
a=b
b=r
euclid(a,b)
# else: # <--- no `return` in this branch!
# ...
Here is an updated version of your code, that addresses that and also a number of other issues:
the name of the function should be meaningful: Euclid is kind of popular and there is a bunch of things named after him, better specify that you actually want to compute the greatest common divisor (GCD)
the first if is not really needed, as it is taken care of by the subsequent code: computing r and the recursive call will take care of swapping a and b if a < b, and if a == b then r == 0, so you b is being returned directly
a = b and b = r are useless, do not use them, just have your recursive call use b and r directly
the second if can be written more clearly in one line
def gcd_euclid_recursive(a, b):
r = a % b
return gcd_euclid_recursive(b, r) if r else b
gcd_euclid_recursive(120, 72)
# 24
gcd_euclid_recursive(64, 120)
# 8
You don't actually return anything in the else path so it just assumes you know best and returns None for you.
The only reason you get 4 for print(euclid(20,4)) is because 4 is a factor of 20 so never uses the else path. Instead it returns b immediately. For anything else, the thing returned from the first recursive call to euclid() will always be None (even if a lower call to that function returns something, you throw it away when returning from the first call).
You need return euclid(a,b) rather than just euclid(a,b).
As an aside (this isn't necessary to answer your specific question but it goes a long way toward improving the implementation of the code), I'm not a big fan of the if something then return else … construct since the else is totally superfluous (if it didn't return, the else bit is automatic).
Additionally, you don't need to assign variables when you can just change what gets passed to the next recursive level.
Taking both those into account (and simplifying quite a bit), you can do something like:
def euclid(a, b):
if b == 0: return a
return euclid(b, a % b)
Your code has an indentation error and one path is missing in your code(r!=0). It should be
def euclid(a,b):
if a>=b:
r=a%b
if (r == 0):
return b
return euclid(b, r)
else:
return euclid(b, a)
I am new to coding and is trying to solve this python question
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
This is the solution given. I have not seen 'x for x in input()'expression, may I know what does this expression do ?
import math
c=50
h=30
value = []
items=[x for x in input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print (','.join(value))
This is my own solution but somehow I got a syntax error.
def sr(D):
For item in D:
return ((2*50*D)/30)**0.5
try:
a=int(input())
j=a.split(",")
print(sr(j))
except:
print('Please enter an integers or intergers seperated by comma')
The x is just a variable that gets assigned to the input that comes in via the input() function.
If you're aware of C style language (or Java), it's similar to
for(int i=0;<some_condition>;<some_operation>){}
This is just a condensed, pythonic and easy to read way to do this.
You can read more Python loops here
https://wiki.python.org/moin/ForLoop
I'm a bit confused as to how this is supposed to work. For example,
I have these two functions that I've written:
def in_range(par):
if (par >= 50) and (par <= 100):
print(True)
else:
print(False)
def squares_in_range(twoargument):
for a in range(3, 20):
b = (a*a)
print(b, end="")
if a<19:
print(end=",")
Now, I would like to use the first function in the second so to say. It should check if the numbers in the second function are within the 50-100 range and then print out "True" if its within and "False" if out of range for each number so that it becomes a list that might look like this: True, False, False, True... and so on.
How do I go about this?
edit: I am referring to "b" in the second function, not "a". I've tried calling the function but nothing happens. I guess that's because the first functions does not use "return"?
It's not clear to me which numbers, a or b, in the second function you were referring to.
This gets you a list of booleans for checking whether the numbers from a is within the range. You can modify it to check for b.
def in_range(par,alist):
if (par >= 50) and (par <= 100):
print(True)
alist.append(True)
else:
print(False)
alist.append(False)
def squares_in_range(twoargument):
within_range=[]
for a in range(3, 20):
in_range(a,within_range)
b = (a*a)
print(b)
if a<19:
print(",")
print(within_range) # print the final list of booleans
squares_in_range(1) #testing
Just write in_range(b) at some point in the second function.
I'm trying to solve a math problem but I would like to make some informatic tests before to understand what happend (and maybe find the solution with my program), my problem is :
Consider the list consisting of the first n natural numbers without zero, ie from 1 to n.
We define the transformation "moving average" on the list of n elements by adding the average of all the terms at the end of the list and eliminating the first term at the beginning of the list.
For example, if n = 4, we have: (1,2,3,4) -> (2,3,4,2.5)
By iterating this process many times, one can observe a phenomenon of standardization and that all elements of the list tend to a common value when the number of iterations tends to + infinity.
It asks for the value of n for this limit is 254859658745.
Well, i'm trying to program the function "moving average" like this :
def moving_average(liste,t):
k=0
S=0
m=0
c=0
n=len(liste)
while c<t:
while k<n:
S+=int(liste[k])
k+=1
m=S/n
liste.pop(0)
liste.append(m)
c+=1
return m
My program works but don't answer what I want, if I take liste=[1,2,3] (for example) for all t>1 the answer is always the same... but I don't understand why.
Can you help me please ?
In the interests of helping you move forwards, here is the first part of an answer. The way to debug this is like this:
def moving_average(liste,t):
k=0
S=0
m=0
c=0
n=len(liste)
while c<t:
print("At c: ", c)
k=0
while k<n:
print(" At k: ", k)
S+=int(liste[k])
k+=1
m=S/n
print(" .. new S", S)
print(" .. new k", k)
print(" .. new m", m)
liste.pop(0)
liste.append(m)
print(" liste: ", liste)
c+=1
return m
test_list = [1,2,3]
test_t = 4
print("Result:", moving_average(test_list, test_t))
Then look at each result until you find one that isn't what you expect
Since you know better than I do what you expect at each step, you might find the underlying issue quicker than I can by doing this :)
Update:
One "obvious" reason why it's not working is because you're not resetting k each time around the c loop.
If you look at the output before fixing, you will see that the "at K" messages only come out once, the first time through.
I've updated the code above to fix this, and I think it does something like you are expecting. I'm not sure why you are taking taking the int() of liste[k], but that is a separate issue.