I'am beginner in programming and have struggled for a while with one task.
Want to write a program wich finds out how many iterations is needed to arrive at the number 6174 from the specified number.
For example.: if I take number 2341 and sort it.
1) 4321-1234=3087
2) 8730-378=8352
3) 8532-2358=6174 (in this case it`s needed 3 iterations.)
And I have to use ,,while loop,, that it runs a code until it comes to number 6174 and stops.
I wrote a code:
n =input('write for nummbers ')
n=str(n)
i=0
i+=1 #"i" show how many times iteration happend.
large = "".join(sorted(n, reverse=True))
little = "".join(sorted(n,))
n = int(large) - int(little)
print(n, i)
Can you give mee some hint how I could run it with while loop.
# untested, all bugs are free ;)
n = input('write for nummbers ')
n = int(n) # you need n as a number
i=0
while n != 6174:
i += 1 #"i" show how many times iteration happened.
large = "".join(sorted(str(n), reverse=True))
little = "".join(sorted(str(n),))
n = int(large) - int(little)
print(n, i)
Related
I'm currently working on this problem that ask me to generate an arrow pattern using loops function that looks something like this:
"How many columns? 3"
*
*
*
*
*
I know I can do this with for loop(probably more efficient too), but that is not what I aimed for. I wanted to achieve this only using while loop.
I have some ideas:
1. I set up a control variable and an accumulator to control the loop
2. I then write 2 separate loops to generate the upper and lower part of the pattern. I was thinking about inserting the space before the asterisks using method like this:
(accumulator - (accumulator - integer)) * spaces.
#Ask the user how many column and direction of column
#they want to generate
Keep_going = True
Go = 0
while keep_going:
Column_num = int(input("How many columns? "))
if Column_num <= 0:
print("Invalid entry, try again!")
else:
print()
Go = 1
#Upper part
while Keep_going == True and Go == 1:
print("*")
print(""*(Column_num - (Column_num - 1) + "*")
...but I soon realized it wouldn't work because I don't know the user input and thus cannot manually calculate how many spaces to insert before asterisks. Now everything on the internet tells me to use for loop and range function, I could do that, but I think that is not helpful for me to learn python since I couldn't utilize loops very well yet and brute force it with some other method just not going to improve my skills.
I assume this is achievable only using while loop.
#Take your input in MyNumber
MyNumber = 5
i = 1
MyText = '\t*'
while i <=MyNumber:
print(MyText.expandtabs(i-1))
i = i+1
i = i-1
while i >=1:
print(MyText.expandtabs(i-1))
i = i-1
Python - While Loop
Well first you have to understand that a while loop loops until a requirement is met.
And looking at your situation, to determine the number of spaces before the * you should have an ongoing counter, a variable that counts how many spaces are needed before you continue. For example:
###Getting the number of columns###
while True:
number=int(input('Enter number of rows: '))
if number<=0:
print('Invalid')
else:
###Ending the loop###
break
#This will determine the number of spaces before a '*'
counter=0
#Loops until counter equals number
while counter!=number:
print(" "*counter + "*")
#Each time it loops the counter variable increases by 1
counter=counter+1
counter=counter-1
#Getting the second half of the arrow done
while counter!=0:
counter=counter-1
print(" "*counter + "*")
Please reply if this did not help you so that i can give a more detailed response
I am using a function to get the number from user, and I am trying to use a while loop to separate the digits of a number. And I am trying to add the digits of the number. But my code runs infinitely.
Example : 2345 -> 15
def sumDigits(n):
sum=0
while len(str(n))>0:
a = n%10
n = n//10
sum += a
return sum
print(sumDigits(2345))
Expected: 15
Actual: I had to shut down the jupyter kernel to stop the while loop.
Edit 2: Removed the updated code as it was answered by the community.
This condition len(str(n))>0 can never be false as long as n is an integer, because str(0) is '0', which has a length of 1.
You need to change the looping condition to exit where there is no more digit to sum, which happens when n reaches 0:
def sum_digits(n):
total = 0
while n > 0:
a = n % 10
n = n // 10
total += a
return total
print(sum_digits(2345))
Note: sum is a built-in in python, so naming a variable sum is not advised. Also, method names usually are written in snake_case, so sum_digits is recommended.
def all_sum(number):
total = 0
if number > 0:
for e in str(number):
if e.isdigit():
total += int(e)
else:
pass
return total
a = all_sum(567897)
This should do your work. Instead of doing two arithmetic operations to 'fetch' the digits, better to change the argument to string and just use each digit. Its faster and saves memory (though it's not too memory consuming).
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
I'm just playing around with lists and have stumbled across an issue with my code. I can't figure out why my count() won't actually work and display the final total for the heads and tails. It prints 0 rather than what's in the new list..? I've tested the print newlist and it is showing that the list is updating once the loop has completed.
Can anyone help me fix this and explain what I am doing wrong?
Thanks!
import random
i = 0
spins = int(input ("How many spins do you want to do? "))
coin = ["heads", "tails"]
newList = []
while i < spins:
i = i+1
spin = random.sample(set(coin),1)
tallyCoin = spin
print (tallyCoin)
newList.append(tallyCoin)
if i >= spins:
print (newList)
totalHeads = newList.count("heads")
totalTails = newList.count("tails")
print ("the total heads for this round were: ", totalHeads)
print ("the total tails for this round were: ", totalTails)
random.sample returns a list so you are collecting lists with a single string in it instead of strings. Try random.sample(coin, 1)[0] instead.
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!