reset a maximum value within a while loop - python-3.x

I am trying to identify how many times values exceed the previous input. the following code works for 1,7,9,0 (two times 7, exceeds 1, 9 exceeds 7), but fails on 1,5,2,4,3,0. I get that this is because I set the maximum to 5 and of course 2 and 4 are less than 5. I cannot figure out what to do to "reset" maximum back to 1
a = int(input())
counter = 0
highest = 1
while a != 0:
if a > highest:
highest = a
counter += 1
a=int(input())
# need to reset highest to next input of 'a'
print(counter)
Grateful for your patience. Still an oldie seeing whether I am brain-dead yet. Sorry if this is a dumb question, I just don't see it. Also the course I am following intimates that I can't use anything but if, else, while, no lists or anything

first_num = int(input())
incremental_count = 0
while first_numv != 0:
second_num = int(input())
if second_num != 0 and first_num < second_num:
incremental_count += 1
first_num = second_num
print(incremental_count)
Once I solved it my way, this was the answer given which is cleverer and simpler!

Related

How do I fix sum of digits of a number code not entering an infinite loop?

I don't understand why it enters an infinite loop. I stated that: if a % 10 == 0: it should break the loop but it doesn't seem to do so. Could someone explain why this happens and why it is not correct and the solution. Thank you!
a = int(input())
total = 0
while a>0:
rest = a % 10
total += rest
if rest == 0:
break
print(total)
It is running for infinite times because of logical error. value of a is not decreasing.
you are checking for remainder, suppose value of a is 230. then at first iteration rest will be 0 and your output will be also 0 (correct sum will be 5).
correct code will be :-
a = int(input())
total = 0
while a>0:
rest = a % 10
total += rest
a=a//10
print(total)

Polydivisible Calculator Fails, Despite Previous Implementation Working

To begin, a definition:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
1 % 1 == 0
14 % 2 == 0
141 % 3 == 0
I'm working on a recursive polydivisible checker, which, given a number, will check to see if that number is polydivisible, and if not, recursively check every other number after until it reaches a number that is polydivisible.
Unfortunately, my code doesn't work the way I want it to. Interestingly, when I input a number that is already polydivisible, it does its job and outputs that polydivisible number. The problem occurs when I input a non-polydivisible number, such as 13. The next polydivisible number should be 14, yet the program fails to output it. Instead, it gets stuck in an infinite loop until the memory runs out.
Here's the code I have:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
I'm assuming the problem occurs in the else statement inside the while loop, where, if the number fails to be polydivisible, the program resets i to 0, and adds 1 to the original number so it can start checking the new number. However, like I explained, it doesn't work the way I want it to.
Any idea what might be wrong with the code, and how to make sure it stops and outputs the correct polydivisible number when it reaches one (like 14)?
(Also note that this checker is only supposed to accept non-negative numbers, hence the initial if conditional)
The mistake is that you are no updating number after incrementing num.
Here is working code:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
I have a similar answer to #PranavaGande, the reason is I did not find any way to iterate an Int. Probably because there isn't one...Duh !!!
def is_polydivisible(n):
str_n = str(n)
list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True
Now, I apologise for this many lines of code as it has to be smaller. However every integer has to be split individually and then divided by its index [Starting from 1 not 0]. Therefore I found it easier to list both of them and divide them index wise.
There is much shorter code than mine, however I hope this serves the purpose to find if the number is Polydivisible or Not. Of-Course you can tweak the code to find the values, where the quotient goes into decimals, returning a remainder which is Non-zero.

Python Collatz Infinite Loop

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

Check if number has a digit multiple times

I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?
This is what I've got so far. the function takes in a list. (updated)
arr = [[1,20],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for c in str(num):
if str(num).count(c) > 1:
# dont know why code is popping off 12 and 13
print(l.pop(num))
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
The best way I can think about is converting the number to a string and doing a Counter on it
from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
print "The number has repeating digits"
#Two-BitAlchemist thanks for the suggestion
looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops
def countNumber(foundDigits,number):
next_number = int(number/10);
reminder = number % 10;
if(next_number < 1):
for num in foundDigits:
if(num == number or num == reminder):
return True
return False;
foundDigits.append(reminder);
return countNumber(foundDigits,next_number)
example in interpreter could be
digitsFound = list()
countNumber(digitsFound, 435229)
Solved this! I didn't know pop executes based on position not value! remove is a better fit here.
arr = [[1,40],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for char in str(num):
if str(num).count(char) < 2: continue
l.remove(num)
break
print(l)
Here is my solution, its simple and works for 2 digit numbers.
nums = list(input().rstrip().split())
def has_doubles(nums):
for number in nums:
if number[0] == number[1]:
print(number)
else:
continue
has_doubles(nums)

How to keep accounts for the range of possible numbers on which it is reasonable to make an attempt to guess (Guessing The Number Game on Python)

I'm a beginner in Python , and I'm trying to make an improvement in the guessing the number game.
So far my guessing the number game consists of guessing a secret randomly integer selected by Python in the range of 1 to 100, inclusive, in 10 or fewer attempts.
"x" is the secret number.
The program should ask the user to type a guess "n" for the number "x".
Before typing each guess, the game program count and displays the number of attempts so far. If after 10 attempts have not guessed the number, the program scolds the user with a message like : Unfortunately you have not able to find out the number in 10 attempts.
The "x "number was 40 for give an example so the program looks like these:
Welcome to the game
The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.
Attempt 1 ,type your guess: 50 # 50 is the input of the user
The program would display something like these:
Attempt 1 ,type your guess: 50
x < 50
Attempt 2 ,type your guess:
In addition, the program must keep accounts for the range of possible numbers on
What it is reasonable to make an attempt to guess.
After the first attempt, when the program told you how is "x" compared to "n", if the guess is not in this range, the program must draw attention with a message like "Ooops, we already knew that x < 60" (for example , if you already typed 50 and the program told you that x < 50)
The thing is that I don't know how to keep accounts for the range of possible numbers on which it is reasonable to make an attempt to guess.
Here is an example of what I want to do:
Welcome to the game
The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.
Attempt 1 ,type your guess: 50
x < 50
Attempt 2 ,type your guess: 60
If someone type 60 , that is not within the possibilities within which you can find x , so what I want to do , is when something like these happens , the program will print for example :
Attempt 2 ,type your guess: 60
Ooops, we already knew that x < 60
Because the program already told the person that x < 50 , so it is not possible that x = 60
Here's my code so far:
#Guessing the number game
import random
attempt = 0
attempt = attempt + 1
print('Welcome to the game')
print('The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.')
x = random.randint(1,100)
while attempt < 11:
print('Attempt', attempt , ',type your guess')
n = input()
n = int(n)
attempt = attempt + 1
if n < x:
print('x >',n)
if n > x :
print('x <',n)
if n == x:
break
if n == x:
attempt = str(attempt)
print('Congratulations, you have guessed the number in ' , int(attempt) -1 , 'attempts')
if n != x:
x = str(x)
print('Unfortunately you have not able to find out the number in 10 attempts. The number was' , x)
All you needed to do was add closestmin and closestmax values to the evaluation of the guessed number. Here's my suggestion as to how to do it
import random
attempt = 1
closestmin = 0
closestmax = 100
print('Welcome to the game')
print('The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.')
x = random.randint(1, 100)
for guess in range(10):
print("Attempt", attempt)
n = int(input('Type your guess'))
if n == x:
attempt = str(attempt)
print('Congratulations, you have guessed the number in' , attempt, 'attempts')
break
elif n < x:
if n > closestmin: #if guess is closer than previous closest lowest guess
closestmin = n #update closest lowest guess with new number
print('x >', n)
elif n < closestmin:
print("We already know that x <", closestmin)
elif n > x :
if n < closestmax: #if guess is closer than previous closest lowest guess
closestmax = n #update closest largest guess with new number
print('x <', n)
elif n > closestmax:
print("We already know that x <", closestmax)
attempt = attempt + 1
if attempt > 10:
print('Unfortunately you have not able to find out the number in 10 attempts. The number was' , x)
break
As you can see, I've added a second if statement that checks to see if the guess was closer than the previous one, and otherwise remind them of their closest guess.
I've also replaced you while loop with a for loop, for greater simplicity.
Keep coding!

Resources