Looping a function that changes it's output every iteration - python

I'm new to python and I'm trying to create something that if the number is odd for example 7 it does this (7 * 3+1) and if it is even for example 6 it does this (6/2) but the problem is that I want to loop this but it updates the number every output from the example earlier 7 I want this to turn to (22/2) and so on and if the number 1 is reached it stops.
output = []
number = 7
def mat(self):
if (self % 2) == 0:
even = self / 2
return even
else:
odd = self * 3 + 1
return odd
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
print(output)
this part doesn't work because it will never reach 1 and it only has 1 output (22) starting from the number 7 :
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))

To update number, you need to assign it:
number = mat(number)
The best place to do this is in the while loop:
while number != 1:
number = mat(number)
For an exercise like this, it makes sense to just print the value on each iteration rather than trying to create an array of results:
while number != 1:
print(number)
number = mat(number)

Just update the value
For while loop:
a = 0
while a<10:
print("Hello World")
a = a + 1
For for loop:
a = 0
for i in range(10):
print("Hello World")
a = a + 1
if a >= 10:
break

Related

Don't understand why code for digit sum isn't working

I tried to do the codewars Sum of Digits/Digital Root problem, where you have to:
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
So passing through 52 would return 7, as 5 + 2 is 7 and passing through 942 would return 6, as 9 + 4 + 2 = 15 and then 1 + 5 = 6.
I came up with this code:
def digital_root(n):
n_str = str(n)
digit_total = 0
while len(n_str) != 1:
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
But it only works for 2 digit numbers and it won't work for higher digit numbers, it just endlessly runs. This code is probably a bad way to do it and I've looked over other people's answers and I get their solution but I just don't get why this won't work for higher digit numbers.
You have got your program almost right. The only challenge I see is with resetting the variable digit_total = 0 after each iteration.
def digital_root(n):
n_str = str(n)
while len(n_str) != 1:
digit_total = 0 #move this inside the while loop
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
print (digital_root(23485))
The output for print (digital_root(23485)) is 4
2 + 3 + 4 + 8 + 5 = 22
2 + 2 = 4
If the digit_total = 0 is not inside the while loop, then it keeps getting added and you get a never ending loop.
While you have a lot of code, you can do this in a single line.
def sum_digits(n):
while len(str(n)) > 1: n = sum(int(i) for i in str(n))
return n
print (sum_digits(23485))
You don't need to create too many variables and get lost in keeping track of them.
Alex,
running a recursive function would always be better than a while loop in such scenarios.
Try this :
def digital_root(n):
n=sum([int(i) for i in str(n)])
if len(str(n))==1:
print(n)
else:
digital_root(n)

How to run function in loop with changing inputs

After the end of the first round of my program (Collatz function), I want my program to continue to calculate from the previous result.
I wrote a program with the possibility of one iteration, which starts from the input:
def collatz(number):
if number % 2 == 0: #parity conditions value
return number // 2
if number % 2 == 1: #parity oddness value
return 3 * number + 1
result = 5
while True:
print ('Type your number')
result = int(input())
print (collatz(result))
If you want to re-run the function over and over again with the last ran result - store the return value in variable and call the function with it.
def collatz(number):
if number % 2 == 0: #parity conditions value
return number // 2
if number % 2 == 1: #parity oddness value
return 3 * number + 1
print ('Type your number')
result = int(input()) #first time the input will come from the user
while True:
result = collatz(result) #calculate new result
print (result)
#if you want to add break out of the loop put it here

Python 3.4.2 Output Formatting

I have written a code in Python that includes a loop that provides 100 answers pertaining to one variable. So for example the output looks like this when I run it in the shell: (top to bottom)
1
2
3
4
5
etc...
How do I format this to show 10 outputs per line: (left to right)
1 2 3 4 5
Here is my code:
def main():
n = 0
while n <= 100:
if getPentagonalNumber(n):
n += 1
number = (n * (3*n - 1)) / 2
print (format(number, "5.0f"), end = ' ')
def getPentagonalNumber(n):
for n in range (1, 100):
if n > 100:
return False
return True
main()
try the following
print(i, end=' ')
EDIT: If you want to print 10 numbers per line, you can do something like this
if i%10==0:
print('')
This will add a new line after every 10 numbers. (Note: This is assuming that i is the loop variable which is incremented once in every iteration)

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

While Statement(no result in shell)

My program should print the sum from even numbers from 2 to 10, but when I pass even_while() in the shell I don't see any result. Which is the problem?
def even_while():
number = 2
s = 0
while number < 10:
if number % 2 == 0:
old_number = number
number = number + 1
s = s + old_number
print(s)
Thanks!
"Infinite loop". number starts as 2. That's even, so add 1 to it. That leaves number as 3. Now the while loop goes around "forever". number % 2 == 0 is never true (number is 3!), and number never changes again.
You don't increment number unless number % 2 == 0, so the while loop doesn't make any progress.
Additionally, you might enjoy the range builtin:
def even_while():
s = 0
for number in range(2, 10):
if number % 2 == 0:
old_number = number
s = s + old_number
print(s)
def even_while():
number = 0
s = 0
while number < 11:
number = number + 1
if number % 2 == 0:
old_number = number
s = s + old_number
print(s)
I think this is ok.

Categories

Resources