Why does this Python code not work? - python

Please help, I cannot figure out why this code does not work. I think the first loop runs forever but I don't know why!
def NTN():
list1 = []
count = 0
number = 0
Start = input('Type Start Number')
while number != Start:
count = count + 1
number = number + count
Stop = input('Type Stop Number')
while number != Stop:
count = count + 1
number = number + count
if number != Stop:
(list1).append(number)
return (list1)
print(NTN())

You are increasing number by increasing amounts in every iteration. Here's an idea of how it is increasing. Assume Start = 4
After 1 loop, count = 1 and number = 1, increase of 1
After 2 loops, count = 2 and number = 3, increase of 2
After 3 loops, count = 3 and number = 6, increase of 3
Since number is never really equal to 4, the loop never ends. What you need probably is while number <= Start. That would terminate the loop after 3 iterations when number is past 4.

change "number != Start" and "number != Stop" to "number < Start" and "number < Stop" in all places, and it should work.
What went wrong: if Start is 2, then in the first iteration of the while loop, count becomes 0+1=1 and number becomes 0+1=1; in the second iteration, count becomes 1+1=2 and number becomes 1+2=3, which bypasses 2. Since your while loop only ends when number is equal to Start, it never ends.

A couple of side-points:
By convention Python variable and function names are lower-case.
input() returns a string; if you want a number you have to convert it ie with int() or float(). (Note: if you are using Python 2.x input() calls eval() which is really awful design - you should be using int(raw_input()) instead.)
so,
# This code assumes Python 3.x
from math import ceil, sqrt
def get_int(prompt):
"""
Prompt until an integer value is entered
"""
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter an integer!")
def tri(n):
"""
Return triangular number n,
ie the sum of (1 + 2 + ... + n)
"""
# using Gaussian sum
return n * (n + 1) // 2
def reverse_tri(t):
"""
For positive integer t,
return the least positive integer n
such that t <= tri(n)
"""
# derived by quadratic formula from
# n * (n + 1) // 2 >= t
return int(ceil(((sqrt(8 * t + 1) - 1) / 2)))
def ntn(start, stop):
"""
Return a list of triangular numbers
such that start <= tri < stop
"""
a = reverse_tri(start)
b = reverse_tri(stop)
return [tri(n) for n in range(a, b)]
def main():
start = get_int('Enter a start number: ')
stop = get_int('Enter a stop number: ')
lst = ntn(start, stop + 1) # include stop number in output
print(lst)
if __name__ == "__main__":
main()

Related

Factors of a number using Python recursive function

I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)

Creating a recursive geometric sequence function python

def geo():
start = int(input()) # starting number
multiplier = int(input()) # the multiplier
length = int(input()) # how long the list should be
for i in range(length):
x = start * multiplier ** i
print(x, "", end = "")
print()
I need to create a recursive geometric function based off user input. I know how to approach it non-recursively but how do I approach it recursively? Thanks in advance.
i.e: if the user inputs
start = 1
multiplier = 2
length = 5
Output: 1, 2, 4, 8, 16
Edit: thanks for all the examples guys, I understand how recursion a lot better now.
Remove the for loop.
Instead of it call the function recursively with a decrement in the argument.
Create a function with an integer as parameter and call it every time until a condition is met.
def geo(start, multiplier, length, i=0):
if length <= 0:
exit() #or use a return statement
x = start * multiplier ** i
print(x, "", end = "")
print()
geo(start, multiplier, length-1, i+1)
start = int(input())
multiplier = int(input())
length = int(input())
i=0
geo(start, multiplier, length, i)
Assuming you have a loop that you want to turn into a recursive function:
for i in range(length):
x = start * multiplier ** i
what you need to do is:
have a stop condition (i < length)
if stop condition is not met -> call again with the next value
do this before the function, because you'll need this value
length = int(input()) # how long the list should be
start = int(input()) # starting number
multiplier = int(input()) # the multiplier
def recursive_geo(i):
# stop condition
if i == length:
return 1 # since the value will be multiplied by the previous values, you don't want to use 0 or any other value
else:
print(x, "", end = "")
print()
return start * multiplier ** i * recursive_geo(i+1)
With any recursive function you need a base case and a general (recursion) case.
Let's start with your current code to get the inputs, but instead of calculating the value immediately we'll call a recursive function.
def geo():
start = int(input()) # starting number
multiplier = int(input()) # the multiplier
length = int(input()) # how long the list should be
result = geo_rec(start, multiplier, length)
print(result)
def geo_rec(start, multiplier, length):
print(start) # As per your current program
# Base case check
if length = 0:
return start
# Recursive case
else:
start = start * multiplier
length = length - 1
geo_rec(start, multiplier, length)
Now consider, if length is 0 what will we get? We will just get start - that's good. If length = 1, we'll recurse one level, and then return start (which by this point will be our original start * multiplier) - also good.
Notice with each run of the recursive case we work our way progressively to the base case?

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Recursion function for counting the number of digits in a number?

So I know that this is something simple that can be done without a recursion function but I need to know the backside to this as I can't seem to figure out how to write this using recursion. im using this so far
n = int(raw_input("What is n? "))
def digit(n):
if n< 10:
return 1
else:
new = n/10
print 1 + digit(new/10)
return 1 + digit(new/10)
digit(n)
Now if I type in a number such as 33 then it outputs 2 but if I do a longer number then it doesn't print it properly and I was unsure as to what exactly it wrong with it.
The problem is,
new = n/10
return 1 + digit(new/10)
You are already dividing the number by 10, in new = n / 10, which reduces the last digit and you are again dividing it by 10 before calling digit. So, you are ignoring 1 digit in every recursive call.
Instead, you can simply do
return 1 + digit(n / 10)
or
new = n / 10
return 1 + digit(new)
#!/usr/bin/python
n = int(raw_input("What is n? "))
def digit(n):
if n < 10:
return 1
else:
return 1 + digit(n/10)
print digit(n)
You can do like this too.
def counter(number):
if(number == 0):
return 0
return counter(int(number/10)) + 1
number = 1998
print(counter(number)) // it will print 4

Solving Project Euler #2 in Python

I am attempting to do Project Euler problem #2. Which is:
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
However the terminal window hangs when I use the following code with 4000000. Smaller numbers run ok. Is there something about this code that is really inefficient, hence the lagginess?
n = int(raw_input("Enter the start number: "))
def fib_generator():
a, b = 0, 1
yield 0
while True:
a, b = b, a + b
yield a
def even_sum(fib_seq):
seq = []
seq = [next(fib_seq) for number in range(n)]
seq = [number for number in seq if number % 2 == 0]
return sum(seq)
def start():
fib = fib_generator()
even_sum = even_sum(fib)
print even_sum
start()
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose values are not more than 4,000,000.
Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ~ n / 5) and that will take an immense amount of time.
Fix the bug, and you'll be okay.
You just need to add logic to stop when the next fibonacci number exceeds 4000000.
Also, I spy a potential problem with this line:
def start():
fib = fib_generator()
even_sum = even_sum(fib) #<--- right here
print even_sum
It isn't good to have a variable name the same as the function name.
Yes, there is something inefficient in your code, you load a very long list into memory twice, with your two seq = ... statements. Why not try one generator expression rather than two list comprehensions? Also, you could alter your Fibonacci generator to stop at a certain number:
def fib_generator(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
def even_sum(fib_seq):
seq = (number for number in fib_seq if not number % 2)
return sum(seq)
def start():
n = int(raw_input('Enter max constraint: '))
fib_seq = fib_generator(n)
even_sum1 = even_sum(fib_seq)
print even_sum1
start()
This ran pretty fast for me
lst = []
num1 = 1
num2 = 2
sum = 0
jump = 0
next = 0
while next<4000000:
next = num1 + num2
if next<4000000:
if jump ==0:
num1 = next
jump = 1
else:
num2 = next
jump = 0
if next%2 == 0:
lst.append(next)
for item in lst:
sum+=item
print ''
print "Sum: ",
print sum

Categories

Resources