def fib_gen(fib=-1):
print(f"initial fib={fib}")
a = 1
b = 0
yield b
i = 1
print(f"initial i={i}")
while(i!=fib):#infinite sequence by default, since default value of fib is -1
c = a
a = a+b
b = c
i = i+1
print(f"i={i}")
print(f"fib={fib}")
print("is fib==i: ",fib==i)
input("Continue? ")
yield a
x = input("First how many fibonacci numbers do you want? ")
fibs = fib_gen(x)
print(f"x={x}")
try:
while(True):
print(next(fibs))
except:
print(f"That's the first {x} fibonacci numbers")
Even when fib and i become equal, the result shows False. Why?
And if I pass a concrete value in the generator function instead of a variable, then the result comes as expected. Why???
input() returns a string by default, to get a number do int(input())
x = int(input("First how many fibonacci numbers do you want? "))
Related
n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)
I'm trying to take the first number from a list and use it as my initial value. When I started doing subtraction, I realized that you actually don't start at 0 as you do with adding number, but you start with first number written in 'for'.
For example, when you add 0+4+5, then 4+5 is actually the same thing; when subtracting, it's different to do 0-4-5 and 4-5. I'm just starting with Python and programming in general, so I'm wondering if this is even possible.
My code:
print ("You chose subtraction.")
b = int(input("Enter how many numbers you want to substract."))
c = [int (input( "Number: ")) for _ in range (b)]
result = functools.reduce(operator.sub, c, INIT_VALUE)
print("Your answer is:", result)
You can get the first number that was entered by accessing c[0] ( or values[0] in my example ), you also only need to subtract the values after this index so you can use c[1:] ( or values[1:] in my example )
import operator
import functools
print("You chose subtraction.")
total_numbers = int(input("Enter how many numbers you want to substract."))
values = [int(input("Number: ")) for _ in range(total_numbers)]
result = functools.reduce(operator.sub, values[1:], values[0])
print("Your answer is:", result)
>> You chose subtraction.
>> Enter how many numbers you want to substract.
> 5
>> Number:
> 10
>> Number:
> 1
>> Number:
> 1
>> Number:
> 1
>> Number:
> 1
>> Your answer is: 6
There are a few ways you can do this:
You could get the first number separately:
>>> INIT_VALUE = input('Number: ')
>>> numbers = [int(input('Number: ')) for _ in range(b - 1)]
>>> result = reduce(sub, numbers, INIT_VALUE)
Alternatively, you could use indexing:
>>> INIT_VALUE = c[0]
>>> rest = c[1:]
>>> result = reduce(sub, rest, INIT_VALUE)
Or, if you wanted to use a loop instead of reduce:
>>> result = int(input('Number: '))
>>> for _ in range(b - 1):
... result -= int(input('Number: '))
You can do reduce(sub, lst[1:], lst[0]), but you can also skip the inifializer altogether
reduce(sub, lst)
If you won't provide it, the first value will be taken
https://docs.python.org/3/library/functools.html#functools.reduce
Another option is itertools.accumulate in Python 3. This allows you see intermediate calculations.
import operator as op
import itertools as it
print("You chose subtraction.")
total_numbers = int(input("Enter how many numbers you want to substract? "))
values = [int(input("Number: ")) for _ in range(total_numbers)]
# You chose subtraction.
# Enter how many numbers you want to substract? 3
# Number: 0
# Number: 5
# Number: 6
results = list(it.accumulate(values, op.sub))
results
# [0, -5, -11]
results[-1]
# -11
See also this post comparing accumulate and reduce.
I have a function named orderInt passed three integers and returns true if the three int are in ascending order, otherwise false. Here's my code so far:
def orderInt(a, b, c):
print "Enter 3 integers: "
a = input()
b = input()
c = input()
How do I compare the variables?
First of all, your indentation is wrong.
def orderInt():
print "Enter 3 integers: "
a = input()
b = input()
c = input()
if a<b<c:
return True
else:
return False
print orderInt()
Second, your function is taking three arguments and also taking inputs. The arguments passed will be overwritten by your inputs.
def orderInt():
print "Enter 3 integers: "
if a<b<c:
return True
else:
return False
a = input()
b = input()
c = input()
print orderInt(a,b,c)
Hope this helps.
I'm writing for creating a list of number from input and get the average of the list. The requirement is: when the user enters a number, the number will be appended to the list; when the user press Enter, the input section will stop and conduct and calculation section.
Here is my code:
n = (input("please input a number"))
numlist = []
while n != '':
numlist.append(float(n))
n = float(input("please input a number"))
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
if I enter numbers, everything works fine. But when I press Enter, it shows ValueError. I know the problem is with float(). How can I solve this?
You don't need the float() around the input() function inside your loop because you call float() when you append n to numlist.
this should solve ur prob ,by adding a try,catch block around ur print statement
n = (input("please input a number"))
numlist = []
while True :
numlist.append(float(n))
#####cath the exception and break out of
try :
n = float(input("please input a number"))
except ValueError :
break
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?
def reverse(num):
s=len(num)
newnum=[None]*length
for i in num:
s=s-1
newnum[s]=i
return newnum
def palindrome(num):
a=str(num)
l=len(z)/2
if a[:1]==a[-1:][::-1]:
b=True
else:
b=False
I am having some trouble to write def main.
def palindrome(num):
return str(num) == str(num)[::-1]
Integer numbers don't have len().
Testing if a number is a palindrome is as simple as testing if the number is equal to its reverse (though if you want maximum efficiency you can just compare characters from both ends of the string until you reach the middle).
To find the reverse of an integer you can either do it the hard way (using mod % and integer division // to find each digit and construct the reverse number):
def reverse(num):
rev = 0
while num > 0:
rev = (10*rev) + num%10
num //= 10
return rev
Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):
def reverse(num):
return int(str(num)[::-1])
This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.
def reverse(i):
return int(i!=0) and ((i%10)*(10**int(math.log(i,10))) + reverse(i//10))
def is_palindrome(i):
return i == reverse(i)
It works for integer i ≥ 0.
Note that reverse(123) == reverse(1230) == 321. This is not a problem, considering any nonzero integer that ends with 0 cannot be a palindrome anyway.
Note also that complete reversal of the integer may of course not be necessary to determine if it's a palindrome. The reversal may be implemented so as to be aborted early if the number is determined to not be a palindrome.
Long but readable:
def palindrome(x):
a=""
x=str(x)
for i in range(len(x),0,-1):
a+=x[i-1]
print a
if a==x:
return True
else:
return False
Reverse an integer and determine if it is a palindrome:
Convert integer to string.
Use reverse function to reverse the string and join it.
Check if reversed number = original number with if else condition.
See code:
number = 1221
reverse = ''.join(reversed(str(number)))
print(reverse)
if (int(reverse) == number):
print("number is Palindrome")
else:
print("number is not Palindrome")
def revers(num):
rev = 0
while num > 0:
rem = num % 10
rev = (rev * 10) + rem
num = num // 10
return rev
I used a list for this program, works with strings too.
print('Enter Something')
a = list(input())
for i in range ((len(a)),0,-1):
print (a[i-1],end='')
import math
a = raw_input("Enter number:")
n = -1
reverse = 0
for i in a:
n += 1
digit = math.pow(10,n)
reverse = int(i)*digit + reverse
print int(reverse)
if int(reverse) == int(a):
print "Palindrome"
else:
print ":("
This code converts int to String and then checks if the string is pallindrome. The advantage is that it is fast, the disadvantage being that it converts int to String thereby compromising with the perfect solution to question.
It handles negative int as well.
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x)
if x >=0 :
if s == s[::-1]:
return True
else:
return False
else:
return False
t=int(input("enter nos of test cases= "))
while t>0:
n=int(input("enter number="))
rev=0
while n>0:
digit=n%10
rev=rev*10+digit
n=n//10
print(rev)
t-=1
Here is my solution.
z=input('input number')
if int(z) == int(str(z)[::-1]):
print('The number is palindrome')
else:
print('The number is not palindrome')
def pal_num(num):
if num<0:
print(False)
elif num == int(str(num)[::-1]):
print(True)
else:
print(False)
This example quickly takes care of the negative number edge case
I try to come out with this myself.
def number():
n = int(input("Enter a number: "))
return n
def reverse(n):
total = ""
while n > 0:
a = n % 10
n//= 10
total+= str(a)
return total
def palindrome (n):
total = 0
while n > 0:
a = n % 10
n//= 10
total+= a
if total == n:
x = "This number has a palindrome"
else:
x = ""
return x
n = number()
print (reverse(n))
print (palindrome(n))
original = raw_input("Enter a no = ") #original = number entered by user
rev = original[::-1] #rev = reverse of original by useing scope resolution
print 'rev of original no =',rev
if original == rev:
print "no's are equal"
else:
print "no's are not equal"