Counting program for fibonacci sequence Python - python

I think what I am trying to do is display a select section from a defined list. Currently this is what I am working with:
#fibonacci sequence algorithm, user stops by either
#entering a maximum Fibonacci value not to exceed or
#a total count that the sequence of numbers must not
#exceed. Use a loop that allows User to repeat program
#as much as they wish, asking if they would like to
#repeat the program each time. Validate that User input
#is either a yes or a no and only allow User to continue
#once a correct response has been given.
import array
array.listOfFibSeq = ['0','1','1','2','3','5','8','13','21','34','55','89','144','...']
startingNumber = ''
endingNumber = ''
continueYes = ''
def getStartingNumber():
print('Please enter a valid starting number of the Fibonacci Sequence')
print(listOfFibSeq)
startingNumber = input()
def getEndingNumber():
print('Please enter a valid ending number the the Fibonacci Sequence')
print(listOfFibSeq)
endingNumber = input()
I'm unsure of how to go about this, but I believe I'm trying to display (for example) 3 through 89 in the Fibonacci sequence or do something like:
lsitOfFibSeq.remove(<3) and listOfFibSeq.remove(>89)
or should I try to display a range of the Fib Sequence with a for loop?

There is no reasonable way to precompute the fibonacci sequence before the user enters a range — you should do this dynamically.
A naive approach would be to have a function that computes the sequence for a given (a, b), all the way to end, discarding everything up to start.
I prefer the generator approach:
import itertools
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
# Print the first 10 values of the sequence
for i in itertools.islice(fib(), 0, 10):
print(i)
Or, in your case, something like:
start = input('Start index: ')
end = input('End index: ')
for i in itertools.islice(fib(), int(start), int(end)):
print(i)
if input('Continue [y/n]: ').rstrip() == 'n':
break

Related

WAP in python script to input a multidigit number and find each of the number's factorial

The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')

Python factorial that requires "while" loop

I am a python student that's new to python and I am required to write a program that calculates the factorial of an input number to find the possible ways to arrange letters in a Scrabble game with only the "while" loop construct.
For example: I request for an input number from a user through a line like this initially:
n = int(input("Enter an integer:"))
and afterwards i need to go about finding the entire factorial with a loop. How do I go about doing this? Below is my entire code and can someone tell me what's wrong with it? It just keeps printing a value of 20:
number_of_letters = int(input("Enter the numbers of letters you have in hand:"))
n = number_of_letters
def factorial(number_of_letters):
while number_of_letters > 1:
a = number_of_letters
n = n - 1
result = a * n
print('The number of combination for {}-letters words is {}'.format(number_of_letters, result)) # To display output
break
return result # Do not remove this line
I think the problem is that you are comparing number_of_letters > 1 while decreasing n and keeping number_of_letters without changes.
Also, i don't know what are you trying to archive with the break statement, and the return statement should be inside the function but outside the while

Square number sequence in Python

I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
When I run this code it infinitely prints "1" ... I'm guessing that the value of a does not increase by += so it's a=1 forever. How do I fix this?
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
You're setting the value of a back to 1 on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1 line.
As others have noted, your specific problem is resetting a each time you loop. A much more Pythonic approach to this is the for loop:
for a in range(1, n):
print(a ** 2)
This means you don't have to manually increment a or decide when to break or otherwise exit a while loop, and is generally less prone to mistakes like resetting a.
Also, note that raw_input returns a string, you need to make it into an int:
n = int(raw_input("Enter number: "))
an even better idea is to make a simple function
def do_square(x):
return x*x
then just run a list comprehension on it
n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]
this is a more pythonic way to do what you are trying to do
you really want to use functions to define functional blocks that are easy to digest and potentially can be reused
you can extend this concept and create a function to get input from the user and do some validation on it
def get_user_int():
#a function to make sure the user enters an integer > 0
while True:
try:
n = int(raw_input("Enter a number greater than zero:"))
except TypeError:
print "Error!! expecting a number!"
continue;
if n > 0:
return n
print "Error: Expecting a number greater than zero!"
and then you can build your input right into your list
squares = [do_square(i) for i in range(1,get_user_int()+1)]
and really do_square is such a simple function we could easily just do it in our loop
squares = [x*x for x in range(1,get_user_int())]
The first line in your loop sets's a to one on every iteration.
You assign a=1 inside the loop. That means it's overwriting the a+=1.
try this:
n = eval(raw_input("Enter number"))
a=1
while a < n:
print a*a
a += 1
The issue here is that the value of a gets overridden every time you enter in the loop
Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..
def powers(x):
n=1
while((n**2)<=x):
print(n**2, end =' ')
n +=1

how to generate a list based on index value

i am trying to generate a list consisting of 0's based off of user prompt. if they enter a one then the one index will be replaced with a one, if they enter a two the two index will be replaced with a one, etc. i am able to generate a random list of one's and zero's but i am having trouble with the input.
here is what i have so far:
import random
def askTheUser():
number = input("Do you want to roll again? Pick a number or numbers thru 0 and 5:")
myList = []
aList = [1,0]
for i in range(5):
myList.append(random.choice(aList))
if number == 1:
return myList[1] = 0
if number == 2:
return myList[2] = 0
return myList
print(askTheUser())
I think you are replacing by 0 not 1, also input is taking string not int so try to cast it
and list index is 0 based so the right code should be:
import random
def askTheUser():
number = input("Do you want to roll again? Pick a number or numbers thru 0 and 4:")
myList = []
aList = [1,0]
for i in range(5):
myList.append(random.choice(aList))
myList[int(number)] = 1
return myList
print(askTheUser())
I am not sure what exactly your program should do. I tried to follow description more than your code (expected input and output would be welcome).
Here is my piece:
from __future__ import print_function # make it work also in python 2.x
import random
def askTheUser():
# don't use magic numbers, use 'constant-like' variables
MAX = 5
# try to avoid too long lines if possible
msg = "Do you want to roll again? " +\
"Pick a number or numbers thru 0 and {}: ".format(MAX)
# you should use raw_input() for asking user, input() is very unsafe
number = raw_input(msg)
# initialize with random [0,1]
myList = [random.randint(0,1) for i in range(MAX)]
try:
# you need to convert string to int
i = int(number, 10)
# negative indexes can be valid ;o)
# let's not allow for that in this case, throwing error
if i < 0:
raise IndexError
myList[i] = 1
# you may expect ValueError if string was not valid integer
# or IndexError if it was beyond range (0, MAX)
except (IndexError, ValueError):
print ("That was wrong value:", number) # if you want, message user
pass
finally:
return myList
if __name__ == '__main__':
print(askTheUser())
If you want to accept multiple values at once, you should use split() on input and process them in loop.
Good luck.

How to map all the values in a range upto n, range(n) in Python

I'm trying to make my first Python calculator which can add given values given by user. The problem is that sometimes we may have several values to add i.e. a + b is not only the addition we have a + b + d + g + h + ... so I have defined a range up to n where n is the user input.
Now the problem is that if the user gives a value of 5 in the range, then how to map the each and every value in that range to enter the values to add?
The code:
def main():
print("how many no.s are we dealing with?");
n=int(input(""));
for i in range(n):
print("addition:");
Cutting things short, I just want a user to first type how many values would be adding and then the user has to type all those values to be typed for the calculator to add them.
It's like if the user has a range of 3 numbers [a + b + c] then the user would type 3 in the first prompt then he would type a, b, c values in each prompt to give out the total.
def main():
n=int(input("how many no.s are we dealing with?"))
result = 0
for i in range(n):
value = float(input('enter next number to add'))
result += value
print('the result is {0}'.format(result))
Notice the lack of ;
How this works is that the result is initialized to 0. Then every time the loop iterates the user is asked for a number. That number is then added to the result.
There is, however, an easier way:
sum_string = input('please enter a sum. for example: "1 + 2 + 10 ..."') #1
result = sum([float(i) for i in sum_string.split('+')]) #2
print('the result is {0}'.format(result)) #3
How this works is:
in line 1: you ask the user to enter a string and store it
in line 2: you do a whole lot... I'll examine it piece by piece:
sum_string.split('+') takes the string inputted by the user and turns it into a list. for example: 1+2+ 45'.split('+') => ['1','2',' 45']
continuing from the example above: [float(i) for i in ['1','2',' 45']] => [1,2,45]
this is called list comprehension. It is awesome and totally worth looking up
lastly sum([1,2,45]) => 48`
in line 3: we print out the result. I'm not really sure what you want to do with it
Note: this will not work with negative numbers as it stands but can be adapted to do so...

Categories

Resources