How to repeat an iteration with the same amount of jump - python-3.x

Wish you are all well.
I am super new in Python and at the moment am having a difficulty to construct a solution for the problem I am having, I doubt I could present the problems correctly but here goes:
I have to make a variable with the name current position and init value of 0 and should be incremented by the number of jump.
I have to make two variables that receive integer input. Jump and Target.
I have to define the number range, between 0 to 9, so range(0, 10).
The jump defines how many number does the code have to skip when it starts to iterate.
The target is the number of which when the jump lands on it, it will exit the loop.
For example, if the target is number 1 and the jump is 2, it means, in the first jump, it will skip the target. And it will continue to do so until it lands on 1.
The problem is, I could not figure out what the problem is.
Here is my humble code...
jump = int(input())
target = int(input())
current_position = 0
for i in range(0, 10):
current_position += jump
if jump == target:
print(current_position, end=" ")
I really need some advise here, please.
Thank you.

The series/range you have is increasing and there no indication or point in your requirements about a decrement, so not sure how last number will go to 0.
Please refer to code below, see if this is something you are looking for -
jump = int(input("Enter value for jump -> "))
target = int(input("Enter value for target -> "))
current_position = 0
for current_position in range(jump,10, jump):
print (current_position)
if current_position == target:
print ('Target found and current position = ', current_position)
break
elif (current_position == len(range(0,10))-jump):
print ('Target not found.')
break
else:
continue

Related

Polydivisible Calculator Fails, Despite Previous Implementation Working

To begin, a definition:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
1 % 1 == 0
14 % 2 == 0
141 % 3 == 0
I'm working on a recursive polydivisible checker, which, given a number, will check to see if that number is polydivisible, and if not, recursively check every other number after until it reaches a number that is polydivisible.
Unfortunately, my code doesn't work the way I want it to. Interestingly, when I input a number that is already polydivisible, it does its job and outputs that polydivisible number. The problem occurs when I input a non-polydivisible number, such as 13. The next polydivisible number should be 14, yet the program fails to output it. Instead, it gets stuck in an infinite loop until the memory runs out.
Here's the code I have:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
I'm assuming the problem occurs in the else statement inside the while loop, where, if the number fails to be polydivisible, the program resets i to 0, and adds 1 to the original number so it can start checking the new number. However, like I explained, it doesn't work the way I want it to.
Any idea what might be wrong with the code, and how to make sure it stops and outputs the correct polydivisible number when it reaches one (like 14)?
(Also note that this checker is only supposed to accept non-negative numbers, hence the initial if conditional)
The mistake is that you are no updating number after incrementing num.
Here is working code:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
I have a similar answer to #PranavaGande, the reason is I did not find any way to iterate an Int. Probably because there isn't one...Duh !!!
def is_polydivisible(n):
str_n = str(n)
list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True
Now, I apologise for this many lines of code as it has to be smaller. However every integer has to be split individually and then divided by its index [Starting from 1 not 0]. Therefore I found it easier to list both of them and divide them index wise.
There is much shorter code than mine, however I hope this serves the purpose to find if the number is Polydivisible or Not. Of-Course you can tweak the code to find the values, where the quotient goes into decimals, returning a remainder which is Non-zero.

How do I achieve this following function only using while loop?

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

Python Collatz Infinite Loop

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

Multiplication table in Python with # on all even numbers

I am trying to create a python multiplication table from 2 - 10. If you enter an invalid number it will tell you that it is an invalid entry and ask you to input a number again. It is also supposed to put a # on all even numbers. I am having trouble continuing after an invalid entry and also putting a # on all even numbers. My current code is below
def main():
rows = int(input("What size multiplication table would you like (2-10): "))
if rows <=1 or rows >10:
print (" Invalid Entry - Enter a number between 2 - 10 ")
else:
counter = 0
multiplicationTable(rows,counter)
def multiplicationTable(rows,counter):
size = rows + 1
for i in range (1,size):
for nums in range (1,size):
value = i*nums
print(value,sep=' ',end="\t")
counter += 1
if counter%rows == 0:
print()
else:
counter
main()
I am typing this on my phone so bear with me.
Since you are trying to only get a certain input, you want to have a loop so that we can keep asking the user to enter a number if it is outside the range we want.
So in a generic example where we repeatedly ask a user for a certain input:
While True:
rows = int(input(“enter size: “))
if 1 <= rows < 10:
multiplicationTable(rows, 0)
break
else:
print(“Invalid”)
continue
While True: will run infinitely naturally. However, the magic is in the continue and break statements. continue will make it restart at the top of the loop and break will make it exit the loop after the process is done.
note:
Some programmers consider it bad practice to use the loops in this fashion because it could imply poor logic.
If you need help with an alternate solution I can try and help when I get to my computer.
Best of luck!

Python Counting the exchanges in a selection sort

I apologize as this is my first question on this site and it is extremely basic, but I am somewhat lost in a current lab I am trying to complete.
Currently I am attempting to count the amount of exchanges(Or swaps? Not sure on the right word there!) during a selection sort throughout the passes.
Now according to my current understanding, the replacement section of our formula is traversing my list. However, it doubles the amount of swaps it is actually supposed to be spitting back at me. Now this would lead me to believe an if statement might need to be operating in the outer loop, but that doesn't seem quite right to me.
An example of what I have done to cause this problem below. I am curious if I am on the right path or should I slash and burn or go back to the drawing board.
The reason I am counting them independently is I am displaying when there is a swap then a grand total of all the swaps. Which I find to be a bit ironic as with a selection sort you can only have 1 swap per pass?
Any case, I apologize for the rather basic question, but I seem to be missing something so I was hoping someone could point me in the right direction of if I should be focusing on the outer loop to determine the exchanges?
print( "Original list:" , a_list, "\n" )
count =1
n = len(a_list)
comp = n -1
exchanges=1
comp_total=0
exch_total=0
for end in range(n, 1, -1): # Each pass starts here
#Setting our running total to adjust for previous value.
comp_total +=comp-(count-1)
print("Pass", count, ":", "Comparisons:",comp-(count-1), "\tExchanges:", exchanges,"\n", end="\t ")
count += 1
# --- Search for Largest ---
min_position = 0
for i in range(1, end):
if a_list[i] > a_list[min_position]: # Perform n
min_position = i
exchanges = 0
exch_total +=1
else:
exchanges = 1
# --------------------------
temp = a_list [end - 1] # Perform exchange
a_list [end - 1] = a_list [min_position]
a_list [min_position] = temp
print(a_list)
print()
print("\tTotal Comparisons:",comp_total, "Total Exchanges:", exch_total)
selection_sort(a_list)
In this case,
My issue was the the fact my print statement was before the actual loop, this was throwing off my count, by placing the if statement past this point, I was able to get an accurate running total!
Cheers!

Resources