How do I achieve this following function only using while loop? - python-3.x

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

Related

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!

Brute Force Hacker Concept in Python 3

The code that i currently have will list all possible combinations
from itertools import product
password = "hr"
chars = 'abcdefghijklmnopqrstuvwxyz' #characters to look for, can have letters added
for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
print(''.join(attempt))
What i need it to do is take each tried attempt and compare it with the variable "password", if it matches break out of the for loop else carry on, any ideas?
One thing you could do to solve this would be to move your whole for length in range code block into a function:
def brute_force(chars, password):
for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
if ''.join(attempt) == password:
print("Found the password!")
return
The problem you're having is that you can only break out of a single loop. There's no built-in solution to say "break out of this loop, and its parent, and nothing else." I find that if you're unable to be using break or continue to move your control flow in the desired direction, just break it off into a function and use return.
This isn't really a problem, necessarily, but chars you're using right now will only ever be able to brute-force an all-letters, all-lower-case string, so it'll go through every single attempt and fail if the password is "Hr".

using a looop to add user input to the set and dict in order discovered

So I'm trying to write a small program that does a few things. First is:
Write a while loop that repeatedly creates a list of words from a line of input from the user. So I did this:
s = input("Please enter a sentence: ")
while True:
pos = 0
for c in s:
if c == " ":
print(s[:pos])
s = s [pos+1:]
break
pos += 1
else:
print(s)
break
I need to add the user inputted words to the set and dict and then display their value in the order in which the program discovered them. I believe I need another loop but I'm not sure. I'm pretty lost at this point and the above is as far as I can seem to come on this program. Any help is appreciated as I am (obviously)new at python.

Resources