Python how to check if value changed - python

I want to print "Same number" if the new number value equals to the last one(same number), else print number variable value if it has changed. How can I do that?
from random import randint
x=0
number=(randint(0,9))
while(x<10):
x+= 1
if(number=="""LAST PRINTED VALUE NUMBER"""):
print ("Same number")
else:
print(number)

You can chage last number in the while loop:
x, last = 0, -1
while (x < 10):
number = randint(0, 9)
if (number == last):
print ("Same number")
else:
print("Last number is {0} now it is {1}".format(last,number))
last = number
x += 1
Output:
Last number is -1 now it is 1
Last number is 1 now it is 2
Last number is 2 now it is 4
Same number
Last number is 4 now it is 2
Last number is 2 now it is 6
Last number is 6 now it is 7
Same number
Last number is 7 now it is 2
Same number

Just save the last one:
from random import randint
x=0
old = number= randint(0,9)
while(x<10):
x+= 1
if(number==old and x > 0):
print ("Same number")
else:
print(number)
old = number
number = randint(0,9)

from random import randint
x = 0
number = -1
while(x < 10):
y = number
number=(randint(0,9))
x+= 1
if(number== y):
print ("Same number")
else:
print(number)

You just need a third variable. Within the "else" after the print statement, set this third variable to "number".

I have a different method:
from random import randint
new = randint(0, 10)
old = new
for i in range(10):
new = randint(0, 10)
if new == old:
print("Same number ({0})".format(new))
else:
print("Diffrent (Last: {0} Now: {1})".format(old, new))
old = new
Output:
Diffrent (Last: 6 Now: 9)
Diffrent (Last: 9 Now: 0)
Diffrent (Last: 0 Now: 2)
Same number (2)
Diffrent (Last: 2 Now: 6)
Same number (6)
Diffrent (Last: 6 Now: 7)
Diffrent (Last: 7 Now: 4)
Same number (4)
Diffrent (Last: 4 Now: 10)

Related

using the calculation number for the next calculation

experts.
I'm trying to define a function (collatz) that:
Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
The result, whatever it is, must enter a loop until the result is 1. (NOK)
So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?
def collatz():
number = int(input('Enter the number: '))
x = number % 2
while number != 1:
if x == 0:
print(f'{number // 2}')
else:
print(f'{3 * number + 1}')
number = number
print(f'{collatz()}')
You need to actually assign the result back to number.
As well:
The divisibility check needs to be in the loop.
The outer print() is not needed.
The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
number = int(input('Enter the number: '))
while number != 1:
if number % 2 == 0:
number //= 2 # Short for "number = number // 2"
else:
number = 3*number + 1
print(number)
collatz()
Example run:
Enter the number: 3
10
5
16
8
4
2
1

hailstone program in python

i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")

Python while loop subtraction

This is a really stupid question but I haven't used this in awhile and can't remember how to do it. I'm doing a recursion problem and need to show the numbers counting down to basically show how the recursion is working. However, I can't seem to figure it out. Here is my code.
def main():
#have user input first number
x = int(input('Enter the first number: '))
#have user input second number
y = int(input('Enter the second number: '))
#calculate result by calling recursive function
result = mult(x, y)
#print the result
print(x, 'times', y, 'is', result)
#define a function that uses recursion
def mult(x, y):
# create a loop to display the numbers
count = y
while count > 0:
print('First number =', x, 'Second number =', count)
count -= 1
#use recursion to multiply the numbers
if x == 0:
return 0
elif x == 1:
return y
else:
return y + mult(x - 1, y)
main()
I need the output to say this:
Enter the first number: 5
Enter the second number: 7
First number = 5 Second Number = 7
First number = 5 Second Number = 6
First number = 5 Second Number = 5
First number = 5 Second Number = 4
First number = 5 Second Number = 3
First number = 5 Second Number = 2
First number = 5 Second Number = 1
5 times 7 = 35
So it's working for the most part, however now it is displaying this:
Enter the first number: 5
Enter the second number: 7
First number = 5 Second number = 7
First number = 5 Second number = 6
First number = 5 Second number = 5
First number = 5 Second number = 4
First number = 5 Second number = 3
First number = 5 Second number = 2
First number = 5 Second number = 1
First number = 4 Second number = 7
First number = 4 Second number = 6
First number = 4 Second number = 5
First number = 4 Second number = 4
First number = 4 Second number = 3
First number = 4 Second number = 2
First number = 4 Second number = 1
First number = 3 Second number = 7
First number = 3 Second number = 6
First number = 3 Second number = 5
First number = 3 Second number = 4
First number = 3 Second number = 3
First number = 3 Second number = 2
First number = 3 Second number = 1
First number = 2 Second number = 7
First number = 2 Second number = 6
First number = 2 Second number = 5
First number = 2 Second number = 4
First number = 2 Second number = 3
First number = 2 Second number = 2
First number = 2 Second number = 1
First number = 1 Second number = 7
First number = 1 Second number = 6
First number = 1 Second number = 5
First number = 1 Second number = 4
First number = 1 Second number = 3
First number = 1 Second number = 2
First number = 1 Second number = 1
5 times 7 is 35
The point of printing the two numbers is to keep track of the recursion. So naturally, the numbers must be printed from inside the recursing function. In other words, you don't want to create an additional loop (using while) to display the numbers, but the recursion is the loop.
You also only want to print the numbers once per recursion step.
What may have additionally confused you is that you have swapped the roles of "first"/x and "second"/y between the desired output and the argument order of the recursion. (You want the "second" number to decrease in the output, but you decrease the first argument (x) of mult.)
It should look like this:
def mult(x, y):
"""Calculate x * y by using recursion."""
print('First number =', x, 'Second number =', y)
if y == 0:
return 0
elif y == 1:
return x
else:
return x + mult(x, y - 1)
if __name__ == '__main__':
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
# calculate result by calling recursive function
result = mult(x, y)
# print the result
print(x, 'times', y, 'is', result)
Just a small change you need to make, you need to update the value of y in the while loop.
#create a loop to display the numbers
while y > 0:
print('First number =', x, 'Second number =', y)
y -= 1
It looks to me like you aren't storing your modified y value. So, the while loop should read like this:
y_temp = y
while y_temp > 0:
print('First number =', x, 'Second number =', y_temp)
y_temp -= 1
Your while loop is outside the recursive call, so the value of y is not getting updated. Move the print statements to be inside the mult function, above the if statement.
def mult(x, y):
print('First number =', x, 'Second number =', y)
print('First number =', x, 'Second number =', y - 1)
if x == 0:
return 0
elif x == 1:
return y
else:
return y + mult(x - 1, y)
You forgot to update y, you're not decreasing y.

100 random numbers with an odd and even counter

I have the following assignment:
In this chapter you saw an example of how to write an algorithm that determines whether
a number is even or odd. Write a program that generates 100 random numbers, and keeps
a count of how many of those random numbers are even and how many are odd.
This is how far I've been able to get, I can get the 100 numbers, but I can't figure out how to total up the odd and evens. This is supposed to include a value returning boolean function as well.
All we're allowed to use is loops, if-elif-else, functions, and other basic things.
import random
NUMBER_LIST = [random.randint(0,1000)]
def main():
for numbers in range(100):
number = print(NUMBER_LIST)
number
is_even(number)
print('The total amount of even numbers is', even_count)
print('The total amount of odd numbers is', 100 - even_count)
def is_even(number):
even_count = 0
for number in NUMBERS_LIST:
if (number % 2):
even_count += 1
return even_count
main()
EDIT:
I'm not supposed to use a List, so if theres a way to do it without, let me know!
import random
def main():
numberList = [] # create an empty list, to add 100 random ints to
for i in range(100):
numberList.append(random.randint(1,1000)) # add a random int
# now, numberList has 100 random numbers in it
# keep track of how many odd numbers
oddCount = 0
# loop through numberList
for number in numberList:
if number%2 == 1: # number is odd
oddCount += 1
evenCount = 100 - oddCount # if a number is not odd, it is not even
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
Okay, now that we have that hard-coded version, let's try a more flexible way that allows you to specify as many things as possible:
def main(numNumbers, smallestNumber, biggestNumber):
numberList = []
for i in range(numNumbers):
numberList.append(random.randint(smallestNumber, biggestNumber))
oddCount = 0
for number in numberList:
if number%2: # oh look, I didn't have to do the `== 1` part
oddCount += 1
evenCount = numNumbers - oddCount
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
import random
NUMBER_LIST = [random.randint(0,1000)]
even = 0;
odd = 0;
for numbers in range(100):
if (numbers%2 == 1):
odd = odd+1
if (numbers%2 == 0):
even = even+1
print('number of evens is: ',even)
print('number of odds is: ',odd)
So you can just do this sort of thing.
from random import randrange
even = 0
for i in range(100):
num = randrange(1000)
if num % 2 == 0:
even += 1
print('There were {0} even numbers and {1} odd numbers.'.format(even, 100-even))
You can do this without a list, but let's do that since your problem may require so.
First of all, note that your code just creates a list with one random number inside it. If you want to populate the list with 100 random numbers, you must do something similar to this:
NUMBER_LIST = []
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
i += 1
Then, you check if the number is even, with number % 2 == 0 (That is, the remainder of the division of number by 2 is 0. this will return either true or false) and increment the respective counter:
NUMBER_LIST = []
# initialize both counters
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
Then, you just need to print the counts:
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
The full code would then be:
import random
NUMBER_LIST = []
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The numbers were: " + str(NUMBER_LIST))
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
And without the list:
import random
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
#!/usr/bin/env python3
import random
def main(n=100):
NUMBER_LIST = [random.randint(0,1000) for x in range(0,n)]
odds = len(list(filter(lambda x: x % 2, NUMBER_LIST)))
print("Odd Numbers: {}\nEven Numbers: {}".format(odds, n-odds))
if __name__ == "__main__":
main()
I am in the same class! This code worked for me.
import random
def main ():
counter = 1
even_numbers = 0
odd_numbers = 0
while counter < 101:
a = random.randint(1,100)
if a % 2 == 0:
even_numbers += 1
else:
odd_numbers += 1
counter += 1
if counter == 101 :
reveal_total(even_numbers, odd_numbers)
def reveal_total(even_numbers, odd_numbers):
print("This many evens : ", even_numbers)
print("This many odds : ", odd_numbers)
main()

How can I log the highest and lowest number entered in Python?

I don't realize what is my mistake, this is how far I got now:
x = 1
e = 0
while x <= 50:
print "Please enter a number (from 1 to 9):"
b = float(raw_input())
asd = 0
if asd == 0:
h = b
l = b
asd = 1
if b < l:
l = b
elif b > h:
h = b
if 1 <= b or b <= 9:
x = x * b
print x
else:
print "Number is too large or too small."
e = e + 1
print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e
This is the program's output:
Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3
Why is the program giving me 5 instead of 4 as lowest number entered and how can I correct that?
You keep resetting asd each iteration, you need to set the variables outside the loop, I would use a list and that will enable you to get the min/max and number of valid inputs :
nums = [] # hold all nums outside the loop
limit = 1
while 50 >= limit:
num = float(raw_input("Please enter a number (from 1 to 9)")
if 1 <= num <= 9:
limit *= num
nums.append(num) # add all to list
else:
print "Number is too large or too small."
print "You have reached a value over 50."
print "Highest number entered:", max(nums)
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)
Everytime you go through the loop, you are setting asd to 0, causing the if statement below it to execute every single time, so you are always blindly updating l with the value the user just entered, which you have named as b
just for fun :)
def get_float_input(msg="Enter a Number:"):
while True:
try:
return float(raw_input(msg))
except ValueError:
print "Invalid Input Please Enter A Float!"
from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)

Categories