How can you sum these outputs in Python? - python

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1

You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.

You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))

I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

Related

The Sum of Consecutive Numbers

I have to write a program which asks the user to type in a limit. The program then calculates the sum of consecutive numbers (1 + 2 + 3 + ...) until the sum is at least equal to the limit set by the user.
In addition to the result it should also print out the calculation performed. I should do this with only a while loop, no lists or True conditionals.
limit = int(input("Limit:"))
base = 0
num = 0
calc = " "
while base < limit:
base += num
num += 1
calc += f" + {num}"
print(base)
print(f"The consecutive sum: {calc} = {base}")
So for example, if the input is 10, the output should be 10 and underneath that should be "The consecutive sum: 1 + 2 + 3 + 4 = 10." If the input is 18, the output should be 21 and underneath that should be "The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21."
Right now I can get it to print the final result (base) and have gotten it to print out the calculation, but it prints out one integer too many. If the input is 10, it prints out 1 + 2 + 3 + 4 + 5 when it should stop before the 5.
I would avoid the while loop and use range instead. You can derive the value of the last term with arithmetic.
If the last term is 𝑛, then the sum will be 𝑛(𝑛+1)/2, which must be less or equal to the input limit. Resolving this equation to 𝑛 given the limit, we get that the 𝑛 is ⌊√(1 + 8β‹…limit) βˆ’ 1) / 2βŒ‹
So then the program can be:
limit = int(input("Limit:"))
n = int(((1 + 8 * limit) ** 0.5 - 1) / 2)
formula = " + ".join(map(str, range(1, n + 1)))
total = n * (n + 1) // 2
print(f"The consecutive sum: {formula} = {total}")
One way that came to my mind is concatenating values for each iteration:
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
calculation = 'The consecutive sum: '
while base < limit:
calculation += f"{num} + "
base += num
num += 1
print(f"{calculation[:-3]} = {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
## 21
The other way is printing value on each iteration without new line in the end (but you have additional + sign in the end here):
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
print('The consecutive sum: ', end='')
while base < limit:
print(f"{num} + ", end='')
base += num
num += 1
print(f"= {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 + = 21
## 21
There's probably a more efficient way to write this but this was what came to mind...
sum = 0
long_output = []
for i in range(limit + 1):
sum += i
long_output.append(str(i))
print("The consecutive sum: {} = {}".format(' + '.join(long_output), sum))
Keep putting stuff in an list and then join them afterwards. i has to be casted to a str type since join is just for strings
NOTE: the output starts at 0 to account for limit being potentially 0 (I don't know what your constraints are, if any)
EDIT: made updates based on #Copperfield's recommendation
You are/were very close. Try rearranging the follow of execution in your while statements. I also find this assignment hard. Try moving you calc line as the first statement after your 'while'.
One other way is to add an if statement:
if base< num :
calc += f" + {num}"
Here is a example to print the calculation
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
msg = ""
while base < limit:
msg = msg + str(num) + "+"
base += num
num += 1
msg = msg[:-1] + "=" + str(limit)
print(msg)
if limit = 21 then the output would be
1+2+3+4+5+6=21

To find if a number is fibonacci or not

I am a student, new to python. I am trying to code a program that will tell if a user input number is fibonacci or not.
num=int(input("Enter the number you want to check\n"))
temp=1
k=0
a=0
summ=0
while summ<=num:
summ=temp+k
temp=summ
k=temp
if summ==num:
a=a+1
print("Yes. {} is a fibonnaci number".format(num))
break
if a==0:
print("No. {} is NOT a fibonacci number".format(num))
#The program is working for only numbers upto 2.
You don't need quite so many variables. A Fibonacci integer sequence can be generated with the single assignment
a, b = b, a + b
# Short for
# temp = a
# a = b
# b = temp + b
Repeated applications sets a to the numbers in the pattern in sequence. The choice of initial values for a and b determine which exact sequence you get. The Fibonacci numbers are generated when a = 0 and b = 1 are used.
a = 0
b = 1
a, b = 1, 0 + 1 # 0, 1
a, b = 1, 1 + 1 # 1, 2
a, b = 2, 1 + 2 # 2, 3
a, b = 3, 2 + 3 # 3, 5
# etc
(As another example, the Lucas numbers are generated if you start with a = 2 and b = 1.)
All you need to do is return True if n == a at each step, iterating until n > a. If n wasn't one of the a values generated by the loop, you'll return False.
n = int(input(...))
a = 0
b = 1
while a <= n:
if n == a:
return True
a, b = b, a + b
return False
I'd suggest something like this:
fib_terms = [0, 1] # first two fibonacci terms
user_input= int(input('Enter the number you want to check\n'))
# Add new fibonacci terms until the user_input is reached
while fib_terms[-1] <= user_input:
fib_terms.append(fib_terms[-1] + fib_terms[-2])
if user_input in fib_terms:
print(f'Yes. {user_input} is a fibonacci number.')
else:
print(f'No. {user_input} is NOT a fibonacci number.')
Check this:
def fibonacci_list(limit):
u_n_1 = 1
u_n_2 = 1
u_n = 1
out_list = [u_n]
while u_n <= limit:
out_list.append(u_n)
u_n = u_n_1 + u_n_2
u_n_2 = u_n_1
u_n_1 = u_n
return out_list
def is_fibonacci_number(n):
if n in fibonacci_list(n):
return True
return False
def main():
n = int(input('Enter a number:'))
if is_fibonacci_number(n):
print(str(n) + ' is a fibonacci number ')
else:
print(str(n) + ' is not a fibonacci number ')
if __name__ == '__main__':
main()
bool checkfibonacci(int n)
{
int a = 0;
int b = 1;
if (n == a || n == b) return true;
int c = a + b;
while(c <= n)
{
if(c == n) return true;
a = b;
b = c;
c = a + b;
}
return false;
}
Something like this will do it.
welcome to the python community.
In Your code temp means the previous number and k means the previous number of temp. The problem is that you change the temp before you assign the next value to k. To solve that you just have to sawp the lines 8 and 9. In the new order you first assign the value of temp to k then summ to temp. That's it!
I suggest you to do it by a list in this way:
fib[i] = fib[i-1] + fib[i-2]
It will improve the clarity of your code.

Factorization: What went wrong with d? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]

How to generate a series using While loop

n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
sum = sum +1
i = i+1
print("The sum is" , sum)
I tried the above code but didn't got my answer.
The question is to generate a series that is: 1,4,7,10,13,16,19,22 using while loop.
To generate series you need to do two things:
Put the print inside the loop to output accumulator variable's value every iteration
Add 3 to sum every iteration and not 1 since it's the difference between series members
n = int(input("Enter n: ")) # n=8 should work
sum = 1
i = 1
while i <= n:
print(str(sum)+",")
sum = sum +3
i = i+1
I see two errors:
You should add i to sum,not 1 (this assumes you are interested in the sum as implied by the code)
You should be incrementing i by 3 not by 1
If I understand you correctly, you want this:
i = 1
while i <= 22:
print(i)
i += 3
n = int(input("Enter n: "))
count = 0
i = 1
sum = 0
while count <= n-1:
print(i)
sum += i
i += 3
count += 1
print("Sum is", sum)
You are going to want to increase the count by three every time with i += 3.
def createList():
user_input = input()
i = 1
list_of_vals = []
while i < int(user_input): # The max value:
list_of_vals.append(i)
i += 3
return list_of_vals
print (createList())
I think you want something like this:
n = int(input("Enter n: "))
series_sum = 0
i = 1
series = []
add = 3
while i <= n:
series.append(i)
series_sum = series_sum + i
i = i + add
print("series: ", series)
print("The sum is" , series_sum)
This would get you a series (and sum of elements) with the last element less than n, starting from i = 1 and increment add = 3

Python: Reversing print order from a while loop

I am writing some code takes values, the values number and N as input and prints, the first N lines of a multiplication table as below:
3 * 4 = 12
2 * 4 = 8
1 * 4 = 4
What I'd like to do is reverse said output to look like this:
1 * 4 = 4
2 * 4 = 8
3 * 4 = 12
The code is here below. I've thought about using slicing such as [:-1] but I'm not sure how to implement it. Assistance would be appreciated. Thanks.
number = input("Enter the number for 'number ': ")
N = input("Enter the number for 'N': ")
if number .isdigit() and N.isdigit():
number = int(number )
N = int(N)
while int(N) > 0:
print('{} * {} = {}'.format(N,number ,N*number))
N = N - 1
else:
print ('Invalid input')
I would instead recommend using a for loop with the range method as such:
for i in range(1, N+1):
print('{} * {} = {}'.format(i,number ,i*number)
I think, you can let the program count upwards.
N = int(N)
i = 1
while int(N) >= i:
print('{} * {} = {}'.format(N,number ,N*number)) # TODO: adjust formula
i = i + 1
Reversing a list is [::-1] (you missed ':') and you are parsing twice the same number N, but in this case you can do
counter = 0
while counter != N:
print('{} * {} = {}'.format(N,number ,N*number))
counter = counter + 1
You could change your while loop like so:
int i = 0
while i < N:
print('{} * {} = {}'.format(i,number ,i*number))
i = i + 1
If you absolutely have to do it using while loops, perhaps something like the following will work.
m = 1
while m <= N:
#Do stuff with m
m += 1
Although I much suggest using a for loop instead.

Categories