I'm trying to generate the fibonacci series here. Not necessarily looking for an answer specific to that series but why the loop I've created here won't generate a list with upto 20 values for an input of '0'.
So far I've tried appending within and before the loop. The result I get is [0,1]. It doesn't seem to add to the list beyond that.
series = []
value = input("Enter an integer: \n")
i = int(value)
series.append(i)
if series[0] == 0:
series.append(1)
for i in series[2:20]:
series[i]=series[i-1]+series[i-2]
series.append(i)
print(series)
After doing series.append(1) you series values [0,1] only so series[2:20] == [] and you iterate on nothing and fill in nothing. And you cannot access an index that is not already allocated, so you can't do series[i] and you did not reach that index yet, you just need to append the values
if series[0] == 0:
series.append(1)
for i in range(2, 20):
series.append(series[i - 1] + series[i - 2])
series[2:20] returns values of series from index 2 included to 20 excluded
range(2,20) generates values 2 included to 20 ecluded
Related
I'd like to create a list that contains 15 values of number 1 and 60 values of number 2 and then I would like the list to be shuffled randomly in a way that there can never be more than one appearance of the value 1 in a row (e.g., it can never be 22212222122112212
Super appreciate any help or directions!
Here's how I would do it.
Generate a set of 15 indices such that none of the indices are adjacent.
In your final list, add 1 if the index is present in the set, otherwise add 2.
Here's what I said in code:
import random
random_list = []
one_indices = set()
while len(one_indices) != 15:
idx = random.randint(0, 74)
if not {idx, idx+1, idx-1} & one_indices:
one_indices.add(idx)
for idx in range(75):
if idx in one_indices:
random_list.append(1)
else:
random_list.append(2)
print(random_list)
Note:
if not {index, index+1, index-1} & one_indices: is just a fancier way of saying
if index not in one_indices and (index+1) not in one_indices and (index-1) not in one_indices:
The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]
I have a list of 3 lists each containing a random integer between 1 and 9:
lists= [[1,3,5],[2,4,6],[7,8,9]]
I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (assuming it is not the end of the list) is bigger or smaller.
for x in lists:
for i in x:
if i= user_choice-1:
Here I am stuck.
Lets say the user_choice is 3. I want the program to find the number 3-1=2 in the nested lists and then compare the number following 2 (in this case 4) to the user_choice.
if your list is
lists= [[1,3,5],[2,4,6],[7,8,9]]
to access the "1" you would type: lists[0][0]
to access the "8" you would type: lists[2][1]
*remember lists start their index at 0!!! :)
I am a little confused by what you are trying to achieve but you can get the index along with the element in a for loop by using:
for index, value in enumerate(my_list):
# Do stuff here
Or you can find the index of any element in a list with:
index = my_list.index(value)
Don't forget to change you = to a == in your if statement, by the way.
If I understand correctly, you want:
for x in lists:
for i in range(len(x)):
if x[i] == user_choice-1 and i < len(x)-1:
if x[i+1] > x[i]:
#Next value is bigger...
else:
#Next value is smaller...
lists= [[1,3,5],[2,4,6],[7,8,9]]
for x in lists:
index = 0
for i in x:
index += 1
if i == user_choice - 1:
print(x[index])
else:
(...)
Background: I have a lengthy script which calculates possible chemical formula for a given mass (based on a number of criteria), and outputs (amongst other things) a code which corresponds to the 'class' of compounds which that formula belong to. I calculate formula from batches of masses which should all be members of the same class. However, given instrumentation etc limits, it is possible to calculate several possible formula for each mass. I need to check if any of the classes calculated are common to all peaks, and if so, return the position of the match/etc.
I'm struggling with working out how to do an iterative if/for loop which checks every combination for matches (in an efficient way).
The image included summarises the issue:
Or on actual screenshots of the data structure:
image link here -
As you can see, I have a list called "formulae" which has a variable number of elements (in this case, 12).
Each element in formulae is a list, again with a variable number of elements.
Each element within those lists is a list, containing 15 7 elements. I wish to compare the 11th element amongst different elements.
I.e.
formulae[0][0][11] == formulae[1][0][11]
formulae[0][0][11] == formulae[1][1][11]
...
formulae[0][1][11] == formulae[11][13][11]
I imagine the answer might involve a couple of nested for and if statements, but I can't get my head around it.
I then will need to export the lists which matched (like formulae[0][0]) to a new array.
Unless I'm doing this wrong?
Thanks for any help!
EDIT:
1- My data structure has changed slightly, and I need to check that elements [?][?][4] and [?][?][5] and [?][?][6] and [?][?][7] all match the corresponding elements in another list.
I've attempted to adapt some of the code suggested, but can't quite get it to work...
check_O = 4
check_N = 5
check_S = 6
check_Na = 7
# start with base (left-hand) formula
nbase_i = len(formulae)
for base_i in range(len(formulae)): # length of first index
for base_j in range(len(formulae[base_i])): # length of second index
count = 0
# check against comparison (right-hand) formula
for comp_i in range(len(formulae)): # length of first index
for comp_j in range(len(formulae[comp_i])): # length of second index
if base_i != comp_i:
o_test = formulae[base_i][base_j][check_O] == formulae[comp_i][comp_j][check_O]
n_test = formulae[base_i][base_j][check_N] == formulae[comp_i][comp_j][check_N]
s_test = formulae[base_i][base_j][check_S] == formulae[comp_i][comp_j][check_S]
na_test = formulae[base_i][base_j][check_Na] == formulae[comp_i][comp_j][check_Na]
if o_test == n_test == s_test == na_test == True:
count = count +1
else:
count = 0
if count < nbase_i:
print base_i, base_j, comp_i,comp_j
o_test = formulae[base_i][base_j][check_O] == formulae[comp_i][comp_j][check_O]
n_test = formulae[base_i][base_j][check_N] == formulae[comp_i][comp_j][check_N]
s_test = formulae[base_i][base_j][check_S] == formulae[comp_i][comp_j][check_S]
na_test = formulae[base_i][base_j][check_Na] == formulae[comp_i][comp_j][check_Na]
if o_test == n_test == s_test == na_test == True:
count = count +1
else:
count = 0
elif count == nbase_i:
matching = "Got a match! " + "[" +str(base_i) + "][" + str(base_j) + "] matches with " + "[" + str(comp_i) + "][" + str(comp_j) +"]"
print matching
else:
count = 0
I would take a look at using in such as
agg = []
for x in arr:
matched = [y for y in arr2 if x in y]
agg.append(matched)
Prune's answer not right, should be like this:
check_index = 11
# start with base (left-hand) formula
for base_i in len(formulae): # length of first index
for base_j in len(formulae[base_i]): # length of second index
# check against comparison (right-hand) formula
for comp_i in len(formulae): # length of first index
for comp_j in len(formulae[comp_i]): # length of second index
if formulae[base_i][base_j][check_index] == formulae[comp_i][comp_j][check_index]:
print "Got a match"
# Here you add whatever info *you* need to identify the match
I'm not sure I fully understand your data structure, hence I'm not gonna write code here but propose an idea: how about an inverted index?
Like you scan once the lists creating kind of a summary of where the value you look for is.
You could create a dictionary composed as follows:
{
'ValueOfInterest1': [ (position1), (position2) ],
'ValueOfInterest2': [ (positionX) ]
}
Then at the end you can have a look at the dictionary and see if any of the values (basically lists) have length > 1.
Of course you'd need to find a way to create a position format that makes sense to you.
Just an idea.
Does this get you going?
check_index = 11
# start with base (left-hand) formula
for base_i in len(formulae): # length of first index
for base_j in len(formulae[0]): # length of second index
# check against comparison (right-hand) formula
for comp_i in len(formulae): # length of first index
for comp_j in len(formulae[0]): # length of second index
if formulae[base_i][base[j] == formulae[comp_i][comp_j]:
print "Got a match"
# Here you add whatever info *you* need to identify the match
I am making a function which will make a list which includes a histogram of a requested list and requested values to use as the values of the histogram. Values above the requested value are included last.
The program is working with a list that is sorted in ascending order numerically, but when a list that is not sorted is used as input, the program seems to discard random values and not evaluate in the same way.
the code:
def histogram(sample, binBoundaries):
c=0
if not binBoundaries:
li = [len(sample)]
return print(li)
for x in sample:
if x > binBoundaries[-1]: #if the value is greater than last bin
c = c+1 #number of values greater increases
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in sample: #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
for i in dic:
listofvalues.append(dic[i])
listofvalues.append(c)
print(listofvalues)
histogram([5, 4, 2, 3], [3])
this will result in an output of [1, 2], where the real output should be [2,2]
Is there something I'm just not seeing that is making the number not be calculated? Let me know where I have gone wrong if you could!
Your problem is that you are removing items from the list sample while you are iterating over it, this is a bad idea because it will result in skipping some elements.
Try taking out the line sample.remove(x), you should get the expected result. If you really do need to remove elements from the input list you should refactor to make sure you still check every element in the list. One option is to iterate over the list in reverse using for x in reversed(sample).
It also looks like you may be removing elements in the wrong place, sample.remove(x) looks like it should be inside of the if directly above it. Try the following code:
...
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in reversed(sample): #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
...