Python - Number with a variable part - python-2.7

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

Related

nested list of lists of inegers - doing arithmetic operation

I have a list like below and need to firs add items in each list and then multiply all results 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6 then 6*1*7*(-6) = -252 I know how to do it by accessing indexes and it works (as below) but I also need to do it in a way that it will work no matter how many sublist there is
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]
def sum_then_product(list):
multip= a*b*c*d
return multip
print sum_then_product(nested_lst)
I have tried with for loop which gives me addition but I don't know how to perform here multiplication. I am new to it. Please, help
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
print sum(i)
Is this what you are looking for?
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output
for sublist in nested_lst:
sublst_out = 0
for x in sublist:
sublst_out += x # your addition of the sublist elements
output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)

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 remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s

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