I'm a novice coding learner.
I am trying to extract numbers only in sequential from the list.
for example, my list is:
s = [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]
from this list I want only the numbers in sequential:
6,7,8,9,10, 13,14,15
so, I have the following code, but it doesn't work.
s = [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]
for i in s:
if s[i+1] - s[i] == 1:
print(s[i])
could you give me some idea? Thank you.
I just solved this question. thank you all for commenting.
s = [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]
a = []
for i in range(len(s)-1):
if s[i] - s[i+1] == -1:
a. append(s[i])
a. append(s[i+1])
print(set(a))
I would iterate through the list s storing the results in set res and at the end, if I want the results sorted, I would apply the sorted function on res to get the output.
Here is some code.
s= [2, 4, 6, 7, 8, 9, 10, 13, 14, 15]
res = set()
for i, num in enumerate(s[:-1]):
if num+1 == s[i+1]:
res = res.union({num} )
res = res.union({s[i+1]})
print(sorted(res))
print(res)
And the output is:
>>> [6, 7, 8, 9, 10, 13, 14, 15]
{6, 7, 8, 9, 10, 13, 14, 15}
Keep in mind that sets are NOT sorted even if they appear to be sorted. This is because sets DO NOT support indexes. So if you want your results sorted, make sure to apply the sorted function to be on the safe side.
you are looping over the items of the list instead of the indices of these items. To loop over the indices use:
if s[1] - s[0] == 1:
print(s[0])
for i in range(1,len(s)):
if s[i] - s[i-1] == 1:
print(s[i])
Related
#nested dictionary
card_values = {
"normal": [2, 3, 4, 5, 6, 7, 8, 9, 10],
"suited": {"J":10, "Q":10, "K":10, "A":11}
}
#code I wrote to try and iterate over the values
all_cards = []
for i in card_values:
for j in card_values[i]:
if j == "J" or j == "Q" or j == "K":
all_cards.append(10)
elif j =="A":
all_cards.append(11)
else:
all_cards.append(j)
print(all_cards)
without doing this, can we call the value corresponding to the key inside the nested dictionary in a for loop?
#output needed
all_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
I would make a set to get the unique values and then sort it.
card_values = {
"normal": [2, 3, 4, 5, 6, 7, 8, 9, 10],
"suited": {"J":10, "Q":10, "K":10, "A":11}
}
all_cards = sorted(
set(card_values["normal"])
| set(card_values["suited"].values())
)
print(all_cards)
You can use this snippet:
values = list(set(card_values["normal"] + list(card_values["suited"].values())))
this returns :
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
what each part of the code is doing:
We are first getting [2, 3, 4, 5, 6, 7, 8, 9, 10] from the "normal" key in card_values. Then we are getting only the values from the "suited" key in card_values and then converting them to a list which leaves [10, 10, 10, 11]. We then combine these two lists and use set() to remove duplicates.
I have tried two methods of creating groups of numbers and then dividing those groups into smaller groups of sequential numbers and selecting one.
The first method used lists, but they wouldn't divide the groups correctly.
# This program prints the wrong number of elements.
# I need the correct number of elements, and I want the list to
# deal with floats.
begin = 1
end = 22
num_groop = 2
num_in_groop = (begin + end) // num_groop
lis = []
# loop iterates through index making list from beginning to end
end = num_in_groop
for _ in np.arange(num_groop):
lis.append(list(np.arange(begin, end+1)))
begin += num_in_groop
end += num_in_groop
print('lis', lis,)
# a function to choose one group from the lis and print it
x_1 = lis[0]
x_2 = lis[1]
inp = input('Choose group 1 or 2 by entering 1 or 2\n')
intinp = int(inp)
def choosefunc():
if intinp == 1:
del x_2[:]
print('You chose group x_1 = ',x_1[:])
elif intinp == 2:
del x_1[:]
print('You chose group x_2 = ',x_2[:])
choosefunc()
print('lis is now', lis)
The problem with this is that when it's repeated to narrow down the groups, it divides only using integers. Though the original max number was 22, after repeating this twice, it produces the wrong number of lists. To be correct maths, it should be this:
The first division of the list into an even number is fine:
[[1,2,3,4,5,6,7,8,9,10,11], [12,13,14,15,16,17,18,19,20,21,22]].
Then when choosing one of these groups, choose the first, and divide by two again that's where the maths doesn't work. It should be this:
lis [[1, 2, 3, 4, 5, 5.5], [5.6, 7, 8, 9, 10, 11]]
But because it doesn't seem to handle floats, it is this:
lis [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]].
That's not correct maths. 22/2 = 11, and 11/2 = 5.5.
I want the lists to be of equal size.
# ---------------------------------------------------
When I try to solve the problem using lists, by using numpy arrays, I get an error that stops me from continuing.
# I tried to solve this problem using array but getting an error.
# TypeError: 'tuple' object cannot be interpreted as an integer.
import numpy as np
begin = 1
end = 22
num_groop = 2
num_in_groop = (begin + end) // num_groop
lis = np.array([])
print('lis is now', lis) # prints the new value for lis
end = num_in_groop
for _ in np.arange(num_groop):
print('line20, lis now', lis)
lis(np.arange(range((begin, end+1)))) #error
begin += num_in_groop
end += num_in_groop
print('lis', lis)
If [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]] is an acceptable split, then
def subdivide_list(a):
midpoint = len(a) // 2
return a[:midpoint], a[midpoint:]
lists = [list(range(1, 12))]
for x in range(3):
print(x, lists)
new_lists = []
for a in lists:
new_lists.extend(subdivide_list(a))
lists = new_lists
does what you want:
0 [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
1 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]
2 [[1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
EDIT
This also works for [list(range(1, 23))] (print adjusted to show the lengths of the lists):
0 [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]] [22]
1 [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]] [11, 11]
2 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22]] [5, 6, 5, 6]
array1=[3, 7, 11, 12, 15, 5, 1, 4]
array2=[14, 10, 9, 16, 2, 13, 6, 8]
I shuffled these arrays.
shuffled1 = sorted(array1, key=lambda k: random.random())
shuffled2 = sorted(array2, key=lambda k: random.random())
However, I do not want the same numbers to come to the same indexes again. For example: 3 and 14 at index 0, 7 and 10 at index 1. I don't want these numbers to be reciprocal again. All numbers need to be couple with another number.
For example:
shuffled1 =[1, 15, 4, 12, 7, 5, 3, 11]
shuffled2 =[13, 8, 9, 14, 2, 16, 6, 10]
İf shuffled arrays not like this, shuffle again.
As first step you can create a dictionary that will be used if shuffled lists array1 and array2 don't contain the values from initial state. Then we repeat shuffling until the condition is met.
For example:
from random import random
array1=[3, 7, 11, 12, 15, 5, 1, 4]
array2=[14, 10, 9, 16, 2, 13, 6, 8]
disallowed_dict = {}
for a, b in zip(array1, array2):
disallowed_dict.setdefault(a, []).append(b)
while any(b in disallowed_dict[a] for a, b in zip(array1, array2)):
array1 = sorted(array1, key=lambda _: random())
array2 = sorted(array2, key=lambda _: random())
print(array1)
print(array2)
Prints (for example):
[1, 15, 4, 7, 5, 11, 12, 3]
[16, 6, 10, 13, 8, 14, 9, 2]
I had completely missread the condition. Try this:
import numpy as np
from random import randint
array1=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def my_shuffle(array1, array2):
narray1 = np.array(array1)
idxs = []
for element in array1:
idx = randint(0,len(array1)-1)
while idx in idxs:
idx = randint(0,len(array1)-1)
idxs.append(idx)
narray1[idx] = element
narray2 = np.array(array2)
it = 0
idxs2 = []
for element in array2:
idx = randint(0,len(array2)-1)
while idx in idxs2 or idx == idxs[it]:
idx = randint(0,len(array2)-1)
idxs2.append(idx)
it+=1
narray2[idx] = element
return narray1, narray2
new1, new2 = my_shuffle(array1, array1)
print(f"{new1}\n{new2}")
I want to find sums of elements of the list by index0,index1 and index1,index2 and index2,index3, and so on.
Like:
my_list = [7, 5, 9, 4, 7, 11]
sums = [12, 14, 13, 11, 18] # 7+5, 5+9, 9+4, 4+7, 7+11
You just have to iterate through the indices:
l = [7, 5, 9, 4, 7, 11]
res = [l[i] + l[i+1] for i in range(len(l)-1)]
print(res)
Output:
[12, 14, 13, 11, 18]
You can use zip and sum for a functional solution:
# don't shadow the built-in `list`
l = [7,5,9,4,7,11]
# generate all neighboring pairs
pairs = zip(l, l[1:])
# generate all sums of pairs
sums = list(map(sum, pairs))
print(sums) # [12, 14, 13, 11, 18]
This works fine :)
list=[7,5,9,4,7,11]
aspSum = []
i = 0
while i<len(list)-1:
aspSum.append(list[i]+list[i+1])
i+=1
For example, we have task, select first ten even numbers in the list.
This can be easily done with simple for loop:
i = 0
list_even = []
for x in range(30):
if x % 2 == 0 and i < 10:
list_even.append(x)
i += 1
print(list_even) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] - correct!
How is it possible to do same with list-comprehension?
I have tried to use enumerate, but it counts all elements, not only that satisfy if statement, so I can't use the index from enumerate as counter.
list_even = [x for i, x in enumerate(range(30)) if x % 2 == 0 and i < 10]
print(list_even) # [0, 2, 4, 6, 8] - incorrect!
The task I describe is just example - I am writing article about list comprehensions and want to understand details and general solution for such class of tasks.
First just filter, then count only the already filtered values?
>>> [x for i, x in enumerate(x for x in range(30) if x % 2 == 0) if i < 10]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Though islice might be a better way to say you only want the first 10:
>>> list(itertools.islice((x for x in range(30) if x % 2 == 0), 10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Or just taking a slice of the full list, if time/space aren't an issue:
>>> [x for x in range(30) if x % 2 == 0][:10]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]