Python == Function to Count All Integers Below Defined Variable, Inclusive [duplicate] - python

This question already has answers here:
Python Memory Error while iterating to a big range
(3 answers)
Closed 6 years ago.
Sorry I have to ask such a simple question, but I've been trying to do this for a while with no luck, despite searching around.
I'm trying to define a function that will get user input for X, and then add every integer from 0 to X, and display the output.
For example, if the user inputs 5, the result should be the sum of 1 + 2 + 3 + 4 + 5.
I can't figure out how to prompt the user for the variable, and then pass this variable into the argument of the function. Thanks for your help.
def InclusiveRange(end):
end = int(input("Enter Variable: ")
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))

Just delete argument "end" from function header and use your function.
InclusiveRange()
or define code in other way:
def InclusiveRange(end):
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
end = int(input("Enter Variable: ")
InclusiveRange(end)

Here's an itertools version:
>>> from itertools import count, islice
>>> def sum_to_n(n):
... return sum(islice(count(), 0, n + 1))
>>>
>>> sum_to_n(int(input('input integer: ')))
input integer: 5
15

You should take the user input out of the function, and instead call the function once you have received the user input.
You also need to store the sum in a separate variable to start, otherwise you're only adding 1 each iteration. (I renamed it to index in this example as it reflects it's purpose more).
def InclusiveRange(end):
index = 0
sum = 0
while index <= end:
sum += start
index += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, sum))
end = int(input("Enter Variable: "))
InclusiveRange(end)
Demo

Instead of using a loop, use a range object, which you can easily send to sum(). Also, you're never actually using the passed end variable, immediately throwing it away and binding end to a new value. Pass it in from outside the function.
def inclusive_range(end):
num = sum(range(end+1))
print("The total of the numbers, from 0 to {}, is: {}".format(end, num))
inclusive_range(int(input("Enter Variable: ")))

You can also use a math formula to calculate the sum of all natural numbers from 1 to N.
def InclusiveRange(end):
''' Returns the sum of all natural numbers from 1 to end. '''
assert end >= 1
return end * (end + 1) / 2
end = int(input("Enter N: "))
print(InclusiveRange(end))

Related

using the collatz sequence in dictionaries

I'm pretty new to python and currently, I'm trying to learn dictionaries. I'm trying to write a program that asks the user for a number, and then outputs the number less than or equal to the one the user entered with the longest Collatz sequence.
This is what I currently have right now, but I don't know why it won't work.
def collatz(number):
segLength = {}
for i in range(1, number + 1):
current = 1
count = 0
while current != 1:
if current % 2 == 0:
current = number / 2
elif current % 2 != 0:
current = (3 * number + 1)
count += 1
segLength[i] = count
value = list(segLength.values())
key = list(segLength.keys())
x = max(value)
index = value.index(x)
output = key[index]
return output
result = collatz(number)
print = result
Each iteration of your for loop, you set current = 1, so current != 1 will always be False and you'll skip the while.
It looks like you want to calculate the collatz sequence for each number so I'm guessing you want to instead set current = i.
Then, for each iteration of your for loop, current will have the number you want to reduce to 1 and count the number of steps it takes. To make this work, you'll want to change:
current = number / 2
(and the corresponding 3n+1 line in the elif) to
current = current / 2
because number is always going to be the number you passed into the function at the start, not the number you're trying to run a collatz sequence on this iteration
It looks like it should work otherwise!
EDIT: you should also call print rather than assign to it as Barmar said.

Generating a palindrome number taken from input

I'm writing a program that takes a number from input and generates it's palindrome number. My program only prints the first half not the second. I tried reverse, didnt work.I have incluede those lines as comment.
My Code:
def show_palindrome(maximum):
maximum = int(input("Enter Number : "))
for number in range(1, maximum + 1):
temporary = number
reverse = 0
while (temporary > 0):
reminder = temporary % 10
reverse = (reverse * 10) + reminder
temporary = temporary //10
if(number == reverse):
#number2 = number[::-1]
#print(number,number2, end = '')
print(number, end = '')
show_palindrome(3)
My output:
123
The output I need:
12321
I believe you're looking for something like this:
def show_palindrome(maximum = None):
if not maximum:
maximum = input("Enter Number : ")
output = str(maximum)
for number in range(1, int(maximum)):
output = str(int(maximum) - number) + str(output) + str(int(maximum) - number)
return output
print(show_palindrome(3))
this returns 12321 for instance
A couple of things I would do differently in your function:
If you're going to require the input in the def (The way you make it optional is to set it equal to something when you declare it like I have it set to None (maximum=None), then you don't need the input() statement.
Since you already know how long you want it to be ( you require it declared when you initialize the function, it's just 2*maximum - 1) there's really no need to use a while loop.
Other than that good job! Keep it up!
You can try something simpler like this:
def show_palindrome():
num = input("Enter Number : ")
print(num + num[:-1][::-1])
show_palindrome()
Input:
123
12
1
Output:
12321
121
1
Apart from the string slice method (as used by #PApostol), you could also use the reversed method :
def show_palindrome():
value = input("Enter Number : ")
print(value[:-1] + "".join(reversed(value)))
Input:
123
Output:
12321
def palindrome(maximum):
number = ''.join([str(num) for num in range(1, maximum + 1)])
return int(number + number[-2::-1])
print(palindrome(3))
Output:
12321
Your code seems over complicated, and I don't even know what to fix in it. What I can tell is that passing a parameter maximum to overwrite it just after with maximum = int(input("Enter Number : ")) is useless, don't pass the parameter.
So let's back to easy things
Build palindrome using strings method : slicing backwards from index -2, and reverse it with -1 increment
def show_palindrome():
value = input("Enter Number : ")
print(value + value[-2::-1])
Build palindrome using math operations : save the remainder, except the first one
def show_palindrome():
value = input("Enter Number : ")
result = value
value = int(value) // 10 # remove last char which would be redundant
while value > 0:
result += str(value % 10)
value = value // 10
print(result)
show_palindrome()

Fibonacci sequence with numbers in 1 line and without using list or array [duplicate]

This question already has answers here:
How do I print a fibonacci sequence to the nth number in Python?
(8 answers)
Closed 2 years ago.
I'm very new to python and programming in general. This is the first year we have programming classes, so I'd say I started about a month ago.
We got our first assignment last week and I've managed to make most of the tasks, apart from the following one:
Generate n numbers from the Fibonacci sequence, where n is entered by the user.
Write these numbers to the screen.
Print the numbers on 1 single line.
Tip: print (value, end = '')
Do not use list or array.
This is the last question and this one is significantly more difficult than the others. I tried some things but non came close to doing what is asked. I genuinely have no clue how I'd even have to start.
In pseudocode:
First you need to check, print and save the results of fibonacci(0) and fibonacci(1)
Then make a loop to calculate the next fibonacci value using the last two calculated and print it.
Update the variables for the last two calculated.
Iterate steps 2 and 3 for each N>2
Thinking in python3:
# Print Fibonacci(0)
if n>=0:
print (1, end =', ')
f2 = 1
# Print Fibonacci(1)
if n>0:
print (1, end =', ')
f1=1
# Print Fibonacci(n) ; n>1
if n>1:
for i in range (2, n+1):
result = f1+f2
print(result, end=', ')
# updating last two variables
f2 = f1
f1 = result
Although not mentioned, you may want to 'memorize' previous Fibonacci numbers so you can generate the sequence faster.
def fibonacci(n, _cache={}):
if n in _cache: # Check to see if the number has been done
return _cache[n] # Return the pre-done number
elif n > 1:
return _cache.setdefault(n, fibonacci(n-1) + fibonacci(n-2)) # Call this function recursively to generate the previous Fibonacci numbers
return n
n = int(input("n = "))
for i in range(n):
print(fibonacci(i), end=', ')
You need to think about loops, how to iterate a set number of times, and use the print statement given to you in the "tip".
In pseudo code:
next_in_sequence = 1
loop_count = 1
while loop_counter <= number_entered:
next_in_sequence = caclulate_next_fibonacci(next_in_sequence)
print (next_in_sequence, end = '')
loop_counter = loop_counter + 1
Have a go at writing this in python, you'll have to write the caclulate_next_fibonacci function to work out the next number in the sequence. If you have any problems edit your question to show your code and ask for more help
To calculate the next Fibonacci number simply add together the two previous values. You can do this in a for loop using variables declared outside the loop to hold the previous two values.
Use this statement within your loop
print (value, end = '')
This will print the sequence all on one line with each value separated by a space.
n = int(input())
fib0 = 0
fib1 = 1
for x in range(0, n):
nextFib = fib0 + fib1
fib0 = fib1
fib1 = nextFib
print(fib0 , end = ' ')

How can I display all numbers in range 0-N that are "super numbers"

The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
number = int(input ("enter integer: "))
def factorial (n):
result = 1
i = n * (n-1)
while n >= 1:
result = result * n
n = n-1
return result
#print(factorial(number))
def breakdown (n):
breakdown_num = 0
remainder = 0
if n < 10:
breakdown_num += factorial(n)
return breakdown_num
else:
while n > 10:
digit = n % 10
remainder = n // 10
breakdown_num += factorial(digit)
#print (str(digit))
#print(str(breakdown_num))
n = remainder
if n < 10 :
#print (str(remainder))
breakdown_num += factorial(remainder)
#print (str(breakdown_num))
return breakdown_num
#print(breakdown(number))
if (breakdown(number)) == number:
print(str(number)+ " is super")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n
N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585

Python: display the number of one's in any user given integer number

How do I display the number of one's in any given integer number?
I am very new to python so keep this in mind.
I need the user to input a whole number.
Then I want it to spit out how many one's are in the number they input.
i am using python 3.3.4
How would I be able to do this with this following code?
num = int(input ("Input a number containing more than 2 digits"))
count = 0
for i in range (0):
if num(i) == "1":
count = count + 1
print (count)
I don't know what i'm doing wrong
it gives me 'int' object is not callable error
Something like this:
Int is not iterable so you may need to convert into string:
>>> num = 1231112
>>> str(num).count('1')
4
>>>
str(num).count('1') works just fine, but if you're just learning python and want to code your own program to do it, I'd use something like this, but you're on the right track with the code you supplied:
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print(count)
Just to help you, here is a function that will print out each digit right to left.
def count_ones(num):
while num:
print(num % 10) # last digit
num //= 10 # get rid of last digit
num = 1112111
answer = str(num).count("1")
num = int(input (" Input a number to have the number of ones be counted "))
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print (' The number of ones you have is ' + str(count))
So i took the user input and added it to the correct answer since when i tried the answer from crclayton it didn't work. So this works for me.

Categories