While loop creating - python

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

Related

Palindrome numberr

I was making research on writing a code to check for Palindrome number in Python and I came across this
class Solution:
def isPalindrome(self, x: int) -> bool:
rev = 0
init_n = x
if (x < 0):
return False
while x != 0:
rev = (rev * 10) + x % 10
x = x // 10
if (rev == init_n):
return True
Question: Please can someone explain the while x!=0: loop for me
While I agree your question could use some extra clarification, or you don't quite understand the code you posted. Here's an explanation. Say we start x = 123
The code:
while x != 0:
rev = (rev*10) + x % 10
x = x // 10
rev = reverse and x is our start number and the edited versions we create as we go.
Each iteration does the following
The first line takes our previous rev and opens up the ones digit before adding the ones digit from the end of x's list. This is done via the mod operator in python which returns the remainder of a number. When applied with the number 10 what is left is the ones digit. Next, we remove our ones digit of x by using floor division which is division that ignores any remainder.
Using the case of x=123, the first iteration sets rev = 3 and x = 12, the second iteration sets rev = 32 and x = 1, the third rev = 321 and x = 0. Which breaks the loop. This is important as it returns the exact reverse of x, which is then compared to x in the last if statement.

How do you mulitply via addition?

I'm having trouble trying to
compute x * y using only addition, printing the intermediate result for each loop iteration, and
printing the final number. This is my
teacher's example of what the output should look like
I could really use some help figuring it out,, I don't really understand how to yet.
Edit: I am a first time coder so I'm not very skilled, I do know the basics though (Also very new to this website) Here's what my code looks like so far:
x = int(input("Input positive x: "))
y = int(input("Input positive y: "))
z = 0
w = 0
if x < 0:
exit("Please input a positive number for x")
if y < 0:
exit("Please input a positive number for y")
def multiplier(number, iterations):
for i in range(1, iterations):
number = number + 3
print(number) # 12
multiplier(number=3, iterations=4)
My answer. Little shorter than the others.
Ok, try thinking of multiplication as adding a number with itself by x times. Hence, 3*4 = 3+3+3+3 = 12, which is adding 3 by itself 4 times
Replicating this with a for loop:
#inputs
x = 3
y = 4
#output
iteration = 1
result = 0
for num in range(4):
result += x
print(f'Sum after iteration {iteration}: {result}')
iteration += 1 #iteration counter
The resulting output will be:
Sum after iteration 1: 3 Sum after iteration 2: 6 Sum after iteration
3: 9 Sum after iteration 4: 12
The code is simple and straightforward,Check which number is bigger and iterate according to that number.
x = 3
y = 4
out = 0
if x > y:
for v in range(0,x):
out += y
print("after iteration",v+1, ":", out)
if y > x:
for v in range(0,y):
out += x
print("after iteration",v+1, ":", out)
print(x,"*", y, "=", out)
Use print to print inside the loop to show each number after adding and the number of iteration occurs.
Here is a start. This assume both arguments are integers 0 or more:
def m(n1, n1a):
n1b = 0
while n1a > 0:
n1b += n1
n1a -= 1
return n1b
n = m(9, 8)
print(n == 72)

Infinite while loop in Python (finding prime number and GCD)

I am currently trapped by a infinite loop in my program and I really don't know what is the fault in it.
Here is my code:
from reference import brute_prime, euclid_gcd, extended_euclid
def rsa(min_p, min_q, min_e):
p = brute_prime(min_p)
q = brute_prime(min_q)
n = p * q
phi = (p - 1) * (q - 1)
e_prime = brute_prime(min_e)
while euclid_gcd(e_prime, phi) != 1:
e_prime = brute_prime(min_e)
print(e_prime)
e_prime += 1
return e_prime
#d = extended_euclid(e_prime, phi)
#tup1 = (d, e_prime, n)
#return tup1
My aim here is to use brute_prime and euclid_gcd to find e, by iteratively finding the next smallest prime number e_prime using brute_prime, and testing whether gcd(e′,ϕ)=1. If successful, terminate, if not, increment e_prime and continue.
Note that these functions that I called are all imported and there is nothing wrong in the function. What is wrong?
EDIT:
When trying to see the result of each iteration I tried something like this
print(rsa(11, 13, 3))
And the loop gives me 3 every single time.
EDIT:
This is brute_prime
def brute_prime(number):
#Making sure that the input from number will be type int
#setting two convenient limits for future use in the loop
number = int(number)
point_begin = 2
point_end = int((number**0.5)) + 1
#Two specific exceptions in the function that will execute and ignores
#later commands so that it is a tiny bit more efficient...
if number == 2:
return 2
elif number == 1:
return 1
while True:
condition = True
for i in range(point_begin, point_end):
if number % i == 0:
condition = False
break
if condition:
return number
else:
number += 1
EDIT:
This is Euclid_gcd
def euclid_gcd(num1, num2):
while num2:
num1, num2 = num2, num1 % num2
return int(num1)
Your while loop in RSA function looks buggy as min_e is not being updated, so same value is used in each iteration thus the loop is stuck, check your logic.
or use this:
while euclid_gcd(e_prime, phi) != 1:
e_prime = brute_prime(min_e)
min_e = e_prime + 1 # check for next prime-number co-prime to phi
Also note, 1 is not prime. For 1 as input, brute_prime should return 2.
Perhaps unrelated, but why not do something like
e_prime = brute_prime(min_e)
#This loop will not calculate and return me e_prime.
#Instead it just keeps running and exits later with nothing.
while euclid_gcd(e_prime, phi) != 1:
e_prime = brute_prime(min_e)
e_prime += 1
return e_prime

Generating Perfect Squares python

I am trying to write the simplest code possible that will continuously print out Perfect Squares. My code so far reads this
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
When I run it, I get a syntax error. The red bit is on the "final" in "print final"
Apologies if it is a really basic error, but I'm stumped.
Thanks for taking the time to read this
I assume you're using Python 3. print is now a function in Python 3.
Do print(final) instead of print final.
Also, it seems like your x and y values are holding the same thing. Why not discard one of them and use just one?
x = 1
while True:
final = x * x
print(final)
x = x + 1
Or better yet, use the builtin exponentiation operator **.
x = 1
while True:
final = x **2
print(final)
x += 1
Also, your code seems to be going into an infinite loop. You may need a condition to break it.
For example, if you want to break when x reaches 10, just add a condition in the while loop, like follows:
x = 1
while True:
final = x **2
print(final)
x += 1
if x == 10:
break
OR Specify a condition in the whilestatement, like follows:
x = 1
while x < 10:
final = x **2
print(final)
x += 1
OR Use a for loop.
for i in range(10):
print(i**2)
In Python 3, print is no longer a statement but a function, so you must enclose what you want to print in parentheses:
print(final)
Here's a link about the function.
You also have an IndentationError, y = y + 1 should be given a space.
And you can simplify that to y += 1 (which is the same thing, in regards to integers)
You can also add a condition to the while-loop:
x = 0
while x < 5:
print x ** 2
x += 1
Prints:
0
1
4
9
16
I would reccomend using Python 3 if you're not already. Also, as x and y are the same value at all times you only need one of them. So instead of reading:
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
You should write:
x = 1
while True:
final = x * x
print(final)
x = x + 1
Hope this helped!
Jake.

python lists append

I was about to code a program which evaluates a polynomial. But the code below is just a try-out for that. The code below gives an output that stops when "counter = t"... I want it to give an output up to when counter=0. How can that be? I wanted to treat every number(input) as a coefficient of the polynomial. If I was successful doing this, I'm planning to make a list then for every, say, element in the list, I will then multiply it to a certain number raised to its index then add them up so that I've evaluated a polynomial.. Am I clear? And will my plan work out?? Thank you so much.. Please help..
t = input("Enter degree of Polynomial: ")
while t < 0:
print ("Not possible! ")
t = input("Enter degree of Polynomial: ")
counter = 0
while counter < t:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
counter += 1
THe ouput goes like this:
Enter degree of polynomial: 5
n: 5
3125
n:4
256
n:3
27
then it ends.. it should continue asking for an input n up to five times..
Try to use raw_input() and keep in mind that raw_input() returns always a string. So you have to convert the returned string to an integer like:
>>> x = int(raw_input("foo: "))
Then it is possible to test something like x > 2 etc. Without casting to integers the following would happen:
>>> "2" > 1
True
>>> "2" > 3
True
First of all: Well done - it's only a little mistake: Remove the "syntactic whitespace" in your last line, or remove it completly
Secondly: Don't forget to add the values ;-) - and with regards to your headline, this is best done with a python list.
The problem seems (to me) that you are having the loop depend on 2 variables, where you perhaps expected it to be only dependent on 1.
Perhaps this works a little better:
while t > 0:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
Something like this?
while True:
degree = int(raw_input("Enter degree of Polynomial: "))
if degree >= 0:
break
print ("Not possible!")
x = float(raw_input("x = "))
y = 0.0
for exponent in reversed(range(degree)):
k = float(raw_input("k[{0}] = ".format(exponent)))
y += k * (x ** exponent)
print("y = ", y)
This solves a polynomial of the form:
y = (k[N-1] * (x ^ N-1) + (k[N-2] * (x ^ N-2) + ... + k[0]

Categories

Resources