What is wrong with this Python code for finding an Armstrong number? - python-3.6

I'm trying to write a Python program that will return an Armstrong number and the resulting outputs do not meet my expectations. An Armstrong number in a given number base is a number that is the sum of its own digits each raised to the power of the number of digits.
for i in range(0,len(lst)):
lst[i] = int(lst[i])
sum2= 0
for i in range(0,len(lst)):
sum1 = lst[i]*lst[i]*lst[i]
sum2 += sum1
if sum2 == n :
print("Armstrong number")
else:
print("Not an Armstrong number")
Why is this code returning incorrect results?

You need to cast n as answered above!
Also Armstrong number is not just power of 3
The power is equal to number of digits present in the number.
For Eg :
153 has 3 digits 1 5 and 3
so 1^3 + 5^3 + 3^3 = 153
But if number is 4 digit Number then :
Input : 1634
Output : 1634 is an Armstrong Number
1^4 + 6^4 + 3^4 + 4^4 = 1634
and so on!
So basically the power is no. of digits present in the given no.
Here is my simple piece of code for it :
def Armstrong(num):
exp = len(num)
res = 0
for i in num:
res += pow(int(i),exp)
if res == int(num):
print(num + " is an Armstrong Number")
else:
print(num + " is not an Armstrong Number")
num=input("Enter a number : ")
Armstrong(num)

You are very, very close. The only problem is that n is a string, not an int, so when you compare it to sum2 it will never be equivalent. Cast n to an int and problem solved:
if sum2 == int(n):
If you want to see a more streamlined way to get the same result, here is an example:
value_string = input("Enter an integer value: ")
starting_value = int(value_string)
digits = [int(char) for char in value_string]
cubed_sum = sum([
one_digit ** 3
for one_digit in digits
])
if cubed_sum == starting_value:
print(f"{starting_value} is an Armstrong number.")
else:
print(f"{starting_value} is not an Armstrong number.")

Related

Function that will return the biggest number of consecutive 0's

For a homework problem, in python we are asked to define in a recursive way a function that will return the biggest number of consecutive 0's in binary for any the number n. We need to use "&" and ">>".
For example, the function should return 2 for n = 44 because its binary representation is 101100.
I do not know where to go from here. Any help would be appreciated!
def max_consecutive_zero_iterative(n):
res = 0
streak = 0
while n > 0:
if n & 1:
streak = 0
else:
streak += 1
n = n >> 1
res = max(res, streak)
return res
def max_consecutive_zero_recursive(n):
if n == 0: # end of recursion
return 0
value = max_consecutive_zero_recursive(n >> 1) # call to recursive
current_streak = value & 0xff # current streak is stored in the lowest 8 bits
longest_streak = value >> 8 # longest streak is stored in the upper bits
if n & 1: # if we have a bit set
return max(longest_streak, current_streak) << 8 # we just return the max value between current_streak and longest_streak, stored in upper bits
# else if the bit is not set
current_streak += 1 # we increase our current streak by 1
# and return the max between the longest_streak and current_streak in the upper bits...
return max(longest_streak, current_streak) << 8 | current_streak
# ... but this time we keep information (we don't reset) about the current_streak stored in the lowest 8 bits.
def main():
print(max_consecutive_zero_recursive(0b1000101111000110000000100110) >> 8)
if __name__ == "__main__":
main()

Recursive Algorithm to add consecutive numbers

I have the following algorithm that adds t consecutive numbers starting at s.
Addup (s,t)
Make result = s
For i from s to t-1
Result = Result + s + i
Return Result
So Addup (3,3) = 3+4+5 = 12 & Addup (4,5) = 4+5+6+7+8
How can this be made recursive?
Q
In Python, for example:
def Addup(s,t):
if t == 1:
return s
else:
return s + Addup(s+1, t-1)

Generating random float points in Julia

I'm trying solve the question of "Can x * (1/x) ever not be 1 when x is a random floating point number between [1,2]" and I am trying to generate random floating numbers in Julia to test the hypotheses. I've tried doing
BigFloat(rand(1,2)), as well as Float64(1,2)
to no avail. Any help is appreciated
The answers is yes
for i=1:100
x = rand() + 1.0;
xi = 1.0/x
y = x * xi
if y != 1.0
println("case ", i, " x*(1/x) != 1 for x=", x, " diff= ", y - 1.0)
end
end
case 18 x*(1/x) != 1 for x=1.3193289816663771 diff= -1.1102230246251565e-16
case 26 x*(1/x) != 1 for x=1.9692333690500858 diff= -1.1102230246251565e-16
case 42 x*(1/x) != 1 for x=1.8927527081187694 diff= -1.1102230246251565e-16
...
Aware this is due to the limited precision of floats (doubles).
This is not true in a mathematical sense.

Python: a type error

So here is my situation. Ive been trying to make a advanced calculator in python 3.4, one where you can just type something like this. '1 + 1', and it would then give you the answer of '2'. Now i will explain how my calculator is supposed to work. So you start by entering a maths equation, then it counts the words you entered based on the spaces. It does this so it knows how long some future loops need to be. Then it splits up everything that you entered. It splits it up into str's and int's but its all still in the same variable and it's all still in order. The thing i'm having trouble with is when it is meant to actually do the calculations.
here is all of my code-
# This is the part were they enter the maths equation
print("-------------------------")
print("Enter the maths equation")
user_input = input("Equation: ")
# This is were it counts all of the words
data_count = user_input.split(" ")
count = data_count.__len__()
# Here is were is splits it into str's and int's
n1 = 0
data = []
if n1 <= count:
for x in user_input.split():
try:
data.append(int(x))
except ValueError:
data.append(x)
n1 += 1
# And this is were it actually calculates everything
number1 = 0
number2 = 0
n1 = 0
x = 0
answer = 0
while n1 <= count:
#The code below checks if it is a number
if data[n1] < 0 or data[n1] > 0:
if x == 0:
number1 = data[n1]
elif x == 1:
number2 = data[n1]
elif data[n1] is "+":
if x == 0:
answer += number1
elif x == 1:
answer += number2
n1 += 1
x += 1
if x > 1:
x = 0
print("Answer =", answer)
but during the calculation it messes up and gives me and error
error-
if data[n1] < 0 or data[n1] > 0:
TypeError: unorderable types: str() < int()
can anyone see what i am doing wrong here?
Thanks
When you are comparing a string and an integer, this problem comes.
Python doesn't guess, it throws an error.
To fix this, simply call int() to convert your string to an integer:
int(input(...))
So, corrected statement should be:
if int(data[n1]) < 0 or int(data[n1]) > 0:

Python Programming While Loop

Hi I'm new to python and programming in general. I am trying write a program that uses a while loop to add integers from 1 to the number entered. the program also has to give an error statement if the user enters a 0 or negative number. So far the integers add up and the error statement works but the program is not looping, it only asks the user to input a number one time. Please help. This is my source code so far. Thanks
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
if x <= 0 or x == -x:
print ("invalid entry")
Try this code...
op='y'
while op=='y':
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
if x > 0:
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
else:
print ("invalid entry")
op = raw_input("Are you want to continue this operation (y/n):" )
Put your whole code this way
done = False
while not done:
//your entire code here except the last 2 lines
if x > 0:
done = True

Resources