Python For loop variable syntax - python-2.7

I'm trying to make a for loop count up and print values from defined variables
Value1 = "X"
Value2 = "Y"
for x in range (1, 2):
print Valuex
So I want this print value1 then value2
What is the syntax for this?

Use an array (also don't start variable names with capital letters):
value = [ "X", "Y" ]
for x in range (0, 2):
print value[x]
Also you probably wanted two elements in your range.

A simple approach can be to put all values in list and then loop. e.g
values = ["X", "Y"]
for x in values:
print x
This will automatically avoid accessing invalid index. while using range you have to be careful to avoid exceptions.

Related

Find the the total number of 1's in binary form for a group number's in a list in python 3

I want to count total number of '1's in binary format of a number which is in a list.
z = ['0b111000','0b1000011'] # z is a list
d = z.count('1')
print(d)
The output is 0.
Whereas the required output should be in the form of [3,3]
which is number of ones in every element that Z is containing :
Here it is :
z=['0b111000','0b1000011']
finalData = []
for word in z:
finalData.append(word.count('1'))
print(finalData)
The problem with your code was you were trying to use count() method on list type and it is used for string. You first need to get the string from the list and then use count() method on it.
Hope this helps :)
z = ['0b111000','0b1000011']
d = z.count('1')
This attempts to find the number of times the string '1' is in z. This obviously returns 0 since z contains '0b111000' and '0b1000011'.
You should iterate over every string in z and count the numbers of '1' in every string:
z = ['0b111000','0b1000011']
output = [string.count('1') for string in z]
print(output)
# [3, 3]
list.count(x) will count the number of occurrences such that it only counts the element if it is equal to x.
Use list comprehension to loop through each string and then count the number of 1s. Such as:
z = ['0b111000','0b1000011']
d = [x.count("1") for x in z]
print(d)
This will output:
[3, 3]

Deleting duplicate x values and their corresponding y values

I am working with a list of points in python 2.7 and running some interpolations on the data. My list has over 5000 points and I have some repeating "x" values within my list. These repeating "x" values have different corresponding "y" values. I want to get rid of these repeating points so that my interpolation function will work, because if there are repeating "x" values with different "y" values it runs an error because it does not satisfy the criteria of a function. Here is a simple example of what I am trying to do:
Input:
x = [1,1,3,4,5]
y = [10,20,30,40,50]
Output:
xy = [(1,10),(3,30),(4,40),(5,50)]
The interpolation function I am using is InterpolatedUnivariateSpline(x, y)
have a variable where you store the previous X value, if it is the same as the current value then skip the current value.
For example (pseudo code, you do the python),
int previousX = -1
foreach X
{
if(x == previousX)
{/*skip*/}
else
{
InterpolatedUnivariateSpline(x, y)
previousX = x /*store the x value that will be "previous" in next iteration
}
}
i am assuming you are already iterating so you dont need the actualy python code.
A bit late but if anyone is interested, here's a solution with numpy and pandas:
import pandas as pd
import numpy as np
x = [1,1,3,4,5]
y = [10,20,30,40,50]
#convert list into numpy arrays:
array_x, array_y = np.array(x), np.array(y)
# sort x and y by x value
order = np.argsort(array_x)
xsort, ysort = array_x[order], array_y[order]
#create a dataframe and add 2 columns for your x and y data:
df = pd.DataFrame()
df['xsort'] = xsort
df['ysort'] = ysort
#create new dataframe (mean) with no duplicate x values and corresponding mean values in all other cols:
mean = df.groupby('xsort').mean()
df_x = mean.index
df_y = mean['ysort']
# poly1d to create a polynomial line from coefficient inputs:
trend = np.polyfit(df_x, df_y, 14)
trendpoly = np.poly1d(trend)
# plot polyfit line:
plt.plot(df_x, trendpoly(df_x), linestyle=':', dashes=(6, 5), linewidth='0.8',
color=colour, zorder=9, figure=[name of figure])
Also, if you just use argsort() on the values in order of x, the interpolation should work even without the having to delete the duplicate x values. Trying on my own dataset:
polyfit on its own
sorting data in order of x first, then polyfit
sorting data, delete duplicates, then polyfit
... I get the same result twice

Python - Number with a variable part

I have a number given in this form 623746xyz3 and i have to code a Python script that prints on screen all numbers that can be created with the combination of all values (from 0 to 9 ) that x,y,z can assume.
Can someone help me?
If those xyz are always next to each other, you can just loop from 0 to 999 and replace that part of the string accordingly.
s = "623746xyz3"
for xyz in range(1000):
sxyz = s.replace('xyz', str(xyz))
print int(sxyz)
In case the x, y, and z can be more 'spread out', you will need three nested loops:
for x in range(10):
sx = s.replace('x', str(x))
for y in range(10):
sxy = sx.replace('y', str(y))
for z in range(10):
sxyz = sxy.replace('z', str(z))
print int(sxyz)
(And in case you do not know the 'variables' a priori, you will first need to find the non-digit characters and use a recursive approach to replace them.)
My first idea:
for x in range(0, 10)
for y in range(0. 10)
for z in range (0, 10)
print 6*1000000000+2*100000000+3*10000000+7*1000000+4*100000+6*10000+x*1000+y*100+z*10+3

How to switch directly to the desired condition without checking other conditions in Python?

I have an python example code as:
Input: (x,y)
if x==0 and y==0:
print x+y+1
elif x==0 and y==y:
print x+y*y+2
elif x==x and y==0:
print x*x+y+3
else:
print x*x+y*y+4
How can I switch directly to the condition as, if my input is (x,y) = (0,0) it will output 1 without checking other conditions?
I tried this using dictionary as,
Input: (x,y)
def Case1():
print x+y+1
def Case2():
print x+y*y+2
def Case3():
print x*x+y+3
def Case4():
print x*x+y*y+4
dict = {(0,0): Case1,
(0,y): Case2,
(x,0): Case3,
(x,y): Case4,
}
dict[(x,y)]()
When I tried this with input (x,y) = (0,0), this gives me output as 4 instead of 1. It seems like, my code is checking only for the Case4. What I am doing wrong in the dictionary?
Thanks!
It seems that you do not quite understand how Python works. A dictionary is not a pattern matching block, as you have in Haskell or Erlang. It is a data structure with concrete values inside. You can try to write print dict after your definition and see what's inside it.
When you create your dict, current concrete values of x and y are used to create the keys. If x and y happen to be 0 at the time, the (0,0) key will be replaced by (x,y) (that's why in your case Case4 is called).
Bogdan explained why you can not use the variables x and y as keys into your dictionary. When they are both zero, all 4 keys will be (0,0) at definition time, so the dictionary only contains one case. You can probably achieve what you want by using the result of the tests on x and y as a key into the dictionary instead (untested):
case_dict = {(True, True): Case1,
(True, False): Case2,
(False, True): Case3,
(False, False): Case4,
}
case_dict[(x == 0, y == 0)]()
Note that you should not call a variable dict, since this is the name of a built-in type.
Say x=0 and y=0. Your final entry in the dict is (x,y):Case4, or 0,0, replacing any previous 0,0. Then you look up dict[x,y], or really dict[0,0] which calls Case4...this will happen regardless of what x,y is.
Stick to your original if. The code is clear, although you can make it simpler:
if x==0 and y==0:
print 1
elif x==0:
print y*y+2
elif y==0:
print x*x+3
else:
print x*x+y*y+4

iterate through paired values in dictionary

I have converted grid1 and grid2 into arrays and using following function which iterates through table and should return corresponding value form table when grid1 and grid2 values are matched. But somehow the final output contain only 4 integer values which isn't correct. Any suggestion what is possibly wrong here?
def grid(grid1,grid2):
table = {(10,1):61,(10,2):75,(10,3):83,(10,4):87,
(11,1):54,(11,2):70,(11,3):80,(11,4):85,
(12,1):61,(12,2):75,(12,3):83,(12,4):87,
(13,1):77,(13,2):85,(13,3):90,(13,4):92,}
grid3 = np.zeros(grid1.shape, dtype = np.int)
for k,v in table.iteritems():
grid3[[grid1 == k[0]] and [grid2 == k[1]]] = v
return grid3
I think what's happening is that the assignment to the variables "k" and "v" not done using "deepcopy". This means the assignment is just to the variables and not their values. For example, when the value of "k" changes on subsequent iterations, all previous "gridx" assignments now reflect the new/current status of "k".