While loop in Python converting integer to a string? - string

So I can't seem to get this. Without the 'while' loop this code works fine but as soon as I apply the loop it stops working right. From some reason it's treating x as a string. Like if x were 2 it would print y as '2222' instead of 16. I'm still new at this can someone tell my why? Thanks!
go = 'y'
while go == 'y':
print('enter x')
x = input()
y = x * 4
print(y)
print('go again?')
go = input()

Python 3's input function always returns a string. This is a change from Python 2, where input returned different kinds of Python objects depending on what was entered by the user. Python 3's version is equivalent to Python 2's raw_input.
With that background in mind, it's easy to fix your code. Just call the int constructor to turn your string into an integer. Or if you want to support non-integer values (like 1.4), use float instead.
As an aside, as your code is currently formatted in the question, it has an infinate loop. Is your logic to change the go variable really at top level? If so, it won't ever change during the loop, which will run forever.

This is actually dependent on your python version. input will automatically convert your string to an integer if it finds one. To prevent this, use the raw_input function in python < 3. For python 3 and above I believe this is the default behavior.

Related

Hashing a tuple not matching the expected value in python

I am trying to solve the below problem:
Given an integer, n , and n space-separated integers as input, create a tuple, t , of those n integers. Then compute and print the result of hash(t).
I am using python 3.
My code is
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
t = tuple(integer_list)
print(hash(t))
The expected output is 3713081631934410656 but I am getting -3550055125485641917. I think my code is correct. Why am i getting a different output?
If I am using Pypy3, I am getting the correct output 3713081631934410656 but not with Python 3
Python doesn't promise that tuple hashing will produce any particular output. There is no such thing as the "correct" output for hash(some_tuple). The tuple hash implementation is free to change, and it has changed in Python 3.8.
Your assignment was likely written for a different Python version than the one you're testing on, without consideration of the fact that the tuple hash algorithm is an implementation detail.

Problem with the output of an exponential calculation

I tried to calculate an exponential calculation, I tried both ways, writing it with the normal ** operator and the pow() function.
If I directly use numbers, everything works completely fine. But as soon as I use variables which get their value from input() functions the result is rounded, although I use the float argument.
I am quite new to coding, so please don't go to hard on me.
Code below:
pow(1.05,5), everything fine, result is 1.2762815625 and so on
float(pow(int(a),int(b)) the result is just 1.0, although it should be the same as above.
it is because you are doing the power operation on int i.e first you are converting the 1.05 to 1 by doing int(1.05) and then calculating the power(). you need to apply pow() on float()
print(float(pow(float(1.05),float(5))))
or either
print(pow(float(1.05),float(5)))
The reason the float function returns 1.0 is because of how it deals with integers.
For example:
integer = 5.5236734
print(float(integer))
The above code's output will be:
5.5236734
Now lets say you make some changes:
integer = 5.5236734
print(int(integer))
First, we made integer a decimal number, and then we said to print the int() form of the decimal.
This will be the result:
5
So, to fix your code, you just need to do this:
a = 1.05
b = 5
print(float(pow(a, b)))
Which will output:
1.2762815625000004
Hope this helps!

Is the 'for loop' for x used in this code a valid substitute for while x<=num?

I am trying to solve this problem of displaying prime numbers upto a specified number.
While I have the standard solution for it. I first tried to solve it myself and ended up writing this code. But I'm not getting the desired output. The standard solution uses the while loop as the main loop. And if that's the ideal loop for this example, why would that be so ?
def count_primes(num):
my_primes=[2]
if num<2:
return 0
for x in range(3,num+1,2):
for y in range(3,x+1):
if x%y==0:
break
else:
my_primes.append(x)
return my_primes
count_primes(100)
I expected a list of all prime numbers up to 100. Instead the output displayed only [2]. My guess is that the 'break' keyword broke out of the entire loop instead of only the if loop.
In your second for loop change range(3,x+1) to range(3,x), since your loop goes until y=x and x%x is always 0.

Connect string value to a corresponding variable name

This question has somehow to do with an earlier post from me. See here overlap-of-nested-lists-creates-unwanted-gap
I think that I have found a solution but i can't figure out how to implement it.
First the relevant code since I think it is easier to explain my problem that way. I have prepared a fiddle to show the code:
PYFiddle here
Each iteration fills a nested list in ag depending on the axis. The next iteration is supposed to fill the next nested list in ag but depending on the length of the list filled before.
The generell idea to realise this is as follows:
First I would assign each nested list within the top for-loop to a variable like that:
x = ag[0]
y = ag[1]
z = ag[2]
In order to identify that first list I need to access data_j like that. I think the access would work that way.
data_j[i-1]['axis']
data_j[i-1]['axis'] returns either x,y or z as string
Now I need to get the length of the list which corresponds to the axis returned from data_j[i-1]['axis'].
The problem is how do I connect the "value" of data_j[i-1]['axis'] with its corresponding x = ag[0], y = ag[1] or z = ag[2]
Since eval() and globals() are bad practice I would need a push into the right direction. I couldn't find a solution
EDIT:
I think I figured out a way. Instead of taking the detour of using the actual axis name I will try to use the iterator i of the parent loop (See the fiddle) since it increases for each element from data_j it kinda creates an id which I think I can use to create a method to use it for the index of the nest to address the correct list.
I managed to solve it using the iterator i. See the fiddle from my original post in order to comprehend what I did with the following piece of code:
if i < 0:
cond = 0
else:
cond = i
pred_axis = data_j[cond]['axis']
if pred_axis == 'x':
g = 0
elif pred_axis == 'y':
g = 1
elif pred_axis == 'z':
g = 2
calc_size = len(ag[g])
n_offset = calc_size+offset
I haven't figured yet why cond must be i and not i-1 but it works. As soon as I figure out the logic behind it I will post it.
EDIT: It doesn't work for i it works for i-1. My indices for the relevant list start at 1. ag[0] is reserved for a constant which can be added if necessary for further calculations. So since the relevant indices are moved up by the value of 1 from the beginning already i don't need to decrease the iterator in each run.

Find all possible variations of a string of letters

Newb programmer here, I'm most familiar with Python but also learning C and Java, so either of 3 would be fine.
What I have is a string of letters, say:
ABXDEYGH
However say,
X is possible to be M and N.
Y is possible to be P and Q.
In this example, I would like basically to print all possible variations of this string of letters.
Like:
ABMDEPGH
ABNDEPGH
ABMDEQGH
ABNDEQGH
Any help would be appreciated. Thanks in advance
This boils down to a simple problem of permutations. What you care about is the part of the text that can change; the variables. The rest can be ignored, until you want to display it.
So your question can be more simply stated: What are all the possible permutations of 1 item from set X and another item from set Y? This is known as a cross-product, sometimes also simply called a product.
Here's a possible Python solution:
import itertools
x = set(['M', 'N'])
y = set(['P', 'Q'])
for items in itertools.product(x, y)
print 'AB{0}DE{1}GH'.format(*items)
Note that the print ''.format() command uses the "unpack arguments" notation described here.
why dont you write two loops. one to replace all possible characters with X and one for Y.
foreach(char c in charSet1){
// replaces X
foreach(char ch in charSet2){
// replace Y
}
}

Resources