I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. Thanks for your help! The assignment and code is below (for an Udemy class).
Happy Numbers -
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. Find first 8 happy numbers.
def find_happy_number(x):
#we need a bunch of lists
digit_list = []
squared_list = []
result_list = []
happy_numbers = []
unhappy_numbers = []
while True:
#break our number into digits
x = str(x)
for digit in x:
digit_list.append(int(digit))
#square each digit and store in list
for digit in digit_list:
squared_digit = digit**2
squared_list.append(squared_digit)
#adds all numbers on that list
result = sum(squared_list)
print(result)
#check to see if it is a happy number
if result == 1:
print(f'{x} is a happy number!')
break
#check to see if it is an un-happy number
if result in result_list:
print(f'{x} is an UN-happy number!')
break
#if it isn't we continue the churning.
#adds result to result list to see if we are looping infinitally
x = result
result_list.append(result)
`
The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.
Consider this for your loop:
while True:
digit_list = [int(digit) for digit in str(x)]
squared_list = [digit**2 for digit in digit_list]
Now you don't need to initialize them. Or, for extra fun, combine it all into one:
while True:
result = sum(int(digit)**2 for digit in str(x))
Related
Hello I am new to coding and just learn some basics of codding can anyone help me out with this problem :- I have written a code to find 1st and last term using loop but can't add them the code is given below
n = input("enter your number:-")
#By loop
if (n.isnumeric):
for i in range(len(n)):
if i == 0:
print(f" your first digit of the number is {n[0]}")
elif i== len(n)-1:
print(f" your last digit of the number is {n[-1]}")
else:
print("Please enter a number and try again!")
please can someone modify this code to find the sum of 1st and last digit ?
thank you:)
Actually, you're very CLose to the answer you're seeking, there are just a few errors to be corrected. See the revised version, and check?
Note - this is to follow OP's thinking, and make minimum changes.
Of course, there're many alternative ways to achieve it (and more error checking for invalid inputs, but that's another story/exercise).
n = input("enter your number:-") # ex. 123
#By loop
if (n.isnumeric()): # calling the method: isnumeric()
for i in range(len(n)):
if i == 0:
first = n[0] # assign it to first digit
print(f" your first digit of the number is {n[0]}")
elif i == len(n)-1:
last = n[len(n) -1] # assign it to last digit
print(f" your last digit of the number is {n[-1]}") # convert to integer
print(f' the sum of first and last digits: {int(first)+int(last)} ')
# 4 <- given input 123
You already know how to get the last item in a sequence - i.e., n[-1]
Therefore, using a loop is irrelevant.
What you do need to do however is to check 2 things.
Is the input at least 2 characters long?
Is the input comprised entirely of decimal characters
Which gives:
inval = input('Enter a number with at least 2 digits: ')
if len(inval) > 1 and inval.isdecimal():
first = inval[0]
last = inval[-1]
print(f'Sum of first and last digits is {int(first)+int(last)}')
else:
print('Input either too short or non-numeric')
Another interesting approach using map() and some unpacking to process the input:
inval = input('Enter a number with at least 2 digits: ')
if len(inval) > 1 and inval.isdecimal():
first, *_, last = map(int, inval)
print(f'Sum of first and last digits is {first+last}')
else:
print('Input either too short or non-numeric')
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
if number % div == 0:
list.append(div)
div =+ 1
print list
this is my code which I made for this exercise :
http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
I am new to programming so i dont know what is wrong with my code but its not giving any output.
I guess this answer is simple enough, and looking from the down-votes people think this too. However... one only learns by asking!
There are three essential mistakes in the code that you propose, and a number of ways to make it more Pythonic.
First, and foremost, dividing by zero is not possible! So you'd want to check numbers in the range (1-number).
Based on the indentation list is printed many times, instead of only at the end of completing the while loop.
You want to avoid using list as a variable because it is a Python keyword.
Then, to make it more Pythonic my proposition is the following:
number = int(input("Enter a number :"))
output = []
for i in range(1,number+1):
if not number%i:
output.append(i)
print(output)
Note that raw_input no longer exists in Python 3.x. Also note that this way we avoid the while loop, that from experience, can easily lead to mistakes. In stead it has been replaced by automatically looping through the entries in the list generated by range(1,number).
Finally a note on range but probably also on semantics. I consider number also to be a divisor of number. To do so I have used range(1,number+1). Because, for example range(5) returns a list up to 5: [0,1,2,3,4]. I.e. it does not include 5.
Here is the code you need:
number = int(input("Enter a number :"))
list = []
# theoretically this is the limit you should test for divisors
for div in range(2, int(number/2 + 1)):
if number % div == 0:
# adds the divisor to the list
list.append(div)
div += 1
# prints all divisors in new line
for item in list:
print(item)
If you are using python 2.7, instead of input use raw_input
I am currently partway through a school project which requires me to create a python program that can read in two non-negative integers, begin and end, and print out all of the palindromes which occur between begin and end (inclusive). The code we have been given is this:
begin = int(input('Enter begin: '))
end = int(input('Enter end: '))
palindromes = 0
# Add your code here. You will want to start with a "for x in range" style loop.
print('There are', palindromes, 'palindrome(s) between', begin, 'and', end)
Question: How would I calculate how many palindromes are in the range of the two numbers entered (and which numbers are palindromes)?
Research: I have tried having a look at pages, this one was a good one though I (being new to python) could not make sense of it when I put it into code:
how to check for a palindrome using python logic
Palindrome number are written in the same way from right to left and from left to right : Exemple :
123 is not a palindrome number because its inverted representation is 321
121 is a palindrome number because its inverted representation is 121
and the simpliest way to do this in python is to convert the number into a string and compare it to its inverted representation (Let's say that n is a number and we want to know if it's a palindrome or not) :
if str(n) == str(n)[::-1]:
print "It's a palindrome number"
so the solution for your problem is an if brunch inside in iteration like below :
print "Enter begin:"
begin = int(raw_input("> "))
print "Enter end:"
end = int(raw_input("> "))
palindromes = 0
for x in range(begin, end):
if str(x) == str(x)[::-1]:
palindromes += 1
print "There are %d palindrome(s) between %d and %d" % (palindromes, begin, end)
A palindrome is a number which when written reversed is same as the original number. For example, 1234321 is a palindrome.
So, to check this, all you have to do is check if the reverse of the number is the same as original.
Here's the code.
begin = int(input('Enter begin:'))
end = int(input('Enter end:'))
palindromes = 0
for i in range(begin, end+1, 1):
if str(i) == str(i)[::-1]: #Here I convert the int to string and check if t matches the reverse
palindromes += 1
print i
print "Total number of palindromes = ",palindromes
Since this is school work I don't see a huge benefit in writing code for you, but here's how to break down the problem.
As the comment in your example says, you're going to want to start with a for x in range loop. In this case I suggest you use the version of range() that takes both a start point and a stop point (begin, and end) -- note that this will iterate over numbers between start and stop INCLUDING start but NOT stop.
Example -- prints numbers 1 to 9 each on their own line:
for x in range(1, 10):
print(x)
Inside your for loop you can then test to see if x is a palindrome. If it is you'll want to add it to a list of found palindromes. Later on you can set your palindromes variable to be the length of this list, and print out the contents as needed.
To find out if x is a palindrome, the answer you've found should help. Alternatively you can think about what a palindrome is and have a go at writing your own method. You'll want to convert x to a string before you start, and then it's just a case of comparing the first and last halves of the string, and there are a few interesting ways of doing this :)
Here are two options you could try:
1) Use slicing to split the string in half (ignoring the middle character if there is an odd number of characters). Reverse ONE half of the string, and then compare it with the other half; if they are the same then it's a palindrome.
2) Use another for loop with a start of 0 and a stop of half the length (rounded down to the nearest whole number). Inside the loop take slices of both ends of the string and compare them.
Example (where x is the loop counter and currently has a value of 0).
string = 'abcd'
string[0+x]
'a'
string[-(1+x)]
'd'
For both of these answers you'll want to look at how to slice a string if you're not already familiar with this. There's some helpful examples in this Python introduction.
Thank you everyone, the code I found to be the answer was this:
begin = int(input('Enter begin: '))
end = int(input('Enter end: '))
palindromes = palindromes = len([i for i in range(begin, end+1) if str(i) == str(i)[::-1]])
for i in range(begin, end+1):
if str(i) == str(i)[::-1]:
print(i,'is a palindrome')
print('There are', palindromes, 'palindrome(s) between', begin, 'and', end)
# Palindrome Number Calculator
Palindrome = False
Test = 0
newInt = 0
myInt = int(input("Enter a number "))
myIntReversed = int(str(myInt)[::-1])
if myInt == myIntReversed:
print("Your number is a palindrome")
Palindrome = True
exit()
while Palindrome == False:
myInt += myIntReversed
Test += 1
myIntReversed = int(str(myInt)[::-1])
if myInt == myIntReversed:
print("Palindrome")
print(myInt)
Palindrome = True
exit()
If you use pycharm then you can use the debug feature to see what test number the computer is at. I am not printing this number so the program runs faster. Try to see if your program can see what the palindrome of 196 is :)
I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1