Python: Problems in calling the function from the while loop - python

I have a while loop which calls the function mainrt() on each iteration.
if __name__ == "__main__":
inp = sys.stdin.read()
inpList = inp.split('\n')
inpList.pop()
for n in inpList:
i = 0
p = 0
n = int (n)
while True:
i += 1
p = n*i
if n == 0:
print "INSOMNIA"
break
else:
res = True
res = mainrt(p)
if res == False:
print p
break
And the mainrt()
def mainrt(n):
#print n
while True:
rem = n % 10
if rem in diMon:
pass
else:
diMon.insert(rem,rem)
if len(diMon) == 10:
return False
break
n = n/10
if n == 0:
return True
break
else:
continue
The problem is as i take input from stdin.read() the first line of the input processed properly by the function, but the second line of the input get printed as it is. It is not being processed by the function
example
INPUT
3
5
OUTPUT SHOLD BE
30
90
But instead I get
30
5
Why the function not processing the input the second time???
There is no run time error so far.

In your mainrt function I do not see that you declare diMon list, so it looks like it is a global variable and you do not clean that list. That mean your mainrt return False at the first check of if len(diMon) == 10: for the second input. You should declare diMon at the beginning od mainrt function or clear it at the end of while loop body.
EDIT:
Now I checked your code one more time and I suggest you to declare diMon at the beginning of for loop
for n in inpList:
diMon = []
i = 0
p = 0
n = int (n)

Related

Code not entering if statement with valid statement and not exiting while loop

I'm trying to see if the Collatz Conjecture is really true, it says that every integer number which is divided per 2 if it's even and multiplied by 3 and added 1 if it's odd, will eventually come to a loop of 4, 2, 1. But it gets stuck in a while loop and doesn't break or gets inside the if statement that I want
integers = [5]
#Returns true if a number is even and false if it's odd
def even(num):
if (num % 2 == 0):
return True
else:
return False
#Returns true if a list of a number is in a loop
def loop(numbers):
for x in numbers:
if (numbers.count(x) > 1 or 4 in x == True):
return True
break
else:
return False
continue
#Print a list of numbers that agree with the Collatz conjecture
def collatz(list):
for x in list:
collatz_nums = []
l = loop(collatz_nums)
list.append(list[-1] + 1)
#Add the first number to the "collatz_nums" list
if (even(x) == True):
collatz_nums.append(x / 2)
elif (even(x) == False):
collatz_nums.append(x * 3 + 1)
#Adds numbers to the collatz_nums variable
while (l != True):
print("Start")
if (l == False):
if (even(collatz_nums[-1]) == True):
collatz_nums.append(collatz_nums[-1] / 2)
print("/2")
else:
collatz_nums.append(collatz_nums[-1] * 3 + 1)
print("*3+1")
else:
print("Exit")
break
print(F'{x} = {collatz_nums}')
collatz(integers)
Let's start here
collatz_nums = []
l = loop(collatz_nums)
You're passing an empty list to a function with only return statements in the event that you have data to loop over, so the function returns, setting l = None
Now while (None!=True) is an infinite loop since you're never modifiying value of l
Perhaps you should move the "add first number" if statements (which really only need to call even function once using if-else) above those two lines? Or above for x in list so that you only add the first number once?
I'd also recommend removing 4 in x == True since I doubt that does what you want

Looping a function that changes it's output every iteration

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

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 script "generating" "None" values

So I have been having this issue with a simple python script I'm working on for an assignment. I am to make a small script simulating a lottery, and have written this code:
import random
def drawNumbers(nlist, n):
drawnlist = []
i = 0
while i < n:
if i == 0:
drawnlist.append(nlist[random.randint(0,33)])
i+=1
else:
r = random.randint(0,33)
dup = False
for x in drawnlist:
if x == r:
dup = True
if dup == False:
drawnlist.append(nlist[r])
i+=1
return drawnlist
def compList(drawlist, guesslist):
count = 0
for j in drawlist:
for h in guesslist:
if j == h:
count +=1
return count
def winnings(right, altright):
altcorrect = False
if altright > 0:
altcorrect = True
if right == 7:
return 2749455
elif right == 6:
if altcorrect:
return 102110
else:
return 3385
elif right == 5:
return 95
elif right == 4:
if altcorrect:
return 45
else:
return 0
a=0
tot = 0
while a <100:
numbers = []
i = 1
while i <= 34:
numbers.append(i)
i+=1
myGuess = []
i = 0
while i <7:
if i == 0:
myGuess.append(random.randint(1,34))
i+=1
else:
r = random.randint(1,34)
dup = False
for x in myGuess:
if x == r:
dup = True
if dup == False:
myGuess.append(r)
i+=1
tot += winnings(compList(drawNumbers(numbers,7),myGuess),compList(drawNumbers(numbers,3),myGuess))
a+=1
print(tot)
And it seems to be working fine for one iteration, however, when I increase a like now with a value of 100, I get an error saying that I cannot sum an "int" object and a "None" objects. When I tinkered with the code and printed "winnings" instead of the summed total for each iteration, it looks like the function sometimes returns "None" instead of a number. I can however not seem to recreate that with a smaller amount of iterations, so my question: Is this code related, or might it be that by calling the functions "too fast" it does not create a number? I know this question might seem odd, but I am new to programming as a whole and python itself, and I have no clue how to debug this.
The winnings function can return None as there is no else to the inner if. In this case, it does not trigger the final else and returns None by default. To fix it, add an else to the if, or just remove the final else in winnings:
def winnings(right, altright):
altcorrect = False
# ...
elif right == 4:
if altcorrect:
return 45
# maybe add an else here?
# or if you get to this point, _always_ return 0
return 0
Your winnings function sometimes returns None. It's because it's not catching some cases. Python returns None if it reaches the end of a function without any other returns being hit.
Specifically, if right is 4 and altright is 0, none of the if cases will get caught and the function returns None.

While loop creating

I am writing a program in Python that defines a function that takes a single argument. The function has to be a while loop the returns the largest power of 16 that it is equal to. However, I am not sure how to write the while loop.
Python Docs
while True:
n = input("Please enter 'hello':")
if n.strip() == 'hello':
break
so, in layman's terms
while <condition>:
...
I couldn't completely understand your question but here's how to do a while loop to get the x to the 16th power of an input:
def loop_function(x):
y = 1
start = x
while y != 16:
result = start * x
start = result
y += 1
return result
print loop_function(3)
The above code will return the answer to 3^16 which is 43046721
You can even make this a broader function two arguements
def loop_function(x, y):
z = 1
start = x
while z != z:
result = start * x
start = result
z += 1
return result
print loop_function(3, 2)
The above code will return 9 i.e 3^2

Categories

Resources