Function keeps looping same two numbers - python-3.x

So i'm trying to follow along in the Automate The Boring Stuff with Python book. There's a question that asks me to make the collatz sequence. One function collatz() will be processing the actual math, while the second function get_collatz() will be the one taking user input and running it through the collatz function until the returned number == 1. I apologize if this is a simple mistake, I may have had a little to drink as well as being new to the site and fairly new to coding also. Would appreciate it if someone could help to point me in the right direction. I don't want a straight up answer because I want to learn myself, would just like an idea of what could be going wrong here. Here is my code.
def collatz(number):
if number % 2 == 0:
number //= 2
print(number)
return number
else:
number = 3 * number + 1
print(number)
return number
def get_collatz():
number = int(input('Put in a number please!: '))
while number != 1:
print(number)
collatz(number)
get_collatz()

Asking only for a hint is not really how stackoverflow questions are meant to be. But if a hint you want, a hint you get :)
def get_collatz():
number = int(input('Put in a number please!: '))
while number != 1:
print(number)
collatz(number)
Your variable, number, is a simple integer. It changes its value only when you use an operation like
number = <something>
number += 2
Hint: You don't seem to use any of these operation inside your implementation of get_collatz(). Not other than the initial input, at least :).

Related

Does (n%2==1) always convey that n is a odd number?

I had recently had a problem with (n%2==1).
The problem was to calculate the number of even and odd numbers in an array. When I tried the above mentioned condition in my code it resulted in a wrong answer. But when I changed it to (n%2==0) it was accepted. Can anyone help me on this?
The code in Python:
n = int(input())
ct = 0
a = [int(i) for i in input().split()]
for i in a:
if((i%2)==1):
ct+=1
ct1 = n-ct
print(ct,ct1)
In your current code, you are printing the output as
oddNumberCount evenNumberCount
But the problem wants you to print it as
evenNumberCount oddNumberCount
So when you switch it to n%2==0, i.e, check for even numbers, it gets accepted because that is the format the problem wants you to print the numbers in.

Locating prime numbers using for loop(s) in Python

So first of all, I realise there are much easier ways to get a list of prime numbers, but I'm just doing this to learn. I have a very poor understanding of a lot of this (as you'll see) so sorry if this is a dumb question. I'm trying to learn.
#make an empty list to store primes in
primes = list()
#make a variable to easily change the amount of numbers I test for primality
high_val = 15
#Allocate a range that I will test all numbers in for primality
for n in range(2, high_val):
#Within the previous for loop, start another for loop to test every integer against every
#value inside the primes list
for p in primes:
if n % p == 0:
print(%s is not prime" % n)
else:
#If n is prime, I add it to the list and print that it is prime
primes.append(n)
print("%s is a prime" % n)
I don't know if those comments make it harder to read, but that's my logic. There is no print output for the function. So I figured, there's just no value in primes, I need to give it something to compare to. So I added a primes.append(2) at the start immediately after the first line, and changed the range to (3, high_val)...
If I do that, it ends up printing about 5 times for every number that it is prime and 5 more messages saying it is not prime. Clearly I'm doing something massively wrong, if anyone knows where I went wrong and/or how to fix this that would be greatly appreciated. Thanks!
The thing is that you are missing some flags: you are printing if the number is prime every time you check it against another number. You should print it only after iterating over all primes.
About this, consider using all:
primes = [2]
high_val = 15
for n in range(3, high_val, 2):
if all(n % p == 0 for p in primes):
print(f"{n} is prime")
primes.append(n)
else:
print(f"{n} is not prime")
ps: I didn't test it.

How to give a Subclip a new name in Python using PyAutoGUI?

Complete beginner here making my first program with PyAutoGui as I cannot get access to the software's API. My issues are currently being that I am unable to come up with a solution to name each subclip with a different appended letter on the end. The naming convention should go like so, MI899001~AA, MI899001~AB, MI899001~AC, MI899001~AD. The only thing that changes is the last letter.
Below is the relevant code I'm currently using for the program I am writing;
def naming_promo():
x = string.ascii_uppercase
pyautogui.typewrite('DNH~P336007A' + x[0][0])
for i in range(7):
if i == 0:
sub_clip_clean()
else:
if i >= 1:
pyautogui.typewrite('567890qwe', 0.2)
sub_clip_package()
naming_promo() # See above Fn for method
pyautogui.moveTo(646, 404, duration=0.50)
pyautogui.click()
move_clips()
The naming_promo() takes the ascii_uppercase and types the first letter. I however can't figure out how to iterate through each character in the string as the For Loop repeats. I've googled many solutions, but I guess I can't get my head around how to do a loop in a loop and increment the x value used each time.
This is my first post so apologies for any etiquette I break. Any help and explanation would be greatly appreciated.
This is my first answer so apologies for any etiquette I break.
I'm not sure I understand everything here, since there's a few functions in the code that I don't know about. However, are you just looking for something like:
def naming_promo(n):
x = string.ascii_uppercase
pyautogui.typewrite('DNH~P336007A' + x[0][n])
and further down in your code, simply create a variable and increment it up one after use:
m = 0
for i in range(7):
if i == 0:
sub_clip_clean()
else:
if i >= 1:
pyautogui.typewrite('567890qwe', 0.2)
sub_clip_package()
naming_promo(m) # See above Fn for method
m += 1
pyautogui.moveTo(646, 404, duration=0.50)
pyautogui.click()
move_clips()

Can someone help me with my Goldbach code ? When i call the function and then put 1,000,000 it seems not to spit out any output i dont know why?

I need to reach 1,000,000 and for some reason it doesn't give me the output for 1,000,000, I don't know what i am doing wrong. Every time i put a small number like 500 it would give me the correct output but as soon as i put 999,999 or 1,000,000 it just doesn't give out any output and when i do a keyboard interruption it says it stopped at break but I need that break in order for the values to only repeat once.
bachslst=[]
primeslst=[]
q=[]
newlst=[]
z=[]
def goldbach(limit):
primes = dict()
for i in range(2, limit+1):
primes[i] = True
for i in primes:
factors = range(i, limit+1, i)
for f in factors[1:]:
primes[f] = False
for i in primes:
if primes[i]==True:
z.append(i)
for num in range(4,limit+1,2):
for k in range(len(z)):
for j in z:
if (k + j ) == num :
x=(str(k),str(j))
q.append(x)
newlst.append([x,[num]])
break
bachslst.append(num)
print(bachslst,'\n')
return newlst
The break that is referred to is not the break in the code, it is the break caused by the keyboard interrupt.
If you want to get your result in less than 1.5 hours, try to reduce the amount of computing that you are doing. There are many implementations for testing the Goldbach Conjecture if you do a search. Some are in other languages, but you can still use them to influence your algorithm.
I have not looked at it, but here is another implementation in Python: https://codereview.stackexchange.com/questions/99161/function-to-find-two-prime-numbers-that-sum-up-to-a-given-even-number

make a function that take an integer and reduces it down to an odd number

I'm working on my final for a class I'm taking(Python 3) im stuck at this part.
he gave us a file with numbers inside of it. we opened it and add those numbers to a list.
"Create a function called makeOdd() that returns an integer value. This function should take in any integer and reduce it down to an odd number by dividing it in half until it becomes an odd number.
o For example 10 would be cut in half to 5.
o 9 is already odd, so it would stay 9.
o But 12 would be cut in half to 6, and then cut in half again to 3.
o While 16 would be cut to 8 which gets cut to 4 which gets cut to 2 which gets cut to 1.
 Apply this function to every number in the array. "
I have tried to search the internet but i have not clue where to even begin with this one. any help would be nice.
Here my whole final so far:
#imports needed to run this code.
from Final_Functions import *
#Defines empty list
myList = []
sumthing = 0
sortList = []
oddList = []
count = 0
#Starts the Final Project with my name,class, and quarter
intro()
print("***************************************************************",'\n')
#Opens the data file and reads it then places the intrager into a list we can use later.
with open('FinalData.Data', 'r') as f:
myList = [line.strip() for line in f]
print("File Read Complete",'\n')
#Finds the Sum and Adverage of this list from FinalData.Data
print("*******************sum and avg*********************************")
for oneLine in myList:
tempNum = int(oneLine)
sumthing = sumthing + tempNum
avg = sumthing /1111
print("The Sum of the List is:",sumthing)
print("The Adverage of the List is:",avg,'\n')
print("***************************************************************",'\n')
#finds and prints off the first Ten and the last ten numbers in the list
firstTen(myList)
lastTen(myList)
print("***************************************************************",'\n')
#Lest sort the list then find the first and last ten numbers in this list
sortList = myList
sortList.sort()
firstTen(sortList)
lastTen(sortList)
print("****************************************************************",'\n')
Language:Python 3
I don't want to give you the answer outright, so I'm going to talk you through the process and let you generate your own code.
You can't solve this problem in a single step. You need to divide repeatedly and check the value every time to see if it's odd.
Broadly speaking, when you need to repeat a process there are two ways to proceed; looping and recursion. (Ok, there are lots, but those are the most common)
When looping, you'd check if the current number x is odd. If not, halve it and check again. Once the loop has completed, x will be your result.
If using recursion, have a function that takes x. If it's odd, simply return x, otherwise call the function again, passing in x/2.
Either of those methods will solve your problem and both are fundamental concepts.
adding to what #Basic said, never do import * is a bad practice and is a potential source of problem later on...
looks like you are still confuse in this simple matter, you want to given a number X reduce it to a odd number by dividing it by 2, right? then ask yourself how I do this by hand? the answer is what #Basic said you first ask "X is a even number?" if the answer is No then I and done reducing this number, but if the answer is Yes then the next step dividing it by 2 and save the result in X, then repeat this process until you get to the desire result. Hint: use a while
to answer your question about
for num in myList:
if num != 0:
num = float(num)
num / 2
the problem here is that you don't save the result of the division, to do that is as simple as this
for num in myList:
if num != 0:
num = float(num)
num = num / 2

Resources