Im trying to write a program that has 2 variables (Integer) and that based on those variables print´s them joined and by order (Smaller number to Higher):
Like this:
together((0,39,100,210),(4,20))
printing the following:
(0,4,20,39,100,210)
The code:
def together(s,t):
y = s + t
z = 0
if sorted(y) == y:
print (y)
else:
for i in range(len(y)-1):
if y[z] > y[z+1]:
y[z+1] = y[z]
return (y)
print y
If variables are set like the following:
s=1,23,40 and t=9,90
I´m getting this:
(1, 23, 40, 9, 90)
which is out of order as you can see it should appear the following:
(1,9,23,40,90)
Why not just append both tuples and then sort them:
def together(s,t):
return tuple(sorted(s + t))
T = ((0,39,100,210),(4,20))
print tuple( sorted( reduce(tuple.__add__, T) ) )
This can combine and sort N number of tuples within a tuple, so it's not limited to two tuples
Related
I know this is a dummy question, but I didn't find the answer here the way I had in mind
I just want to know if I can apply multiple filters within a single filter function
A simple code to try it:
def check_odd(x):
return (x % 2) == 0
l1 = list(range(1,20))
list(filter((check_odd and lambda x:x>=5), l1))
Using the code above only one of the filters is applied (the 2nd).
I solved it using:
list(filter(check_odd, filter(lambda x:x>=5, l1)))
But I wonder if there is a way to group all filters in filter function.
Just transform the and inside the lamda, and combine your conditions there:
def check_odd(x):
return (x % 2) == 0
l1 = list(range(1,20))
l2 = list(filter((lambda x:x>=5 and check_odd(x)), l1))
print(l2)
Update
You can actually combine any number of conditions from other functions by wrapping them all inside the lambda. Here's an example:
def check_odd(x):
return (x % 2) == 0
def check_greater_than_five(x):
return x >= 5
def check_divisible_by_three(x):
return x % 3 == 0
l1 = list(range(1,20))
l2 = list(filter((lambda x: (check_odd(x) or check_divisible_by_three(x)) and check_greater_than_five(x)), l1))
print(l2) #prints all numbers that are greater than five, and are divisible by either 2 or 3
Took a large data set, removed any numbers that are not within 2 SD from a specific column and created an array, now I want to remove any numbers not in array from columns without messing up index. Would preferably like to convert any non-present numbers as nan.
Code used to remove values outside of 2 SD:
pupil_area_array = numpy.array(part_data['pupil_area'])
mean = numpy.mean(part_data['pupil_area'], axis=0)
sd = numpy.std(part_data['pupil_area'], axis=0)
final_list = [x for x in part_data['pupil_area'] if (x > mean - 2 * sd)]
final_list = [x for x in final_list if (x < mean + 2 * sd)]
print(final_list)
If you are not restricted to using a generator, you should be able to use map() https://www.geeksforgeeks.org/python-map-function/:
def filter_sd(value):
if x > mean - 2 * sd:
return x
return None #or return 'Nan'
final = map(filter_sd, part_data['pupil_area'])
I apologise for the terrible description and if this is a duplicated, i have no idea how to phrase this question. Let me explain what i am trying to do. I have a list consisting of 0s and 1s that is 3600 elements long (1 hour time series data). i used itertools.groupby() to get a list of consecutive keys. I need (0,1) to be counted as (1,1), and be summed with the flanking tuples.
so
[(1,8),(0,9),(1,5),(0,1),(1,3),(0,3)]
becomes
[(1,8),(0,9),(1,5),(1,1),(1,3),(0,3)]
which should become
[(1,8),(0,9),(1,9),(0,3)]
right now, what i have is
def counter(file):
list1 = list(dict[file]) #make a list of the data currently working on
graph = dict.fromkeys(list(range(0,3601))) #make a graphing dict, x = key, y = value
for i in list(range(0,3601)):
graph[i] = 0 # set all the values/ y from none to 0
for i in list1:
graph[i] +=1 #populate the values in graphing dict
x,y = zip(*graph.items()) # unpack graphing dict into list, x = 0 to 3600 and y = time where it bite
z = [(x[0], len(list(x[1]))) for x in itertools.groupby(y)] #make a new list z where consecutive y is in format (value, count)
z[:] = [list(i) for i in z]
for i in z[:]:
if i == [0,1]:
i[0]=1
return(z)
dict is a dictionary where the keys are filenames and the values are a list of numbers to be used in the function counter(). and this gives me something like this but much longer
[[1,8],[0,9],[1,5], [1,1], [1,3],[0,3]]
edits:
solved it with the help of a friend,
while (0,1) in z:
idx=z.index((0,1))
if idx == len(z)-1:
break
z[idx] = (1,1+z[idx-1][1] + z[idx+1][1])
del z[idx+1]
del z[idx-1]
Not sure what exactly is that you need. But this is my best attempt of understanding it.
def do_stuff(original_input):
new_original = []
new_original.append(original_input[0])
for el in original_input[1:]:
if el == (0, 1):
el = (1, 1)
if el[0] != new_original[-1][0]:
new_original.append(el)
else:
(a, b) = new_original[-1]
new_original[-1] = (a, b + el[1])
return new_original
# check
print (do_stuff([(1,8),(0,9),(1,5),(0,1),(1,3),(0,3)]))
I am trying to create a list of numbers from a function and a for-loop. Here is a copy of my code:
Rh = 1096776000000
print "What is your value for 'n'?"
n = float(raw_input(">"))
m = range(int(n+1), int(n+21))
def wavelength(a,b):
list = [((1 / (Rh * ((1 / (a**2)) - (1 / (float(x)**2))))) * 10 ** 14)
for x in b]
return list
for elements in wavelength(n,m):
print "%.3f" % elements, 'nm'
This will print out what I want, but I need to take all of the data points and put them into a list. Any ideas?
I guess you're in need of something like this:
l = [] # An empty list
for elements in wavelength(n,m):
l.append("%.3f" % elements, 'nm') # Adding rounded values to the list
print l # Print the full list
results = ["%.3f nm" % elements for elements in wavelength(n,m)]
This is a simple program but I am finding difficulty how it is actually working.
I have database with 3 tuples.
import matplotlib.pyplot as plt
queries = {}
rewrites = {}
urls = {}
for line in open("data.tsv"):
q, r, u = line.strip().split("\t")
queries.setdefault(q,0)
queries[q] += 1
rewrites.setdefault(r,0)
rewrites[r] += 1
urls.setdefault(u,0)
urls[u] += 1
sQueries = []
sQueries = [x for x in rewrites.values()]
sQueries.sort()
x = range(len(sQueries))
line, = plt.plot(x, sQueries, '-' ,linewidth=2)
plt.show()
This is whole program,
Now
queries.setdefault(q,0)
This command will set the values as 0 , if key i,e and q is not found.
queries[q] += 1
This command will increment the value of each key by 1 if key is there.
Same we continue with all tuples.
Then,
sQueries = [x for x in rewrites.values()]
Then we store the values from Dictionary rewrites , to List Squeries
x = range(len(sQueries))
This command I am not getting what is happening. Can anyone please explain.
len(sQueries)
gives number of elements in your list sQueries
x = range(len(sQueries))
will create a list x containing elements from 0,1,... to (but not including) length of your sQueries array
This:
sQueries = []
sQueries = [x for x in rewrites.values()]
sQueries.sort()
is an obtuse way of writing
sQueries = rewrites.values()
sQueries = sorted(sQueries)
in other words, sort the values of the rewrites dictionary. If, for the sake of argument, sQueries == [2, 3, 7, 9], then len(sQueries) == 4 and range(4) == [0, 1, 2, 3].
So, now you're plotting (0,2), (1,3), (2,7), (3,9), which doesn't seem very useful to me. It seems more likely that you would want the keys of rewrites on the x-axis, which would be the distinct values of r that you read from the TSV file.
length = len(sQueries) # this is length of sQueries
r = range(length) # this one means from 0 to length-1
so
x = range(len(sQueries)) # means x is from 0 to sQueries length - 1