Creating a Fibonacci sequence function in Python 3 - python-3.x

I am trying to create a function that prints a list of the first 4 numbers in the Fibonacci sequence, the first 10 numbers in the Fibonacci sequence, and then "the first -4" numbers in the Fibonacci sequence. The "-4" numbers in the Fibonacci sequence should return an empty list because there is no "-4" numbers in the sequence. I need the function to print the 3 lists as an end result in the main() function. Here is my code so far, I'm new to functions so any help would be appreciated.
fn = []
def F(n):
i = 0
a = 0
b = 1
for i in range(0,n):
temp = a
a = b
b = temp + b
fn.append(b)
i = i + 1
return fn
main():
print F(4)
print F(10)
print F(-4)

Your function for generating Fibonacci numbers is correct except the global variable fn = [] should be declared within the function body. Also, as suggested in the comment by #alfasin, a, b = b, a + b is more Pythonic.
def fib_list(n):
a = 0; b = 1; fib_list = []
if n <= 0:
return
for i in range(0, n):
a, b = b, a + b
fib_list.append(b)
return fib_list
The other problems I could find with your code:
* print is not a statement in Python 3.x.x, it is a function instead, i.e. print F(4) should be print(F(4))
* main(): should be changed to if __name__ == '__main__':

Related

I want to return the sum of all indexes in n via recursion. How do I do this?

def final_sum(n):
n = str(n)
if int(n) == 0:
return 0
else:
x = int(n[0])
return x + int(final_sum(n[1:]))
print(final_sum(123))
For example, if my n is 123, I should be getting 6. But I am having an error in this code. Can anyone help? I have to use recursive function. So tell me what's wrong with the code.
in return x + int(final_sum(n[1:])), n[1:] is str type
in the beginning of the function, with n = str(n), you assume the input is an int
Besides, you did not consider the case that n[1:] can be empty in return x + int(final_sum(n[1:])).
Here is an anwser based on your code
def final_sum(n):
if n == 0:
return 0
n = str(n)
x = int(n[0])
if len(n)==1:
return x
else:
return x + final_sum(int(n[1:]))
Here is another version using % operation
def final_sum(n):
if n < 10:
return n
return n % 10 + final_sum(n // 10)
First of all, at the beggining I would do this instead of casting back and forth:
def final_sum(n):
if n<10:
return n
You see, the problem is, in the last recursive iteration, you are passing this to the function:
final_sum("")
When you should be passing an int. I think this is happening because your last cast is backwards and you never check how many digits the number has. So the code should look like this:
def final_sum(n):
if n<10:
return n
n = str(n)
x = int(n[0])
return x + final_sum(int(n[1:]))
print(final_sum(123))

Code showing no output whatsoever (python)

Trying to make a little Fibonacci game where the user guesses a set amount of steps. I'm trying to make a functioning Fibonacci generator to make the lists to refer to later, but nothing is showing up. I'm sure I'm returning the values. What am I doing wrong?
""" Core Fibonacci Code
a = int(input("How many steps of fibonacci would you like? "))
def fibonacci(counter):
a = 0
b = 1
count = 2
print (a)
print (b)
fib = [0, 1]
while (counter > count):
c = a + b
print (c)
a = b
b = c
count += 1
fibonacci(a)
"""
def fibonacci(counter):
a = 0
b = 1
count = 2
print (a)
print (b)
fib_list.append = a
fib_list.append = b
while (counter > count):
c = a + b
fib_list.append = c
a = b
b = c
count += 1
def homescreen():
print = ("Which gamemode would you like to play?")
print = ("EASY - 10 Steps")
print = ("MEDIUM - 25 Steps")
print = ("HARD - 50 Steps")
request = input("")
if request is "Easy" or "easy":
z = 10
elif request is "Medium" or "medium":
z = 25
elif request is "Hard" or "hard":
z = 50
return z
homescreen()
fibonacci(z)
print (fib_list)
Use print("Which gamemode would you like to play?") and not print=.
You use such format when your returning something from the called function.
eg:
def foo():
#Something
return y
x=foo()
Note :
Use the function append(), dont use lib_list.append=a.
Also declare lib_list outside the function fibonacci() as you're mentioning it in the function call outside of the function.

always got the same output with random.choice in a function

I tried using for-loop to exec my function but its always the same result.
import random
def main(arr):
result = random.choice(arr)
...some code...
return len(result)
for i in range(100):
main(arr)
I could only get diff result from stop/run the terminal. Anyone know why?
my question is the same as this one. random.choice always same
import random
results = []
with open('kargerMinCut.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split('\t'))
def contract(arr):
while len(arr) > 2:
# Generate random number in list of lists
# ranList = random.choice(arr)
ranList = arr[np.random.choice(len(arr))]
ranNum = random.choice(ranList[1:])
# retrieve the index of the random number
listIndex = arr.index(ranList)
for i in range(0, len(arr)):
if arr[i][0] == ranNum:
targetList = i
break
target = ranList[0]
for i in range(0, len(arr)):
if i == listIndex:
arr[i].pop(0)
arr[i] = [x for x in arr[i] if x != ranNum]
elif i == targetList:
arr[i] = [x for x in arr[i] if x != target]
else:
for index, item in enumerate(arr[i]):
if item == target:
arr[i][index] = ranNum
arr[targetList] += arr[listIndex]
del arr[listIndex]
return len(arr[0])-1
the arr would be like this
array = [[1,2,3,4],[2,1,3,4],[3,1,2,4],[4,1,2,3]]
I don't know what you do inside your function but I've got the normal result. And in the question what you linked to the person just used seed. This is kinda pseudorandom that gives you all the time the same random output. Here is the link to deep your knowledge about pseudorandom
import random
arr = [1,2,3,4,5]
def main(arr):
result = random.choice(arr)
print(result)
for i in range(100):
main(arr)
The result is as it has to be:
1
3
5
3
4
3
1
4
4
3
2

Trouble with variables (Python)

I'm a newbie with programming and I'm in trouble with this code:
def supercalcx(a, b):
n = a
while a <= b:
n = n * a
a = a + 1
print(n)
The IDE give me the error: "TypeError: can't multiply sequence by non-int of type 'str'", but I'm sure the inputs are ints or floats, can anyone explain me the problem. Thanks !
This function works:
>>> def supercalcx(a, b):
... n = a
... while a <= b:
... n = n * a
... a = a + 1
... print(n)
...
>>> supercalcx(2, 4)
48
Your function does not convert between data types. A very crude method of this is to do the following below:
def supercalcx(a,b):
n = int(a)
a = int(a)
b = int(b)
while a <= b:
n = n * a
a = a + 1
print(n)
A couple of suggestions to improve your code:
A function should rarely have the print() function inside of it; instead, use the return keyword. You can change a = a + 1 to a += 1 and n = n * a to n *= a. You can also introduce try and except which will attempt to perform whatever is tabbed under try and if something throws an error specified by the except block, it will then perform whatever is tabbed under except. A somewhat improved version is below:
def supercalcx(a, b):
try:
n = int(a)
a = int(a)
b = int(b)
except ValueError:
return "Unable to convert to integers!"
while a <= b:
n *= a
a += 1
return n
print(supercalcx("1", 2))
print(supercalcx(1, 2))

Counting substrings in string

Lets assume that i have 2 strings
M = "sses"
N = "assesses"
I have to count how many times string M is present into string N
I am not allowed to use any import or methods just loops and range() if needed.
M = "sses"
N = "assesses"
counter = 0
if M in N:
counter +=1
print(counter)
This isn't good enough i need loop to go trough N and count all M present
in this case it is 2.
def count(M, N):
i = 0
count = 0
while True:
try:
i = N.index(M, i)+1
count += 1
except ValueError:
break
return count
Or a one-liner without str.index:
def count(M, N):
return sum(N[i:i+len(M)]==M for i in range(len(N)-len(M)+1))
The same without using the sum function:
def count(M, N):
count = 0
for i in range(len(N)-len(M)+1):
if N[i:i+len(M)] == M:
count += 1
return count

Resources