I'm a new learner of python, when I try to write a Collatz function I find that pycharm shows me one line is unreachable. I wonder why the function can't run the code
def Collatz(numBer):
if numBer%2 == 0:
return numBer//2
else:
return 3*numBer+1
print(numBer) #this code is unreachale
print('Please input the number:')
numBer = int(input())
while numBer != 1:
Collatz(numBer)
print(Collatz(numBer)) #because the former code are unreachable,so I write this to print the results
numBer = Collatz(numBer)
All code within the same scope below a return statement is unreachable because the function will finish its execution there. In your case you are returning the result so there is no need to rerun the function again to print it. Just take it in a variable and use it:
def Collatz(numBer):
if numBer%2 == 0:
return numBer//2
else:
return 3*numBer+1
print('Please input the number:')
numBer = int(input())
while numBer != 1:
numBer = Collatz(numBer)
print(numBer)
Hello welcome to Stack Overflow!
The reason why the print is "unreachable" is because of the return before the print. return ends a control flow so any code after the return is disregarded. Basically, the control flow goes like this (based on your function):
"Is the numBer divisible by 2?"
"If yes, then give me the integer division of that number and 2"
"Otherwise, give me the 3*number + 1"
If you wanted to print the number before you return it, it would be best to store it first into a variable and then return that variable, like so:
def Collatz(numBer):
if Collatz % 2 == 0:
value = numBer // 2
else:
value = 3 * numBer + 1
print(value)
return value
Related
I'm asked to write a function generate_palindrome() that takes a given positive integer number n and applies the following procedure to it:
(i) Check if the number is palindrome. If it is, then return it otherwise continue with the next step.
(ii) Reverse the number and calculate the sum of the original number with the reversed number.
(iii) Repeat from (i) (until a palindrome is found.)
I wrote this function:
def generate_palindrome(n):
numbers = list(str(n))
for i in range(len(numbers)):
if numbers[i] == numbers[-i-1]:
return n
else:
while numbers[i] != numbers[-i-1]:
rev = list(reversed(numbers))
rev_num = int(''.join(rev))
n = n + rev_num
return n
I don't know for what reason when I try a random number that is not already palindrome, the code doesn't respond, it's still running until an indefinite amount of time. I tried changing it with an if code but it doesn't iterate my function, so I think my only chance is with the while code, but maybe I'm the one who's wrong. What do you think?
I think that you should've added a broken functionality to your while loop so that when a specific condition is achieved it breaks. And I think that the indentation of the last return statement is wrong. :)
Here you go:
#!/usr/bin/env python3
def generate_palindrome(num: int):
if str(num) == str(num)[::-1]:
return num
else:
while str(num) != str(num)[::-1]:
rev = int(str(num)[::-1])
num += rev
return num
if __name__ == '__main__':
print(generate_palindrome(212)) # prints 212
print(generate_palindrome(12)) # prints 33
print(generate_palindrome(43)) # prints 77
This is the best solution:
def generate_palindrome(n):
while True:
number = list(str(n))
num = ''
if number[::-1] == number:
for i in number:
num = num + i
print(num)
break
print(a)
else:
for i in number:
num = num + i
n = int(num) + int(num[::-1])
generate_palindrome()
New here at stackoverflow. I'm learning python right now and picked up the book Automate the Boring Stuff with Python. Need some recommendations or tips on how to clean up my code. Here is one of the small projects from the book:
Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
The output of this program could look something like this:
Enter number:
3
10
5
16
8
4
2
1
Here's the code I came up with. Any recommendations on cleaning up the code or is this good enough? Thank you all!
def collatz(number):
if number % 2 == 0: # Even numbers
print(number // 2)
return number // 2
elif number % 2 == 1: # Odd numbers
result = 3 * number + 1
print(result)
return result
while True: # Made a loop until a number is entered
try:
n = input("Enter a random number: ")
while n != 1:
n = collatz(int(n))
break
except ValueError:
print("Enter numbers only.")
Use else in the place of elif , it will give same reasult.
Optimized for readability and usage, not on performance.
def collatz(number):
print(n)
return number // 2 if number % 2 == 0 else 3 * number + 1
while True: # Made a loop until a number is entered
try:
n = input("Enter a random number: ")
while n != 1: n = collatz(int(n))
break
except ValueError: print("Enter numbers only.")
I have to words. They have tehe same lenght. I want to check if the second word is encoded with a Caesar cipher correctly. I wrote a simple function, but sometimes it works but sometimes not. I dont know what is wrong.
This may code:
def check_Ceaesar(word1, word2):
t=word1
s=word2
k=ord(s[0])-ord(t[0])
if k>0:
k=ord(s[0])-ord(t[0])
else: k=26+(ord(s[0])-ord(t[0]))
for i in range(1,len(t)):
if ord(t[i])<ord(s[i]):
temp=ord(s[i])-ord(t[i])
else: temp=26+(ord(s[i])-ord(t[i]))
if temp!=k:
return "YES"
break
else:
return "NO"
You should return 'NO' if temp is not equal to k instead, and wait for the loop to finish before returning 'YES'.
Change:
for i in range(1,len(t)):
if ord(t[i])<ord(s[i]):
temp=ord(s[i])-ord(t[i])
else: temp=26+(ord(s[i])-ord(t[i]))
if temp!=k:
return "YES"
break
else:
return "NO"
to:
for i in range(1,len(t)):
if ord(t[i])<ord(s[i]):
temp=ord(s[i])-ord(t[i])
else: temp=26+(ord(s[i])-ord(t[i]))
if temp!=k:
return "NO"
return "YES"
You can also check that the differences between the ordinary numbers of the corresponding letters of the two words after taking the modulo of 26 are of only one number by converting them to a set and checking that the length of the set is 1:
def check_Ceaesar(word1, word2):
return len({(ord(a) - ord(b)) % 26 for a, b in zip(word1, word2)}) == 1
Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue
My program breaks if a person inputs a letter instead of a interger the base of the problem is around here
while quesses<6 :
guesses = guesses+1
guess = input("Guess a number 1 to 100)
if int(guess) ==r:
print("correct you took" + str(guesses) + "tries")
break
the problem is if a letter is used it breaks what could I do to make it evaluate that it is a string the redo then input without increasing the value of guesses
Use some function to do the number parsing.
Parse the user input inside some try-except block.
If that succeeded => increase counter and return result and counter.
If not => call your number parsing function again.
Some simple number guessing game would be:
from random import choice
def get_number(current):
result = None
try:
result = int(
input('>>> [Round #{}] Guess a number between 1 and 100: '.format(
current + 1
))
)
except ValueError:
print('!!> [ERROR] Please try again')
if result is not None:
current += 1
return result, current
return get_number(current=current)
guesses = 0
unknown = choice(range(0, 100+1))
# print('>>> [debug] unknown is:', unknown)
while guesses < 6:
guess, guesses = get_number(guesses)
if guess == unknown:
print('>>> you win!', 'took', guesses, 'guesses')
break
print('>>> game over')